Пример #1
0
 /** Utility method to serialize an exception and its stack trace to simple HTML. */
 private final void serializeException(PrintWriter osw, Throwable t) {
   osw.write("<b>Exception</b>: " + t.toString() + "\n<br/><br/>");
   osw.write("<b>Stack trace:</b>");
   osw.write(
       "<pre style=\"margin: 1px solid red; padding: 3px; font-family: sans-serif; font-size: small;\">");
   t.printStackTrace(osw);
   osw.write("</pre>");
 }
Пример #2
0
 private void sendResponse(HttpServletResponse pResp, String pContentType, String pJsonTxt)
     throws IOException {
   setContentType(pResp, pContentType);
   pResp.setStatus(200);
   setNoCacheHeaders(pResp);
   PrintWriter writer = pResp.getWriter();
   writer.write(pJsonTxt);
 }
Пример #3
0
  /**
   * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the
   * exception message to the output stream.
   *
   * @param message Message to be printed to the logger and to the output stream.
   * @param t Exception that caused the error.
   */
  protected void filterError(String message, Throwable t) {
    log.error("XSLT filter error: " + message, t);
    if (false == origResponse.isCommitted()) {
      // Reset the buffer and previous status code.
      origResponse.reset();
      origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      origResponse.setContentType("text/html; charset=UTF-8");
    }

    // Response committed. Just push the error to the output stream.
    try {
      final OutputStream os = origResponse.getOutputStream();
      final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1"));
      osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->");
      osw.write("<h1 style=\"color: red; margin-top: 1em;\">");
      osw.write("Internal server exception");
      osw.write("</h1>");
      osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>");
      serializeException(osw, t);
      if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) {
        osw.write("<br/><br/><h2>ServletException root cause:</h2>");
        serializeException(osw, ((ServletException) t).getRootCause());
      }
      osw.write("</body></html>");
      osw.flush();
    } catch (IOException e) {
      // Not much to do in such case (connection broken most likely).
      log.debug("Filter error could not be returned to client.");
    }
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.write("<h1>Hello, <em>World!</em></h1>");
    writer.close();
  }
Пример #5
0
  /* write JS to stream */
  public void writeJavaScript(PrintWriter out, RequestProperties reqState) throws IOException {

    /* prefetch map "Loading" image */
    if (this.getProperties().getBoolean(PROP_MAP_LOADING, false)) {
      String mapLoadingImageURI = this.getProperties().getString(PROP_MAP_LOADING_IMAGE, null);
      if (!StringTools.isBlank(mapLoadingImageURI)) {
        out.write("<link rel=\"prefetch\" href=\"" + mapLoadingImageURI + "\">\n");
      }
    }

    /* JSMap variables */
    JavaScriptTools.writeStartJavaScript(out);
    this.writeJSVariables(out, reqState);
    JavaScriptTools.writeEndJavaScript(out);

    /* Subclass JavaScript includes */
    // links to MapProvider support are written by the subclass here
    this.writeJSIncludes(out, reqState);

    /* JSMap Custom included JavaScript */
    String jsMapURLs[] =
        StringTools.parseStringArray(this.getProperties().getString(PROP_javascript_src, ""), '\n');
    this.writeJSIncludes(out, reqState, jsMapURLs);

    /* JSMap Custom inline JavaScript */
    String jsMapInline =
        StringTools.trim(this.getProperties().getString(PROP_javascript_inline, null));
    if (!StringTools.isBlank(jsMapInline)) {
      JavaScriptTools.writeStartJavaScript(out);
      out.write("// --- Inline Javascript [" + this.getName() + "]\n");
      out.write(jsMapInline);
      out.write("\n");
      JavaScriptTools.writeEndJavaScript(out);
    }

    /* event CSV parsing code */
    JavaScriptTools.writeStartJavaScript(out);
    out.write(EventUtil.getInstance().getParseMapEventJS(reqState.isFleet(), reqState.getLocale()));
    JavaScriptTools.writeEndJavaScript(out);
  }
Пример #6
0
  /**
   * Process incoming HTTP POST requests
   *
   * @param request Object that encapsulates the request to the servlet
   * @param response Object that encapsulates the response from the servlet
   */
  public void performTask(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {
      String service = getServiceName(request);
      PrintWriter out = null;
      out = response.getWriter();
      out.write(res.getString(service));
      out.flush();
      out.close();
    } catch (Throwable t) {
    }
  }
Пример #7
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    PrintWriter out = response.getWriter();
    String location = URLDecoder.decode(request.getParameter("location"));
    String type = URLDecoder.decode(request.getParameter("type"));
    String unit = URLDecoder.decode(request.getParameter("unit"));
    String awsURL =
        "http://default-environment-ii9naedwp8.elasticbeanstalk.com/?location="
            + URLEncoder.encode(location)
            + "&type="
            + type
            + "&unit="
            + unit;
    // out.write(awsURL);
    String myurl = URLEncoder.encode(awsURL);
    // out.write("\n"+myurl);
    URL url = new URL(awsURL);
    URLConnection urlConnection = url.openConnection();

    InputStream awsResponse = urlConnection.getInputStream();
    InputStreamReader iSReader = new InputStreamReader(awsResponse);
    StringBuffer sb = new StringBuffer();
    String xmlLine;
    BufferedReader buf = new BufferedReader(iSReader);
    try {
      while ((xmlLine = buf.readLine()) != null) {
        sb.append(xmlLine);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    xmlLine = sb.toString();

    response.setContentType("application/json; charset=UTF-8");
    int indent = 6;
    try {
      JSONObject jsonObj = XML.toJSONObject(xmlLine);
      String json1 = jsonObj.toString(indent);
      out.write(json1);
    } catch (JSONException ex) {
      ex.printStackTrace();
    }
  }
 private void getServices(HttpServletResponse res) {
   InputStream is = null;
   try {
     URL url = ctx.getResource(resourcesDir + XHP_CONFIG);
     // use classpath if not found locally.
     if (url == null)
       url = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + XHP_CONFIG);
     is = url.openStream();
   } catch (Exception ex) {
     try {
       getLogger().severe("XmlHttpProxyServlet error loading xhp.json : " + ex);
       PrintWriter writer = res.getWriter();
       writer.write(
           "XmlHttpProxyServlet Error: Error loading xhp.json. Make sure it is available in the /resources directory of your applicaton.");
       writer.flush();
     } catch (Exception iox) {
     }
   }
   services = xhp.loadServices(is);
 }
Пример #9
0
  public void handlePageBody(PageContext pc) throws ServletException, IOException {
    ServletContext context = pc.getServletContext();
    Document doc = null;
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      doc = builder.newDocument();
    } catch (Exception e) {
      throw new ServletException(e);
    }

    Element rootElem = doc.createElement("xaf");
    doc.appendChild(rootElem);

    try {
      DatabaseContextFactory.createCatalog(pc, rootElem);
      transform(pc, doc, ACE_CONFIG_ITEM_PROPBROWSERXSL);
    } catch (NamingException e) {
      PrintWriter out = pc.getResponse().getWriter();
      out.write(e.toString());
      e.printStackTrace(out);
    }
  }
Пример #10
0
 /**
  * Process an HTML get or post.
  *
  * @exception ServletException From inherited class.
  * @exception IOException From inherited class.
  */
 public void scanOutXML(PrintWriter out, String strDirectory) throws IOException {
   File dir = new File(strDirectory);
   if (!dir.isDirectory()) return;
   File[] rgFiles = dir.listFiles(new Filter());
   out.write("<directory>");
   out.write("		<name>" + strDirectory + "</name>");
   for (int x = 0; x < rgFiles.length; x++) {
     for (int y = x + 1; y < rgFiles.length; y++) {
       if (rgFiles[x].getName().compareTo(rgFiles[y].getName()) > 0) {
         File file = rgFiles[x];
         rgFiles[x] = rgFiles[y];
         rgFiles[y] = file;
       }
     }
   }
   for (int i = 0; i < rgFiles.length; i++) {
     File file = rgFiles[i];
     out.write("	<file>");
     out.write("		<name>" + file.getName() + "</name>");
     out.write("		<size>" + file.length() + "</size>");
     out.write("	</file>");
   }
   out.write("</directory>");
 }
Пример #11
0
  public static void writeMenu(
      PrintWriter out,
      RequestProperties reqState,
      String menuID,
      boolean expandableMenu,
      boolean showIcon,
      int descriptionType,
      boolean showMenuHelp)
      throws IOException {
    PrivateLabel privLabel = reqState.getPrivateLabel();
    Locale locale = reqState.getLocale();
    String parentPageName = null;
    Account account = reqState.getCurrentAccount();

    /* disable menu help if menu description is not displayed */
    boolean showInline = false;
    if (descriptionType == ExpandMenu.DESC_NONE) {
      showMenuHelp = false;
      showInline = true;
    }

    /* sub style classes */
    String topMenuID =
        !StringTools.isBlank(menuID) ? menuID : (expandableMenu ? "expandMenu" : "fixedMenu");
    String groupClass = "menuGroup";
    String leafClass = "itemLeaf";
    String leafDescClass = "itemLeafDesc";
    String helpClass = "itemLeafHelp";
    String helpPadClass = "itemLeafHelpPad";
    String leafIconClass = "itemLeafIcon";

    /* start menu */
    out.println("<ul id='" + topMenuID + "'>");

    /* iterate through menu groups */
    Map<String, MenuGroup> menuMap = privLabel.getMenuGroupMap();
    for (String mgn : menuMap.keySet()) {
      MenuGroup mg = menuMap.get(mgn);
      if (!mg.showInTopMenu()) {
        // skip this group
        // Print.logInfo("Skipping menu group: %s", mgn);
        continue;
      }

      boolean didDisplayGroup = false;
      for (WebPage wp : mg.getWebPageList(reqState)) {
        String menuName = wp.getPageName();
        String iconURI = showIcon ? wp.getMenuIconImage() : null; // may be blank/null
        String menuHelp = wp.getMenuHelp(reqState, parentPageName);
        String url = wp.encodePageURL(reqState); // , RequestProperties.TRACK_BASE_URI());

        /* skip login page */
        if (menuName.equalsIgnoreCase(Constants.PAGE_LOGIN)) {
          // omit login
          // Print.logInfo("Skipping login page: %s", menuName);
          continue;
        }

        /* skip sysAdmin pages */
        if (wp.systemAdminOnly() && !Account.isSystemAdmin(account)) {
          continue;
        }

        /* skip pages that are not ok to display */
        if (!wp.isOkToDisplay(reqState)) {
          continue;
        }

        /* menu description */
        String menuDesc = null;
        switch (descriptionType) {
          case DESC_NONE:
            menuDesc = null;
            break;
          case DESC_SHORT:
            menuDesc = wp.getNavigationDescription(reqState);
            break;
          case DESC_LONG:
          default:
            menuDesc = wp.getMenuDescription(reqState, parentPageName);
            break;
        }

        /* skip this menu item? */
        if (StringTools.isBlank(menuDesc) && StringTools.isBlank(iconURI)) {
          // Print.logWarn("Menu name has no description: %s", menuName);
          continue;
        }

        /* start menu group */
        if (!didDisplayGroup) {
          // open Menu Group
          didDisplayGroup = true;
          out.write("<li class='" + groupClass + "'>" + mg.getTitle(locale) + "\n");
          if (showInline) {
            out.write("<br><table cellpadding='0' cellspacing='0' border='0'><tr>\n");
          } else {
            out.write("<ul>\n"); // <-- start menu sub group
          }
        }

        /* menu anchor/link */
        String anchorStart = "<a";
        if (!StringTools.isBlank(menuHelp)) {
          anchorStart += " title=\"" + menuHelp + "\"";
        }
        String target =
            StringTools.blankDefault(wp.getTarget(), "_self"); // ((WebPageURL)wp).getTarget();
        if (target.startsWith("_")) {
          anchorStart += " href=\"" + url + "\"";
          anchorStart += " target=\"" + target + "\"";
        } else {
          PixelDimension pixDim = wp.getWindowDimension();
          if (pixDim != null) {
            int W = pixDim.getWidth();
            int H = pixDim.getHeight();
            anchorStart +=
                " onclick=\"javascript:openFixedWindow('"
                    + url
                    + "','"
                    + target
                    + "',"
                    + W
                    + ","
                    + H
                    + ")\"";
            anchorStart += " style=\"text-decoration: underline; color: blue; cursor: pointer;\"";
          } else {
            anchorStart += " href=\"" + url + "\"";
            anchorStart += " target=\"" + target + "\"";
          }
        }
        anchorStart += ">";

        /* inline? */
        if (showInline) {

          /* menu icon (will not be blank here) */
          out.write("<td class='" + leafIconClass + "'>");
          if (!StringTools.isBlank(iconURI)) {
            out.write(
                anchorStart + "<img class='" + leafIconClass + "' src='" + iconURI + "'/></a>");
          } else {
            out.write("&nbsp;");
          }
          out.write("</td>");

        } else {

          /* start menu list item */
          out.write("<li class='" + leafClass + "'>");

          /* special case for non-icons */
          if (StringTools.isBlank(iconURI)) {

            /* menu description/help */
            if (!StringTools.isBlank(menuDesc)) {
              out.write(
                  "<span class='" + leafDescClass + "'>" + anchorStart + menuDesc + "</a></span>");
              if (showMenuHelp && !StringTools.isBlank(menuHelp)) {
                out.write("<br>");
                out.write("<span class='" + helpPadClass + "'>" + menuHelp + "</span>");
              }
            }

          } else {
            // this section may not appear as expected on IE

            /* start table */
            out.write("<table class='" + leafClass + "' cellpadding='0' cellspacing='0'>");
            out.write("<tr>");

            /* menu icon */
            if (!StringTools.isBlank(iconURI)) {
              out.write("<td class='" + leafIconClass + "'>");
              out.write(
                  anchorStart + "<img class='" + leafIconClass + "' src='" + iconURI + "'/></a>");
              out.write("</td>");
            }

            /* menu description/help */
            if (!StringTools.isBlank(menuDesc)) {
              out.write("<td class='" + leafDescClass + "'>");
              out.write(
                  "<span class='" + leafDescClass + "'>" + anchorStart + menuDesc + "</a></span>");
              if (showMenuHelp && !StringTools.isBlank(menuHelp)) {
                out.write("<br>");
                out.write("<span class='" + helpClass + "'>" + menuHelp + "</span>");
              }
              out.write("</td>");
            }

            /* end table */
            out.write("</tr>");
            out.write("</table>");
          }

          /* end menu list item */
          out.write("</li>\n");
        }
      }

      /* end menu group */
      if (didDisplayGroup) {
        if (showInline) {
          out.write("</tr></table>\n");
        } else {
          out.write("</ul>\n");
        }
        out.write("</li>\n");
      }
    }

    /* end of menu */
    out.write("</ul>\n");

    /* init menu if expandable */
    if (expandableMenu) {
      out.write(
          "<script type=\"text/javascript\"> new ExpandMenu('" + topMenuID + "'); </script>\n");
    }
  }
  @Override
  public void render(RenderRequest portletReq, RenderResponse portletResp)
      throws PortletException, IOException {
    LOGGER.entering(LOG_CLASS, "main portlet render entry");

    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    PrintWriter writer = portletResp.getWriter();

    PortletSession ps = portletReq.getPortletSession();
    String msg =
        (String)
            ps.getAttribute(
                RESULT_ATTR_PREFIX + "DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse",
                APPLICATION_SCOPE);
    if (msg != null) {
      writer.write("<p>" + msg + "</p><br/>\n");
      ps.removeAttribute(
          RESULT_ATTR_PREFIX + "DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse",
          APPLICATION_SCOPE);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_containsHeader */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.containsHeader must return false"         */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_containsHeader", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeRedirectURL1 */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.encodeRedirectURL must return null"       */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeRedirectURL1",
              aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeRedirectUrl */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.encodeRedirectUrl must return null"       */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeRedirectUrl",
              aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeURL1 */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.encodeURL must provide the same           */
    /* functionality as ActionResponse.encodeURL"                           */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeURL1", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeUrl */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.encodeUrl must provide the same           */
    /* functionality as ActionResponse.encodeURL"                           */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeUrl", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getBufferSize */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.getBufferSize must return 0"              */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getBufferSize", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getCharacterEncoding */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.getCharacterEncoding must return null"    */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getCharacterEncoding",
              aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getContentType */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.getContentType must return null"          */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getContentType", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getLocale */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.getLocale must return null"               */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getLocale", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_isCommitted */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.isCommitted must return true"             */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_isCommitted", aurl);
      tb.writeTo(writer);
    }
  }
Пример #13
0
  /* write mapping support JS to stream */
  protected void writeJSVariables(PrintWriter out, RequestProperties reqState) throws IOException {
    // This var initilizations must not use any functions defined in 'jsmap.js'
    PrivateLabel privLabel = reqState.getPrivateLabel();
    I18N i18n = privLabel.getI18N(JSMap.class);
    Locale locale = reqState.getLocale();
    GeoPoint dftCenter = this.getDefaultCenter(null);
    boolean isFleet = reqState.isFleet();
    Account account = reqState.getCurrentAccount();
    long maxPushpins = this.getMaxPushpins(reqState);
    out.write("// --- Map support Javascript [" + this.getName() + "]\n");
    JavaScriptTools.writeJSVar(out, "MAP_PROVIDER_NAME", this.getName());

    /* properties */
    boolean wrotePropHeader = false;
    RTProperties rtp = this.getProperties();
    for (Iterator<?> i = rtp.keyIterator(); i.hasNext(); ) {
      Object key = i.next();
      if (!this._skipPropKey(key)) {
        if (!wrotePropHeader) {
          // out.write("\n");
          out.write("// Defined properties\n");
          wrotePropHeader = true;
        }
        String val[] = StringTools.parseStringArray(rtp.getProperty(key, "").toString(), '\n');
        String propVar = "PROP_" + key.toString().replace('.', '_').replace('-', '_');
        if (val.length == 1) {
          if (StringTools.isDouble(val[0], true)
              || StringTools.isLong(val[0], true)
              || StringTools.isBoolean(val[0], true)) {
            JavaScriptTools.writeJSVar(out, propVar, val[0], false);
          } else {
            JavaScriptTools.writeJSVar(out, propVar, val[0]);
          }
        } else if (val.length > 1) {
          JavaScriptTools.writeJSVar(out, propVar, StringTools.join(val, "\\n"));
        }
      }
    }

    /* speed units */
    Account.SpeedUnits speedUnits = reqState.getSpeedUnits();
    boolean speedIsKph = speedUnits.equals(Account.SpeedUnits.KPH);
    double altUnitsMult = speedIsKph ? 1.0 : GeoPoint.FEET_PER_METER;
    String altUnitsName =
        speedIsKph
            ? i18n.getString("JSMap.altitude.meters", "Meters")
            : i18n.getString("JSMap.altitude.feet", "Feet");

    /* constants (these do not change during the user session) */
    out.write("// Element IDs\n");
    JavaScriptTools.writeJSVar(out, "MAP_ID", this.getMapID());
    JavaScriptTools.writeJSVar(out, "ID_DETAIL_TABLE", ID_DETAIL_TABLE);
    JavaScriptTools.writeJSVar(out, "ID_DETAIL_CONTROL", ID_DETAIL_CONTROL);
    JavaScriptTools.writeJSVar(out, "ID_LAT_LON_DISPLAY", ID_LAT_LON_DISPLAY);
    JavaScriptTools.writeJSVar(out, "ID_DISTANCE_DISPLAY", ID_DISTANCE_DISPLAY);
    JavaScriptTools.writeJSVar(out, "ID_LATEST_EVENT_DATE", ID_LATEST_EVENT_DATE);
    JavaScriptTools.writeJSVar(out, "ID_LATEST_EVENT_TIME", ID_LATEST_EVENT_TIME);
    JavaScriptTools.writeJSVar(out, "ID_LATEST_EVENT_TMZ", ID_LATEST_EVENT_TMZ);
    JavaScriptTools.writeJSVar(out, "ID_LATEST_BATTERY", ID_LATEST_BATTERY);
    JavaScriptTools.writeJSVar(out, "ID_MESSAGE_TEXT", ID_MESSAGE_TEXT);
    out.write("// Geozone IDs\n");
    JavaScriptTools.writeJSVar(out, "ID_ZONE_LATITUDE_", ID_ZONE_LATITUDE_);
    JavaScriptTools.writeJSVar(out, "ID_ZONE_LONGITUDE_", ID_ZONE_LONGITUDE_);
    JavaScriptTools.writeJSVar(out, "ID_ZONE_RADIUS_M", ID_ZONE_RADIUS_M);
    out.write("// Session constants\n");
    JavaScriptTools.writeJSVar(out, "PUSHPINS_SHOW", rtp.getBoolean(PROP_map_pushpins, true));
    JavaScriptTools.writeJSVar(out, "MAX_PUSH_PINS", maxPushpins);
    JavaScriptTools.writeJSVar(out, "MAX_CREATION_AGE_SEC", rtp.getInt(PROP_map_maxCreationAge, 0));
    JavaScriptTools.writeJSVar(out, "MAP_WIDTH", this.getDimension().getWidth());
    JavaScriptTools.writeJSVar(out, "MAP_HEIGHT", this.getDimension().getHeight());
    JavaScriptTools.writeJSVar(out, "IS_FLEET", isFleet);
    JavaScriptTools.writeJSVar(
        out, "SHOW_SAT_COUNT", rtp.getBoolean(PROP_detail_showSatCount, false));
    JavaScriptTools.writeJSVar(out, "SHOW_SPEED", rtp.getBoolean(PROP_info_showSpeed, true));
    JavaScriptTools.writeJSVar(
        out, "COMBINE_SPEED_HEAD", rtp.getBoolean(PROP_combineSpeedHeading, true));
    JavaScriptTools.writeJSVar(out, "SHOW_ALTITUDE", rtp.getBoolean(PROP_info_showAltitude, false));
    JavaScriptTools.writeJSVar(out, "SHOW_ADDR", reqState.getShowAddress());
    JavaScriptTools.writeJSVar(
        out, "INCL_BLANK_ADDR", rtp.getBoolean(PROP_info_inclBlankAddress, true));
    JavaScriptTools.writeJSVar(
        out, "SHOW_OPT_FIELDS", rtp.getBoolean(PROP_info_showOptionalFields, true));
    JavaScriptTools.writeJSVar(
        out, "INCL_BLANK_OPT_FIELDS", rtp.getBoolean(PROP_info_inclBlankOptFields, true));
    JavaScriptTools.writeJSVar(
        out, "LATLON_FORMAT", Account.getLatLonFormat(account).getIntValue());
    JavaScriptTools.writeJSVar(
        out, "DISTANCE_KM_MULT", reqState.getDistanceUnits().getMultiplier());
    JavaScriptTools.writeJSVar(out, "SPEED_KPH_MULT", speedUnits.getMultiplier());
    JavaScriptTools.writeJSVar(out, "SPEED_UNITS", speedUnits.toString(locale));
    JavaScriptTools.writeJSVar(out, "ALTITUDE_METERS_MULT", altUnitsMult);
    JavaScriptTools.writeJSVar(out, "ALTITUDE_UNITS", altUnitsName);
    JavaScriptTools.writeJSVar(out, "TIME_ZONE", reqState.getTimeZoneString(null)); // long
    JavaScriptTools.writeJSVar(
        out,
        "DEFAULT_CENTER",
        "{ lat:" + dftCenter.getLatitude() + ", lon:" + dftCenter.getLongitude() + " }",
        false);
    JavaScriptTools.writeJSVar(out, "DEFAULT_ZOOM", this.getDefaultZoom(JSMap.DEFAULT_ZOOM, false));
    JavaScriptTools.writeJSVar(out, "PUSHPIN_ZOOM", this.getDefaultZoom(JSMap.PUSHPIN_ZOOM, true));
    JavaScriptTools.writeJSVar(out, "MAP_AUTHORIZATION", this.getAuthorization());
    JavaScriptTools.writeJSVar(
        out, "SCROLL_WHEEL_ZOOM", rtp.getBoolean(PROP_scrollWheelZoom, false));
    JavaScriptTools.writeJSVar(out, "DEFAULT_VIEW", rtp.getString(PROP_map_view, "").toLowerCase());
    JavaScriptTools.writeJSVar(out, "ROUTE_LINE_SHOW", rtp.getBoolean(PROP_map_routeLine, true));
    JavaScriptTools.writeJSVar(
        out, "ROUTE_LINE_COLOR", rtp.getString(PROP_map_routeLine_color, "#FF2222"));
    JavaScriptTools.writeJSVar(
        out, "ROUTE_LINE_ARROWS", rtp.getBoolean(PROP_map_routeLine_arrows, false));
    JavaScriptTools.writeJSVar(
        out,
        "ROUTE_SNAP_TO_ROAD",
        rtp.getBoolean(PROP_map_routeLine_snapToRoad, false)); // Google V2 only
    JavaScriptTools.writeJSVar(out, "REPLAY_INTERVAL", this.getReplayInterval());
    JavaScriptTools.writeJSVar(out, "REPLAY_SINGLE", this.getReplaySinglePushpin());

    /* address title */
    String adrTitles[] = reqState.getAddressTitles();
    String adrTitle = ListTools.itemAt(adrTitles, 0, null);

    /* device title */
    String devTitles[] = reqState.getDeviceTitles();
    String devTitle = ListTools.itemAt(devTitles, 0, null);

    /* labels */
    out.write("// Localized Text/Labels\n");
    JavaScriptTools.writeJSVar(
        out,
        "HEADING",
        "new Array("
            + "\""
            + GeoPoint.CompassHeading.N.toString(locale)
            + "\","
            + "\""
            + GeoPoint.CompassHeading.NE.toString(locale)
            + "\","
            + "\""
            + GeoPoint.CompassHeading.E.toString(locale)
            + "\","
            + "\""
            + GeoPoint.CompassHeading.SE.toString(locale)
            + "\","
            + "\""
            + GeoPoint.CompassHeading.S.toString(locale)
            + "\","
            + "\""
            + GeoPoint.CompassHeading.SW.toString(locale)
            + "\","
            + "\""
            + GeoPoint.CompassHeading.W.toString(locale)
            + "\","
            + "\""
            + GeoPoint.CompassHeading.NW.toString(locale)
            + "\")",
        false);
    JavaScriptTools.writeJSVar(out, "TEXT_INFO_DATE", i18n.getString("JSMap.info.date", "Date"));
    JavaScriptTools.writeJSVar(out, "TEXT_INFO_GPS", i18n.getString("JSMap.info.gps", "GPS"));
    JavaScriptTools.writeJSVar(out, "TEXT_INFO_SATS", i18n.getString("JSMap.info.sats", "#Sats"));
    JavaScriptTools.writeJSVar(out, "TEXT_INFO_SPEED", i18n.getString("JSMap.info.speed", "Speed"));
    JavaScriptTools.writeJSVar(out, "TEXT_INFO_HEADING", GeoPoint.GetHeadingTitle(locale));
    JavaScriptTools.writeJSVar(
        out, "TEXT_INFO_ALTITUDE", i18n.getString("JSMap.info.altitude", "Altitude"));
    JavaScriptTools.writeJSVar(
        out, "TEXT_INFO_STOP_TIME", i18n.getString("JSMap.info.stopTime", "Stop Time"));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_INFO_ADDR",
        !StringTools.isBlank(adrTitle)
            ? adrTitle
            : i18n.getString("JSMap.info.address", "Address"));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_DEVICE",
        !StringTools.isBlank(devTitle) ? devTitle : i18n.getString("JSMap.device", "Device"));
    JavaScriptTools.writeJSVar(out, "TEXT_DATE", i18n.getString("JSMap.dateTime", "Date/Time"));
    JavaScriptTools.writeJSVar(out, "TEXT_CODE", i18n.getString("JSMap.code", "Status"));
    JavaScriptTools.writeJSVar(out, "TEXT_LATLON", i18n.getString("JSMap.latLon", "Lat/Lon"));
    JavaScriptTools.writeJSVar(out, "TEXT_SATCOUNT", i18n.getString("JSMap.satCount", "#Sats"));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_ADDR",
        !StringTools.isBlank(adrTitle) ? adrTitle : i18n.getString("JSMap.address", "Address"));
    JavaScriptTools.writeJSVar(out, "TEXT_SPEED", reqState.getSpeedUnits().toString(locale));
    JavaScriptTools.writeJSVar(out, "TEXT_HEADING", i18n.getString("JSMap.heading", "Heading"));
    JavaScriptTools.writeJSVar(out, "TEXT_DISTANCE", reqState.getDistanceUnits().toString(locale));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_TIMEOUT",
        i18n.getString("JSMap.sessionTimeout", "Your session has timed-out.\nPlease login ..."));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_PING_OK",
        i18n.getString(
            "JSMap.pingDevice.ok",
            "A command request has been sent.\nThe {0} should respond shortly ...",
            devTitles));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_PING_ERROR",
        i18n.getString(
            "JSMap.pingDevice.err",
            "The command request failed.\nThe {0} may not support this feature ...",
            devTitles));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_MAXPUSHPINS_ALERT",
        i18n.getString(
            "JSMap.maxPushpins.err",
            "The maximum number of allowed pushpins has been exceeded.\n"
                + " [max={0}] Not all pushpins may be displayed on this map.\n"
                + "Adjust the 'From' time to see remaining pushpins",
            String.valueOf(maxPushpins)));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_MAXPUSHPINS_MSG",
        i18n.getString(
            "JSMap.maxPushpins.msg",
            "Only partial data displayed.  The maximum allowed pushpins has been reached.<BR>"
                + "Adjust the Date/Time range accordingly to view the remaining pushpins."));
    JavaScriptTools.writeJSVar(
        out, "TEXT_UNAVAILABLE", i18n.getString("JSMap.unavailable", "unavailable"));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_showLocationDetails",
        i18n.getString("JSMap.showLocationDetails", "Show Location Details"));
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_hideLocationDetails",
        i18n.getString("JSMap.hideLocationDetails", "Hide Location Details"));

    /* map "Loading ..." */
    JavaScriptTools.writeJSVar(
        out,
        "TEXT_LOADING_MAP_POINTS",
        (rtp.getBoolean(PROP_MAP_LOADING, false)
            ? i18n.getString("JSMap.loadingMapPoints", "Loading Map Points ...")
            : null));
    JavaScriptTools.writeJSVar(
        out, "MAP_LOADING_IMAGE_URI", rtp.getString(PROP_MAP_LOADING_IMAGE, null));

    /* icons/shadows */
    JSMap.writePushpinArray(out, reqState);

    /* constants (these do not change during the user session) */
    out.write("// Geozone support constants\n");
    JavaScriptTools.writeJSVar(out, "jsvGeozoneMode", false);
    JavaScriptTools.writeJSVar(out, "MAX_ZONE_RADIUS_M", Geozone.MAX_RADIUS_METERS);
    JavaScriptTools.writeJSVar(out, "MIN_ZONE_RADIUS_M", Geozone.MIN_RADIUS_METERS);
    JavaScriptTools.writeJSVar(
        out, "DETAIL_REPORT", this.isFeatureSupported(FEATURE_DETAIL_REPORT));
    JavaScriptTools.writeJSVar(
        out, "DETAIL_INFO_BOX", this.isFeatureSupported(FEATURE_DETAIL_INFO_BOX));
    JavaScriptTools.writeJSVar(out, "TEXT_METERS", GeoPoint.DistanceUnits.METERS.toString(locale));

    /* variables */
    out.write("// TrackMap Vars\n");
    JavaScriptTools.writeJSVar(out, "jsvPoiPins", null);
    JavaScriptTools.writeJSVar(out, "jsvDataSets", null);
    JavaScriptTools.writeJSVar(out, "jsvDetailPoints", null);
    JavaScriptTools.writeJSVar(out, "jsvDetailVisible", false);
    JavaScriptTools.writeJSVar(
        out,
        "jsvDetailAscending",
        privLabel.getBooleanProperty(PrivateLabel.PROP_TrackMap_detailAscending, true));
    JavaScriptTools.writeJSVar(
        out,
        "jsvDetailCenterPushpin",
        privLabel.getBooleanProperty(PrivateLabel.PROP_TrackMap_detailCenterPushpin, false));

    /* last update time */
    TimeZone tmz = reqState.getTimeZone();
    String dateFmt =
        (account != null) ? account.getDateFormat() : BasicPrivateLabel.getDefaultDateFormat();
    String timeFmt =
        (account != null) ? account.getTimeFormat() : BasicPrivateLabel.getDefaultTimeFormat();
    DateTime today = new DateTime(tmz);
    JavaScriptTools.writeJSVar(out, "jsvTodayEpoch", today.getTimeSec());
    JavaScriptTools.writeJSVar(
        out,
        "jsvTodayYMD",
        "{ YYYY:"
            + today.getYear(tmz)
            + ", MM:"
            + today.getMonth1(tmz)
            + ", DD:"
            + today.getDayOfMonth(tmz)
            + " }",
        false);
    JavaScriptTools.writeJSVar(out, "jsvTodayDateFmt", today.format(dateFmt, tmz));
    JavaScriptTools.writeJSVar(out, "jsvTodayTimeFmt", today.format(timeFmt, tmz));
    JavaScriptTools.writeJSVar(out, "jsvTodayTmzFmt", today.format("z", tmz));

    /* last event time */
    out.write("// Last event time\n");
    DateTime lastEventTime = reqState.getLastEventTime();
    if (lastEventTime != null) {
      JavaScriptTools.writeJSVar(out, "jsvLastEventEpoch", lastEventTime.getTimeSec());
      JavaScriptTools.writeJSVar(
          out,
          "jsvLastEventYMD",
          "{ YYYY:"
              + lastEventTime.getYear(tmz)
              + ", MM:"
              + lastEventTime.getMonth1(tmz)
              + ", DD:"
              + lastEventTime.getDayOfMonth(tmz)
              + " }",
          false);
      JavaScriptTools.writeJSVar(out, "jsvLastEventDateFmt", lastEventTime.format(dateFmt, tmz));
      JavaScriptTools.writeJSVar(out, "jsvLastEventTimeFmt", lastEventTime.format(timeFmt, tmz));
      JavaScriptTools.writeJSVar(out, "jsvLastEventTmzFmt", lastEventTime.format("z", tmz));
      JavaScriptTools.writeJSVar(out, "jsvLastBatteryLevel", 0L);
      JavaScriptTools.writeJSVar(out, "jsvLastSignalStrength", 0L);
    } else {
      JavaScriptTools.writeJSVar(out, "jsvLastEventEpoch", 0L);
      JavaScriptTools.writeJSVar(out, "jsvLastEventYMD", null);
      JavaScriptTools.writeJSVar(out, "jsvLastEventDateFmt", null);
      JavaScriptTools.writeJSVar(out, "jsvLastEventTimeFmt", null);
      JavaScriptTools.writeJSVar(out, "jsvLastEventTmzFmt", null);
      JavaScriptTools.writeJSVar(out, "jsvLastBatteryLevel", 0.0);
      JavaScriptTools.writeJSVar(out, "jsvLastSignalStrength", 0.0);
    }

    /* map pointers */
    out.write("// Map vars\n");
    JavaScriptTools.writeJSVar(out, "jsmapElem", null);
    JavaScriptTools.writeJSVar(out, "jsmap", null);
  }
Пример #14
0
  public void writeLandingPage(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String landingPage = getNewTokenLandingPage();

    /** default to current page * */
    if (landingPage == null) {
      StringBuilder sb = new StringBuilder();

      sb.append(request.getContextPath());
      sb.append(request.getServletPath());

      landingPage = sb.toString();
    }

    /** create auto posting form * */
    StringBuilder sb = new StringBuilder();

    sb.append("<html>\r\n");
    sb.append("<head>\r\n");
    sb.append("<title>OWASP CSRFGuard Project - New Token Landing Page</title>\r\n");
    sb.append("</head>\r\n");
    sb.append("<body>\r\n");
    sb.append("<script type=\"text/javascript\">\r\n");
    sb.append("var form = document.createElement(\"form\");\r\n");
    sb.append("form.setAttribute(\"method\", \"post\");\r\n");
    sb.append("form.setAttribute(\"action\", \"");
    sb.append(landingPage);
    sb.append("\");\r\n");

    /** only include token if needed * */
    if (isProtectedPage(landingPage)) {
      sb.append("var hiddenField = document.createElement(\"input\");\r\n");
      sb.append("hiddenField.setAttribute(\"type\", \"hidden\");\r\n");
      sb.append("hiddenField.setAttribute(\"name\", \"");
      sb.append(getTokenName());
      sb.append("\");\r\n");
      sb.append("hiddenField.setAttribute(\"value\", \"");
      sb.append(getTokenValue(request, landingPage));
      sb.append("\");\r\n");
      sb.append("form.appendChild(hiddenField);\r\n");
    }

    sb.append("document.body.appendChild(form);\r\n");
    sb.append("form.submit();\r\n");
    sb.append("</script>\r\n");
    sb.append("</body>\r\n");
    sb.append("</html>\r\n");

    String code = sb.toString();

    /** setup headers * */
    response.setContentType("text/html");
    response.setContentLength(code.length());

    /** write auto posting form * */
    OutputStream output = null;
    PrintWriter writer = null;

    try {
      output = response.getOutputStream();
      writer = new PrintWriter(output);

      writer.write(code);
      writer.flush();
    } finally {
      Writers.close(writer);
      Streams.close(output);
    }
  }
  @Override
  public void render(RenderRequest portletReq, RenderResponse portletResp)
      throws PortletException, IOException {
    LOGGER.entering(LOG_CLASS, "main portlet render entry");

    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    PrintWriter writer = portletResp.getWriter();

    writer.write(
        "<div id=\"DispatcherTests_SPEC2_19_ForwardServletResource\">no resource output.</div>\n");
    ResourceURL resurl = portletResp.createResourceURL();
    resurl.setCacheability(PAGE);
    writer.write("<script>\n");
    writer.write("(function () {\n");
    writer.write("   var xhr = new XMLHttpRequest();\n");
    writer.write("   xhr.onreadystatechange=function() {\n");
    writer.write("      if (xhr.readyState==4 && xhr.status==200) {\n");
    writer.write(
        "         document.getElementById(\"DispatcherTests_SPEC2_19_ForwardServletResource\").innerHTML=xhr.responseText;\n");
    writer.write("      }\n");
    writer.write("   };\n");
    writer.write("   xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n");
    writer.write("   xhr.send();\n");
    writer.write("})();\n");
    writer.write("</script>\n");
  }
  public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;
    PrintWriter writer = null;
    String serviceKey = null;

    try {
      BufferedReader in = req.getReader();
      String line = null;
      while ((line = in.readLine()) != null) {
        if (bodyContent == null) bodyContent = new StringBuffer();
        bodyContent.append(line);
      }
    } catch (Exception e) {
    }
    try {
      if (requireSession) {
        // check to see if there was a session created for this request
        // if not assume it was from another domain and blow up
        // Wrap this to prevent Portlet exeptions
        HttpSession session = req.getSession(false);
        if (session == null) {
          res.setStatus(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
      serviceKey = req.getParameter("id");
      // only to preven regressions - Remove before 1.0
      if (serviceKey == null) serviceKey = req.getParameter("key");
      // check if the services have been loaded or if they need to be reloaded
      if (services == null || configUpdated()) {
        getServices(res);
      }
      String urlString = null;
      String xslURLString = null;
      String userName = null;
      String password = null;
      String format = "json";
      String callback = req.getParameter("callback");
      String urlParams = req.getParameter("urlparams");
      String countString = req.getParameter("count");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          JSONObject service = services.getJSONObject(serviceKey);
          // default to the service default if no url parameters are specified
          if (urlParams == null && service.has("defaultURLParams")) {
            urlParams = service.getString("defaultURLParams");
          }
          String serviceURL = service.getString("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } else {
          writer = res.getWriter();
          if (serviceKey == null)
            writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
          else
            writer.write(
                "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
          writer.flush();
          return;
        }
      } catch (Exception ex) {
        getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
      }

      Map paramsMap = new HashMap();
      paramsMap.put("format", format);
      // do not allow for xdomain unless the context level setting is enabled.
      if (callback != null && allowXDomain) {
        paramsMap.put("callback", callback);
      }
      if (countString != null) {
        paramsMap.put("count", countString);
      }

      InputStream xslInputStream = null;

      if (urlString == null) {
        writer = res.getWriter();
        writer.write(
            "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
        writer.flush();
        return;
      }
      // default to JSON
      res.setContentType(responseContentType);
      out = res.getOutputStream();
      // get the stream for the xsl stylesheet
      if (xslURLString != null) {
        // check the web root for the resource
        URL xslURL = null;
        xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
        // if not in the web root check the classpath
        if (xslURL == null) {
          xslURL =
              XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
        }
        if (xslURL != null) {
          xslInputStream = xslURL.openStream();
        } else {
          String message =
              "Could not locate the XSL stylesheet provided for service id "
                  + serviceKey
                  + ". Please check the XMLHttpProxy configuration.";
          getLogger().severe(message);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        writer.flush();
      } catch (java.io.IOException ix) {
        ix.printStackTrace();
      }
      return;
    } finally {
      try {
        if (out != null) out.close();
        if (writer != null) writer.close();
      } catch (java.io.IOException iox) {
      }
    }
  }
Пример #17
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType(XML_RESPONSE_HEADER); // Talkback happens in XML form.
    response.setCharacterEncoding("UTF-8"); // Unicode++
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = null; // The talkback buffer.

    // handle startrecord
    Integer startRecord = 0;

    if (!(request.getParameter("startRecord") == null)) {
      try {
        startRecord = Integer.parseInt(request.getParameter("startRecord")) - 1;
      } catch (NumberFormatException e) {
        startRecord = 0;
      }
    }

    // maximumrecords
    Integer maximumRecords = Integer.parseInt(this.config.getProperty("default_maximumRecords"));
    if (!(request.getParameter("maximumRecords") == null)) {
      maximumRecords = Integer.parseInt(request.getParameter("maximumRecords"));
    }

    // operation
    String operation = request.getParameter("operation");

    // x_collection
    String x_collection = request.getParameter("x-collection");
    if (x_collection == null) x_collection = this.config.getProperty("default_x_collection");
    if (x_collection == null) operation = null;

    // sortkeys
    String sortKeys = request.getParameter("sortKeys");

    // sortorder
    String sortOrder = request.getParameter("sortOrder");

    // recordschema
    String recordSchema = request.getParameter("recordSchema");
    if (recordSchema == null) recordSchema = "dc";

    if (recordSchema.equalsIgnoreCase("dcx")) {
      recordSchema = "dcx";
    }

    if (recordSchema.equalsIgnoreCase("solr")) {
      recordSchema = "solr";
    }

    // query request
    String query = request.getParameter("query");
    String q = request.getParameter("q");

    // who is requestor ?
    String remote_ip = request.getHeader("X-FORWARDED-FOR");

    if (remote_ip == null) {
      remote_ip = request.getRemoteAddr().trim();
    } else {
      remote_ip = request.getHeader("X-FORWARDED-FOR");
    }

    // handle debug
    Boolean debug = Boolean.parseBoolean(request.getParameter("debug"));
    if (!debug) {
      out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    }

    // handle query
    if ((query == null) && (q != null)) {
      query = q;
    } else {
      if ((query != null) && (q == null)) {
        q = query;
      } else {
        operation = null;
      }
    }

    // handle operation
    if (operation == null) {
      if (query != null) {
        operation = "searchRetrieve";
      } else {
        operation = "explain";
      }
    }

    //  searchRetrieve
    if (operation.equalsIgnoreCase("searchRetrieve")) {
      if (query == null) {
        operation = "explain";
        log.debug(operation + ":" + query);
      }
    }

    // start talking back.
    String[] sq = {""};
    String solrquery = "";

    // facet

    String facet = null;
    List<FacetField> fct = null;

    if (request.getParameter("facet") != null) {
      facet = request.getParameter("facet");
      log.debug("facet : " + facet);
    }

    if (operation == null) {
      operation = "searchretrieve";
    } else { // explain response
      if (operation.equalsIgnoreCase("explain")) {
        log.debug("operation = explain");
        out.write("<srw:explainResponse xmlns:srw=\"http://www.loc.gov/zing/srw/\">");
        out.write("</srw:explainResponse>");
      } else { // DEBUG routine
        operation = "searchretrieve";

        String triplequery = null;

        if (query.matches(".*?\\[.+?\\].*?")) { // New symantic syntax
          triplequery = symantic_query(query);
          query = query.split("\\[")[0] + " " + triplequery;
          log.fatal(triplequery);

          solrquery = CQLtoLucene.translate(query, log, config);
        } else {
          solrquery = CQLtoLucene.translate(query, log, config);
        }
        log.debug(solrquery);

        if (debug == true) {
          response.setContentType(HTML_RESPONSE_HEADER);
          out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
          out.write("<html><body>\n\n");
          out.write("'" + remote_ip + "'<br>\n");
          out.write("<form action='http://www.kbresearch.nl/kbSRU'>");
          out.write("<input type=text name=q value='" + query + "' size=120>");
          out.write("<input type=hidden name=debug value=True>");
          out.write("<input type=submit>");
          out.write("<table border=1><tr><td>");
          out.write("q</td><td>" + query + "</td></tr><tr>");
          out.write("<td>query out</td><td>" + URLDecoder.decode(solrquery) + "</td></tr>");
          out.write(
              "<tr><td>SOLR_URL</td><td> <a href='"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/?q="
                  + solrquery
                  + "'>"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/select/?q="
                  + solrquery
                  + "</a><br>"
                  + this.config.getProperty("solr_url")
                  + solrquery
                  + "</td></tr>");
          out.write(
              "<b>SOLR_QUERY</b> : <BR> <iframe width=900 height=400 src='"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/../?q="
                  + solrquery
                  + "'></iframe><BR>");
          out.write(
              "<b>SRU_QUERY</b> : <BR> <a href="
                  + this.config.getProperty("baseurl")
                  + "?q="
                  + query
                  + "'>"
                  + this.config.getProperty("baseurl")
                  + "?q="
                  + query
                  + "</a><br><iframe width=901 height=400 src='http://www.kbresearch.nl/kbSRU/?q="
                  + query
                  + "'></iframe><BR>");
          out.write(
              "<br><b>JSRU_QUERY</b> : <BR><a href='http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection="
                  + x_collection
                  + "'>http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection=GGC</a><br><iframe width=900 height=400 src='http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection=GGC'></iframe>");

        } else { // XML SearchRetrieve response
          String url =
              this.config.getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl");
          String buffer = "";
          CommonsHttpSolrServer server = null;
          server = new CommonsHttpSolrServer(url);
          log.fatal("URSING " + url);
          server.setParser(new XMLResponseParser());
          int numfound = 0;
          try {
            SolrQuery do_query = new SolrQuery();
            do_query.setQuery(solrquery);
            do_query.setRows(maximumRecords);
            do_query.setStart(startRecord);

            if ((sortKeys != null) && (sortKeys.length() > 1)) {
              if (sortOrder != null) {
                if (sortOrder.equals("asc")) {
                  do_query.setSortField(sortKeys, SolrQuery.ORDER.asc);
                }
                if (sortOrder.equals("desc")) {
                  do_query.setSortField(sortKeys, SolrQuery.ORDER.desc);
                }
              } else {
                for (String str : sortKeys.trim().split(",")) {
                  str = str.trim();
                  if (str.length() > 1) {
                    if (str.equals("date")) {
                      do_query.setSortField("date_date", SolrQuery.ORDER.desc);
                      log.debug("SORTORDERDEBUG | DATE! " + str + " | ");
                      break;
                    } else {
                      do_query.setSortField(str + "_str", SolrQuery.ORDER.asc);
                      log.debug("SORTORDERDEBUG | " + str + " | ");
                      break;
                    }
                  }
                }
              }
            }

            if (facet != null) {
              if (facet.indexOf(",") > 1) {
                for (String str : facet.split(",")) {
                  if (str.indexOf("date") > 1) {
                    do_query.addFacetField(str);
                  } else {
                    do_query.addFacetField(str);
                  }
                  // do_query.setParam("facet.method", "enum");
                }
                // q.setFacetSort(false);
              } else {
                do_query.addFacetField(facet);
              }
              do_query.setFacet(true);
              do_query.setFacetMinCount(1);
              do_query.setFacetLimit(-1);
            }

            log.fatal(solrquery);

            QueryResponse rsp = null;
            boolean do_err = false;
            boolean do_sugg = false;
            SolrDocumentList sdl = null;
            String diag = "";
            StringBuffer suggest = new StringBuffer("");

            String content = "1";

            SolrQuery spellq = do_query;
            try {
              rsp = server.query(do_query);
            } catch (SolrServerException e) {
              String header = this.SRW_HEADER.replaceAll("\\$numberOfRecords", "0");
              out.write(header);
              diag = this.SRW_DIAG.replaceAll("\\$error", e.getMessage());
              do_err = true;
              rsp = null;
            }

            log.fatal("query done..");
            if (!(do_err)) { // XML dc response

              SolrDocumentList docs = rsp.getResults();
              numfound = (int) docs.getNumFound();
              int count = startRecord;
              String header =
                  this.SRW_HEADER.replaceAll("\\$numberOfRecords", Integer.toString(numfound));
              out.write(header);
              out.write("<srw:records>");

              Iterator<SolrDocument> iter = rsp.getResults().iterator();

              while (iter.hasNext()) {
                count += 1;
                if (recordSchema.equalsIgnoreCase("dc")) {
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                  out.write(
                      "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" xmlns:facets=\"info:srw/extension/4/facets\" >");
                  StringBuffer result = new StringBuffer("");

                  construct_lucene_dc(result, resultDoc);

                  out.write(result.toString());
                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }

                if (recordSchema.equalsIgnoreCase("solr")) {
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/solr</srw:recordSchema>");
                  out.write("<srw:recordData xmlns:expand=\"http://www.kbresearch.nl/expand\">");
                  StringBuffer result = new StringBuffer("");
                  construct_lucene_solr(result, resultDoc);
                  out.write(result.toString());

                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }

                if (recordSchema.equalsIgnoreCase("dcx")) { // XML dcx response
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                  out.write(
                      "<srw:recordData><srw_dc:dc xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/marc.relators/\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");

                  String dcx_data =
                      helpers.getOAIdcx(
                          "http://services.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                          log);
                  if (x_collection.equalsIgnoreCase("ggc-thes")) {
                    dcx_data =
                        helpers.getOAIdcx(
                            "http://serviceso.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                            log);
                  }

                  if (!(dcx_data.length() == 0)) {
                    out.write(dcx_data);
                  } else {
                    // Should not do this!!

                    out.write("<srw:record>");
                    out.write("<srw:recordPacking>xml</srw:recordPacking>");
                    out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                    out.write(
                        "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" >");
                    StringBuffer result = new StringBuffer("");

                    construct_lucene_dc(result, resultDoc);

                    out.write(result.toString());
                    out.write("</srw:recordData>");
                    out.write(
                        "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                    out.write("</srw:record>");
                  }

                  out.write("</srw_dc:dc>");

                  StringBuffer expand_data;
                  boolean expand = false;

                  if (content.startsWith("GGC-THES:AC:")) {
                    String tmp_content = "";
                    tmp_content = content.replaceFirst("GGC-THES:AC:", "");
                    log.fatal("calling get");
                    expand_data =
                        new StringBuffer(
                            helpers.getExpand(
                                "http://www.kbresearch.nl/general/lod_new/get/"
                                    + tmp_content
                                    + "?format=rdf",
                                log));
                    log.fatal("get finini");

                    if (expand_data.toString().length() > 4) {

                      out.write(
                          "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                      out.write(expand_data.toString());
                      expand = true;
                    }
                  } else {
                    expand_data =
                        new StringBuffer(
                            helpers.getExpand(
                                "http://www.kbresearch.nl/ANP.cgi?q=" + content, log));
                    if (expand_data.toString().length() > 0) {
                      if (!expand) {
                        out.write(
                            "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                        expand = true;
                      }
                      out.write(expand_data.toString());
                    }
                  }
                  if (expand) {
                    out.write("</srw_dc:expand>");
                  }

                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }
              }
            }

            if ((do_err) || (numfound == 0)) {
              log.fatal("I haz suggestions");

              try {
                spellq.setParam("spellcheck", true);
                spellq.setQueryType("/spell");
                server = new CommonsHttpSolrServer(url);
                rsp = server.query(spellq);
                sdl = rsp.getResults();
                SpellCheckResponse spell;
                spell = rsp.getSpellCheckResponse();
                List<SpellCheckResponse.Suggestion> suggestions = spell.getSuggestions();
                if (suggestions.isEmpty() == false) {
                  suggest.append("<srw:extraResponseData>");
                  suggest.append("<suggestions>");

                  for (SpellCheckResponse.Suggestion sugg : suggestions) {
                    suggest.append("<suggestionfor>" + sugg.getToken() + "</suggestionfor>");
                    for (String item : sugg.getSuggestions()) {
                      suggest.append("<suggestion>" + item + "</suggestion>");
                    }
                    suggest.append("</suggestions>");
                    suggest.append("</srw:extraResponseData>");
                  }
                  do_sugg = true;
                }
              } catch (Exception e) {
                rsp = null;
                // log.fatal(e.toString());
              }
              ;
            }
            ;

            if (!do_err) {
              if (facet != null) {

                try {
                  fct = rsp.getFacetFields();
                  out.write("<srw:facets>");

                  for (String str : facet.split(",")) {
                    out.write("<srw:facet>");
                    out.write("<srw:facetType>");
                    out.write(str);
                    out.write("</srw:facetType>");

                    for (FacetField f : fct) {
                      log.debug(f.getName());
                      // if (f.getName().equals(str+"_str") || (f.getName().equals(str+"_date")) ) {
                      List<FacetField.Count> facetEnties = f.getValues();
                      for (FacetField.Count fcount : facetEnties) {
                        out.write("<srw:facetValue>");
                        out.write("<srw:valueString>");
                        out.write(helpers.xmlEncode(fcount.getName()));
                        out.write("</srw:valueString>");
                        out.write("<srw:count>");
                        out.write(Double.toString(fcount.getCount()));
                        out.write("</srw:count>");
                        out.write("</srw:facetValue>");
                        //   }
                      }
                    }
                    out.write("</srw:facet>");
                  }
                  out.write("</srw:facets>");
                  startRecord += 1;
                } catch (Exception e) {
                }

                // log.fatal(e.toString()); }
              }
            } else {
              out.write(diag);
            }
            out.write("</srw:records>"); // SearchRetrieve response footer
            String footer = this.SRW_FOOTER.replaceAll("\\$query", helpers.xmlEncode(query));
            footer = footer.replaceAll("\\$startRecord", (startRecord).toString());
            footer = footer.replaceAll("\\$maximumRecords", maximumRecords.toString());
            footer = footer.replaceAll("\\$recordSchema", recordSchema);
            if (do_sugg) {
              out.write(suggest.toString());
            }
            out.write(footer);
          } catch (MalformedURLException e) {
            out.write(e.getMessage());
          } catch (IOException e) {
            out.write("TO ERR is Human");
          }
        }
      }
    }
    out.close();
  }
Пример #18
0
 /* write mapping support JS to stream */
 public static void writePushpinArray(PrintWriter out, RequestProperties reqState)
     throws IOException {
   MapProvider mapProv = reqState.getMapProvider();
   out.write("// Icon URLs\n");
   out.write("var jsvPushpinIcon = new Array(\n");
   OrderedMap<String, PushpinIcon> iconMap = mapProv.getPushpinIconMap(reqState);
   for (Iterator<String> k = iconMap.keyIterator(); k.hasNext(); ) {
     String key = k.next();
     PushpinIcon ppi = iconMap.get(key);
     String I = ppi.getIconURL();
     boolean iE = ppi.getIconEval();
     int iW = ppi.getIconWidth();
     int iH = ppi.getIconHeight();
     int iX = ppi.getIconHotspotX();
     int iY = ppi.getIconHotspotY();
     String S = ppi.getShadowURL();
     int sW = ppi.getShadowWidth();
     int sH = ppi.getShadowHeight();
     String B = ppi.getBackgroundURL();
     int bW = ppi.getBackgroundWidth();
     int bH = ppi.getBackgroundHeight();
     int bX = ppi.getBackgroundOffsetX();
     int bY = ppi.getBackgroundOffsetY();
     out.write("    {");
     out.write(" key:\"" + key + "\",");
     if (iE) {
       out.write(" iconEval:\"" + I + "\",");
     } else {
       out.write(" iconURL:\"" + I + "\",");
     }
     out.write(" iconSize:[" + iW + "," + iH + "],");
     out.write(" iconOffset:[" + iX + "," + iY + "],");
     out.write(" iconHotspot:[" + iX + "," + iY + "],");
     out.write(" shadowURL:\"" + S + "\",");
     out.write(" shadowSize:[" + sW + "," + sH + "]");
     if (!StringTools.isBlank(B)) {
       out.write(",");
       out.write(" bgURL:\"" + B + "\",");
       out.write(" bgSize:[" + bW + "," + bH + "],");
       out.write(" bgOffset:[" + bX + "," + bY + "]");
     }
     out.write(" }");
     if (k.hasNext()) {
       out.write(",");
     }
     out.write("\n");
   }
   out.write("    );\n");
 }