public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    res.setContentType("text/html");
    try {
      PrintWriter pw = res.getWriter();
      pw.println("<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE></head>");
      pw.println(
          "<body><br><br><br><form name=modifyuser method=post action='http://peers:8080/servlet/showUser')");
      v = U.allUsers();
      pw.println("<table align='center' border=0> <tr><td>");
      pw.println(
          "Select User Name To Modify</td><td><SELECT id=select1 name=uid style='HEIGHT: 22px; LEFT: 74px; TOP: 222px; WIDTH: 155px'>");
      pw.println("<OPTION selected value=''></OPTION>");
      for (i = 0; i < v.size(); i++)
        pw.println(
            "<OPTION value="
                + (String) v.elementAt(i)
                + ">"
                + (String) v.elementAt(i)
                + "</OPTION>");
      pw.println(
          "</SELECT></td></tr><tr><td></td><td><input type='submit' name='submit' value='Submit'></td></tr></table></form></body></html>");
      pw.flush();
      pw.close();

    } catch (Exception e) {
    }
  }
Пример #2
0
  void sendHTML(
      HttpServletRequest request,
      HttpServletResponse response,
      String script,
      Exception scriptError,
      Object scriptResult,
      StringBuffer scriptOutput,
      boolean capture)
      throws IOException {
    // Format the output using a simple templating utility
    SimpleTemplate st = new SimpleTemplate(BshServlet.class.getResource("page.template"));
    st.replace("version", getBshVersion());

    // String requestURI = HttpUtils.getRequestURL( request ).toString()
    // I was told this should work
    String requestURI = request.getRequestURI();

    st.replace("servletURL", requestURI);
    if (script != null) st.replace("script", script);
    else st.replace("script", exampleScript);
    if (capture) st.replace("captureOutErr", "CHECKED");
    else st.replace("captureOutErr", "");
    if (script != null)
      st.replace(
          "scriptResult", formatScriptResultHTML(script, scriptResult, scriptError, scriptOutput));

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    st.write(out);
    out.flush();
  }
Пример #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.");
    }
  }
Пример #4
0
  private void level2level3catalog(
      RadarType radarType,
      String pathInfo,
      PrintWriter pw,
      HttpServletRequest req,
      HttpServletResponse res)
      throws IOException {

    try {
      String type;
      if (pathInfo.contains("level2")) type = radarType.toString() + "/level2";
      else type = radarType.toString() + "/level3";

      ByteArrayOutputStream os = new ByteArrayOutputStream(10000);
      InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false);
      factory.writeXML(cat, os, true);
      InvCatalogImpl tCat = factory.readXML(new ByteArrayInputStream(os.toByteArray()), catURI);

      Iterator parents = tCat.getDatasets().iterator();
      while (parents.hasNext()) {
        ArrayList<InvDatasetImpl> delete = new ArrayList<InvDatasetImpl>();
        InvDatasetImpl top = (InvDatasetImpl) parents.next();
        Iterator tDatasets = top.getDatasets().iterator();
        while (tDatasets.hasNext()) {
          InvDatasetImpl ds = (InvDatasetImpl) tDatasets.next();
          if (ds instanceof InvDatasetScan) {
            InvDatasetScan ids = (InvDatasetScan) ds;
            if (ids.getPath() == null) continue;
            if (ids.getPath().contains(type)) {
              ids.setXlinkHref(ids.getPath() + "/dataset.xml");
            } else {
              delete.add(ds);
            }
          }
        }
        // remove datasets
        for (InvDatasetImpl idi : delete) {
          top.removeDataset(idi);
        }
      }
      if (pathInfo.endsWith("xml")) {
        String catAsString = factory.writeXML(tCat);
        pw.println(catAsString);
        pw.flush();
      } else {
        HtmlWriter.getInstance().writeCatalog(req, res, tCat, true); // show catalog as HTML
      }
    } catch (Throwable e) {
      log.error("RadarServer.level2level3catalog failed", e);
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return;
  }
Пример #5
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) {
    }
  }
Пример #6
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String zip = request.getParameter("zip");
   WeatherService weatherService = new WeatherService();
   PrintWriter out = response.getWriter();
   try {
     out.println(weatherService.retrieveForecast(zip));
   } catch (Exception e) {
     out.println("Error Retrieving Forecast: " + e.getMessage());
   }
   out.flush();
   out.close();
 }
Пример #7
0
 void sendRaw(
     HttpServletRequest request,
     HttpServletResponse response,
     Exception scriptError,
     Object scriptResult,
     StringBuffer scriptOutput)
     throws IOException {
   response.setContentType("text/plain");
   PrintWriter out = response.getWriter();
   if (scriptError != null) out.println("Script Error:\n" + scriptError);
   else out.println(scriptOutput.toString());
   out.flush();
 }
Пример #8
0
 protected void writeResponse(
     final HttpServletResponse httpServletResponse,
     final SimpleStatusResponse simpleStatusResponse) {
   Gson gson = new Gson();
   try {
     httpServletResponse.setContentType("application/json; charset=utf-8");
     _log.debug("Serializing: " + simpleStatusResponse);
     final PrintWriter writer = httpServletResponse.getWriter();
     gson.toJson(simpleStatusResponse.getResponseStatus(), writer);
     writer.flush();
     writer.close();
   } catch (Exception e) {
     _log.error("Error while writing response: " + e.getMessage(), e);
   }
 }
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    res.setContentType("text/html");
    PrintWriter pw = res.getWriter();
    PR.deleteProduct(req.getParameter("prid"));
    pw.println("<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE></head>");
    pw.println("<table align='center' border=0>");
    pw.println("<tr col span=2><th>Web-Enabled Automated Manufacturing Process</th></tr>");
    pw.println("<tr><td>Product ID:</td><td>" + req.getParameter("prid") + "</td></tr>");

    pw.println("<tr><td>Product data is deleted Click on OK to Continue</td></tr>");
    pw.println(
        "<tr><td align=center><a href='http://peers:8080/servlet/deleteProduct' target='main'>OK</a></td>");
    pw.println("<td></td></tr>");
    pw.println("</table></form></body></html>");
    pw.flush();
    pw.close();
  }
 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);
 }
Пример #11
0
 protected void writeResponseGenericWithDate(
     final HttpServletResponse httpServletResponse,
     final Date lastModified,
     final int expirationTime,
     final Object object) {
   Gson gson = new Gson();
   try {
     httpServletResponse.setContentType("application/json; charset=utf-8");
     if (lastModified != null) {
       httpServletResponse.addHeader("Expires", createDateHeader(expirationTime));
       httpServletResponse.addHeader("Last-Modified", toHttpDate(lastModified));
     }
     _log.debug("Serializing: " + object);
     final PrintWriter writer = httpServletResponse.getWriter();
     gson.toJson(object, writer);
     writer.flush();
     writer.close();
   } catch (Exception e) {
     _log.error("Error while writing response: " + e.getMessage(), e);
   }
 }
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   res.setContentType("text/html");
   hs = req.getSession(true);
   PrintWriter pw = res.getWriter();
   uid = req.getParameter("did");
   if (!uid.equals("")) {
     v = D.getDealer(uid);
     pw.println(
         "<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE><script language=javascript>function set() {");
     pw.println(
         "document.deldealer.select1.value='"
             + (String) v.elementAt(4)
             + "'} </script></head><P align=center><FONT color=deepskyblue size=4><STRONG>MODIFY&nbsp;DEALER </STRONG></FONT></P> ");
     pw.println(
         "<body onLoad=set()><br><br><form name=deldealer method=post action='http://peers:8080/servlet/DelDealer'>");
     pw.println(
         "<center><TABLE border=0 cellPadding=1 cellSpacing=1 width='75%' style='HEIGHT: 147px; WIDTH: 248px'>");
     pw.println(
         "<TR><TD>DealerId&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD><TD><INPUT id=text1 name=did value="
             + (String) v.elementAt(0)
             + "></TD></TR>");
     pw.println(
         "<TR><TD>DealerName</TD><TD><INPUT id=text2 name=dname value="
             + (String) v.elementAt(1)
             + " ></TD></TR><TR><TD>DealerAddress</TD>");
     pw.println(
         "<TD><INPUT id=text2 type=text name=daddr value="
             + (String) v.elementAt(2)
             + "></TD></TR><TR><TD>CreditLimit</TD><TD><INPUT id=text4 name=cl value="
             + v.get(3).toString());
     pw.println(
         "></TD></TR><TR><TD><P>Staus</P></TD><td><SELECT id=select1 name=status style='HEIGHT: 22px; LEFT: 1px; TOP: 1px; WIDTH: 136px'> <OPTION ");
     pw.println(
         "selected value=''></OPTION><OPTION value=Active>Active</OPTION><OPTION value=Inactive>Inactive</OPTION></SELECT><INPUT id=submit1 name=submit1 style='LEFT: 151px; TOP: 318px' type=submit value=Delete></TD></TR>");
     pw.println("</table></center></form></body></html>");
     pw.flush();
     pw.close();
   }
 }
Пример #13
0
  /**
   * Send a permanent redirect (HTTP status 301 "Moved Permanently") response with the given target
   * path.
   *
   * <p>The given target path may be relative or absolute. If it is relative, it will be resolved
   * against the request URL.
   *
   * @param targetPath the path to which the client is redirected.
   * @param req the HttpServletRequest
   * @param res the HttpServletResponse
   * @throws IOException if can't write the response.
   */
  public static void sendPermanentRedirect(
      String targetPath, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // Absolute URL needed so resolve the target path against the request URL.
    URI uri;
    try {
      uri = new URI(req.getRequestURL().toString());
    } catch (URISyntaxException e) {
      log.error(
          "sendPermanentRedirect(): Bad syntax on request URL <" + req.getRequestURL() + ">.", e);
      log.info(
          "sendPermanentRedirect(): "
              + UsageLog.closingMessageForRequestContext(
                  HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0));
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return;
    }
    String absolutePath = uri.resolve(targetPath).toString();
    absolutePath = res.encodeRedirectURL(absolutePath);

    res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    res.addHeader("Location", absolutePath);

    String title = "Permanently Moved - 301";
    String body =
        new StringBuilder()
            .append("<p>")
            .append("The requested URL <")
            .append(req.getRequestURL())
            .append("> has been permanently moved (HTTP status code 301).")
            .append(" Instead, please use the following URL: <a href=\"")
            .append(absolutePath)
            .append("\">")
            .append(absolutePath)
            .append("</a>.")
            .append("</p>")
            .toString();
    String htmlResp =
        new StringBuilder()
            .append(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag())
            .append("<head><title>")
            .append(title)
            .append("</title></head><body>")
            .append("<h1>")
            .append(title)
            .append("</h1>")
            .append(body)
            .append("</body></html>")
            .toString();

    log.info("sendPermanentRedirect(): redirect to " + absolutePath);
    log.info(
        "sendPermanentRedirect(): "
            + UsageLog.closingMessageForRequestContext(
                HttpServletResponse.SC_MOVED_PERMANENTLY, htmlResp.length()));

    // Write the catalog out.
    PrintWriter out = res.getWriter();
    res.setContentType("text/html");
    out.print(htmlResp);
    out.flush();
  }
Пример #14
0
  // get pathInfo and parmameters from servlet call
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    PrintWriter pw = null;
    try {
      long startms = System.currentTimeMillis();

      if (cat == null || rm.nexradList == null) { // something major wrong
        res.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            "radarServer Radar Station/Catalog initialization problem");
        return;
      }
      // setup
      String pathInfo = req.getPathInfo();
      if (pathInfo == null) pathInfo = "";
      RadarType radarType = RadarType.nexrad; // default
      if (pathInfo.indexOf('/', 1) > 1) {
        String rt = pathInfo.substring(1, pathInfo.indexOf('/', 1));
        radarType = RadarType.valueOf(rt);
      }
      // default is xml, assume errors will be recorded by logger from this point
      if (!pathInfo.endsWith("html")) {
        pw = res.getWriter();
        res.setContentType("text/xml; charset=iso-8859-1"); // default
      }
      // radar  query
      if (req.getQueryString() != null) {
        // log.debug("RadarServer query ="+ req.getQueryString() );
        if (log.isDebugEnabled())
          log.debug("<documentation>\n" + req.getQueryString() + "</documentation>\n");
        rm.radarQuery(radarType, req, res, pw);
        if (log.isDebugEnabled())
          log.debug("after doGet " + (System.currentTimeMillis() - startms));
        pw.flush();
        return;
      }
      // return radarCollections catalog   xml or html
      if (pathInfo.startsWith("/catalog.xml") || pathInfo.startsWith("/dataset.xml")) {
        InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false); // no validation
        String catAsString = factory.writeXML(cat);
        pw.println(catAsString);
        res.setStatus(HttpServletResponse.SC_OK);
        pw.flush();
        return;
      } else if (pathInfo.startsWith("/catalog.html") || pathInfo.startsWith("/dataset.html")) {
        try {
          int i =
              HtmlWriter.getInstance().writeCatalog(req, res, cat, true); // show catalog as HTML
        } catch (Exception e) {
          log.error("Radar HtmlWriter failed ", e);
          res.sendError(
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "radarServer HtmlWriter error " + pathInfo);
          return;
        }
        return;
      }
      // level2 and level3 catalog/dataset
      if (pathInfo.contains("level2/catalog.")
          || pathInfo.contains("level3/catalog.")
          || pathInfo.contains("level2/dataset.")
          || pathInfo.contains("level3/dataset.")) {
        level2level3catalog(radarType, pathInfo, pw, req, res);
        return;
      }
      // return stations of dataset
      if (pathInfo.endsWith("stations.xml")) {
        pathInfo = pathInfo.replace("/stations.xml", "");
        Element rootElem = new Element("stationsList");
        Document doc = new Document(rootElem);
        doc = rm.stationsXML(radarType, doc, rootElem, pathInfo.substring(1));
        XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
        pw.println(fmt.outputString(doc));
        pw.flush();
        return;
      }
      // return specific dataset information, ie IDD
      if (pathInfo.endsWith("dataset.xml") || pathInfo.endsWith("catalog.xml")) {
        datasetInfoXml(radarType, pathInfo, pw);
        return;
      }
      // needs work nobody using it now
      // return Dataset information in html form format
      if (pathInfo.endsWith("dataset.html") || pathInfo.endsWith("catalog.html")) {
        datasetInfoHtml(radarType, pathInfo, pw, res);
        return;
      }
      // mal formed request with no exceptions
      res.sendError(HttpServletResponse.SC_NOT_FOUND);

    } catch (FileNotFoundException e) {
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND);

    } catch (Throwable e) {
      log.error("RadarServer.doGet failed", e);
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  } // end doGet
Пример #15
0
  private void datasetInfoXml(RadarType radarType, String pathInfo, PrintWriter pw)
      throws IOException {

    try {
      pw.println(
          "<catalog xmlns=\"http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" name=\"Radar Data\" version=\"1.0.1\">\n");
      // add service
      pw.println(
          "  <service name=\"radarServer\" base=\"/thredds/radarServer/\" serviceType=\"DQC\" />\n");
      pathInfo = pathInfo.replace("/dataset.xml", "");
      pathInfo = pathInfo.replace("/catalog.xml", "");
      if (pathInfo.startsWith("/")) pathInfo = pathInfo.substring(1);
      for (int i = 0; i < datasets.size(); i++) {
        InvDatasetScan ds = (InvDatasetScan) datasets.get(i);
        if (!(pathInfo.equals(ds.getPath()))) {
          continue;
        }

        pw.println("  <dataset ID=\"" + ds.getID() + "\" serviceName=\"radarServer\">");

        pw.println("    <urlpath>" + ds.getPath() + "</urlpath>");
        pw.println("    <dataType>" + ds.getDataType() + "</dataType>");

        pw.println("    <dataFormat>" + ds.getDataFormatType() + "</dataFormat>");

        pw.println("   <serviceName>radarServer</serviceName>");

        pw.println("    <metadata inherited=\"true\">");

        pw.println("    <documentation type=\"summary\">" + ds.getSummary() + "</documentation>");
        CalendarDateRange dr = ds.getCalendarDateCoverage();
        pw.println("      <TimeSpan>");
        pw.print("        <start>");
        if (pathInfo.contains("IDD")) {
          pw.print(rm.getStartDateTime(ds.getPath()));
        } else {
          pw.print(dr.getStart().toString());
        }
        pw.println("</start>");
        pw.println("        <end>" + dr.getEnd().toString() + "</end>");
        pw.println("      </TimeSpan>");
        ThreddsMetadata.GeospatialCoverage gc = ds.getGeospatialCoverage();
        LatLonRect bb = new LatLonRect();
        gc.setBoundingBox(bb);
        pw.println("      <LatLonBox>");
        pw.println("        <north>" + gc.getLatNorth() + "</north>");
        pw.println("        <south>" + gc.getLatSouth() + "</south>");
        pw.println("        <east>" + gc.getLonEast() + "</east>");
        pw.println("        <west>" + gc.getLonWest() + "</west>");
        pw.println("      </LatLonBox>");

        ThreddsMetadata.Variables cvs = (ThreddsMetadata.Variables) ds.getVariables().get(0);
        List vl = cvs.getVariableList();

        pw.println("      <Variables>");
        for (int j = 0; j < vl.size(); j++) {
          ThreddsMetadata.Variable v = (ThreddsMetadata.Variable) vl.get(j);
          pw.println(
              "        <variable name=\""
                  + v.getName()
                  + "\" vocabulary_name=\""
                  + v.getVocabularyName()
                  + "\" units=\""
                  + v.getUnits()
                  + "\" />");
        }
        pw.println("      </Variables>");
        String[] stations = rm.stationsDS(radarType, dataLocation.get(ds.getPath()));
        rm.printStations(stations, pw, radarType);

        pw.println("    </metadata>");
        pw.println("  </dataset>");
      }
      pw.println("</catalog>");
      pw.flush();
    } catch (Throwable e) {
      log.error("RadarServer.datasetInfoXml", e);
    }
    return;
  }
Пример #16
0
  private void datasetInfoHtml(
      RadarType radarType, String pathInfo, PrintWriter pw, HttpServletResponse res)
      throws IOException {
    pathInfo = pathInfo.replace("/dataset.html", "");
    pathInfo = pathInfo.replace("/catalog.html", "");
    Element root = new Element("RadarNexrad");
    Document doc = new Document(root);

    if (pathInfo.startsWith("/")) pathInfo = pathInfo.substring(1);
    for (int i = 0; i < datasets.size(); i++) {
      InvDatasetScan ds = (InvDatasetScan) datasets.get(i);
      if (!(pathInfo.equals(ds.getPath()))) {
        continue;
      }

      // at this point a valid dataset
      // fix the location
      root.setAttribute("location", "/thredds/radarServer/" + ds.getPath());

      // spatial range
      ThreddsMetadata.GeospatialCoverage gc = ds.getGeospatialCoverage();
      LatLonRect bb = new LatLonRect();
      gc.setBoundingBox(bb);
      String north = Double.toString(gc.getLatNorth());
      String south = Double.toString(gc.getLatSouth());
      String east = Double.toString(gc.getLonEast());
      String west = Double.toString(gc.getLonWest());

      Element LatLonBox = new Element("LatLonBox");
      LatLonBox.addContent(new Element("north").addContent(north));
      LatLonBox.addContent(new Element("south").addContent(south));
      LatLonBox.addContent(new Element("east").addContent(east));
      LatLonBox.addContent(new Element("west").addContent(west));
      root.addContent(LatLonBox);

      // get the time range
      Element timeSpan = new Element("TimeSpan");
      CalendarDateRange dr = ds.getCalendarDateCoverage();
      timeSpan.addContent(new Element("begin").addContent(dr.getStart().toString()));
      timeSpan.addContent(new Element("end").addContent(dr.getEnd().toString()));
      root.addContent(timeSpan);

      ThreddsMetadata.Variables cvs = (ThreddsMetadata.Variables) ds.getVariables().get(0);
      List vl = cvs.getVariableList();

      for (int j = 0; j < vl.size(); j++) {
        ThreddsMetadata.Variable v = (ThreddsMetadata.Variable) vl.get(j);
        Element variable = new Element("variable");
        variable.setAttribute("name", v.getName());
        root.addContent(variable);
      }

      // add pointer to the station list XML
      /*
      Element stnList = new Element("stationList");
      stnList.setAttribute("title", "Available Stations", XMLEntityResolver.xlinkNS);
      stnList.setAttribute("href", "/thredds/radarServer/"+ pathInfo +"/stations.xml",
          XMLEntityResolver.xlinkNS);
      root.addContent(stnList);
      */
      // String[] stations = rns.stationsDS( dataLocation.get( ds.getPath() ));
      // rns.printStations( stations );

      // add accept list
      Element a = new Element("AcceptList");
      a.addContent(new Element("accept").addContent("xml"));
      a.addContent(new Element("accept").addContent("html"));
      root.addContent(a);
    }
    ServerMethods sm = new ServerMethods(log);
    InputStream xslt = sm.getInputStream(contentPath + getPath() + "radar.xsl", RadarServer.class);

    try {
      // what's wrong here xslt = getXSLT( "radar.xsl" );
      XSLTransformer transformer = new XSLTransformer(xslt);
      Document html = transformer.transform(doc);
      XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
      String infoString = fmt.outputString(html);
      res.setContentType("text/html; charset=iso-8859-1");
      pw = res.getWriter();
      pw.println(infoString);
      pw.flush();

    } catch (Exception e) {
      log.error("radarServer reading " + contentPath + getPath() + "radar.xsl");
      log.error("radarServer XSLTransformer problem for web form ", e);
    } finally {
      if (xslt != null) {
        try {
          xslt.close();
        } catch (IOException e) {
          log.error("radarServer radar.xsl: error closing" + contentPath + getPath() + "radar.xsl");
        }
      }
    }
    return;
  }
Пример #17
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("utf-8");
    if (jjNumber.isDigit(jjTools.getParameter(request, "maxSize"))) {
      maxSize = Long.parseLong(jjTools.getParameter(request, "maxSize"));
    }

    response.setCharacterEncoding("utf-8");
    String name = request.getParameter("name");
    name = name == null ? "" : name;
    response.setContentType("text/plain");
    super.init(getServletConfig());
    //        response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    //        out.println();

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    //        fileItemFactory.setSizeThreshold(1024 * 1024); //1 MB

    try {
      ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
      List items = uploadHandler.parseRequest(request);
      Iterator itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()) {
          /*
           * Field
           */
          //                    out.println("Field Name=" + item.getFieldName() + ", Value=" +
          // item.getString());
          data.put(item.getFieldName(), item.getString());
        } else {
          /*
           * File
           */
          File folderAddress =
              new File(request.getServletContext().getRealPath(Save_Folder_Name)); // "/" +
          String extension = "";
          String nameWithoutExtension = item.getName();
          if (item.getName().lastIndexOf(".") > -1) {
            extension = item.getName().substring(item.getName().lastIndexOf("."));
            nameWithoutExtension =
                item.getName()
                    .substring(
                        item.getName().lastIndexOf("\\") + 1, item.getName().lastIndexOf("."));
          }
          folderAddress.mkdirs();
          nameWithoutExtension = "P";
          File file =
              new File(
                  folderAddress
                      + "/"
                      + nameWithoutExtension.toLowerCase()
                      + jjNumber.getRandom(10)
                      + extension.toLowerCase());
          String i = "0000000000";
          while (file.exists()) {
            i = jjNumber.getRandom(10);
            file =
                new File(
                    folderAddress
                        + "/"
                        + nameWithoutExtension.toLowerCase()
                        + i
                        + extension.toLowerCase());
          }
          if (!name.equals("")) {
            file = new File(folderAddress + "/" + name);
          }
          //                    out.println("File Name=" + item.getName()
          //                            + ", Field Name=" + item.getFieldName()
          //                            + ", Content type=" + item.getContentType()
          //                            + ", File Size=" + item.getSize()
          //                            + ", Save Address=" + file);
          //                    out.println(file);
          //                    String urlPath =
          // request.getRequestURL().toString().replace("Upload2", "Upload") + "/" +
          // file.getName().replace("\\", "/");
          //                    out.println("<html><head><meta http-equiv='Content-Type'
          // content='text/html; charset=utf-8'></head><body><input type='text' name='T1' size='58'
          // value='" + urlPath + "'></body></html>");
          data.put(item.getFieldName(), file.getAbsolutePath());
          if (!file.getName().toLowerCase().endsWith(".exe")) {
            item.write(file);
          }
          long size = file.length();
          ServerLog.Print("?>>>>>>" + file + "   -    Size:" + size);
          if (size > maxSize) {
            file.delete();
            out.print("big");
          } else {
            out.print(
                file.getName()
                    .replace(" ", "%20")
                    .replace("<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", ""));
            ServerLog.Print("Write pic in: " + file + " size:" + file.length());
            String name2 = file.getName().substring(0, file.getName().lastIndexOf("."));
            String extension2 =
                file.getName()
                    .substring(file.getName().lastIndexOf(".") + 1, file.getName().length());
            File file2 = new File(file.getParent() + "/" + name2 + "_small." + extension2);
            if (extension2.toLowerCase().equals("jpg")
                || extension2.toLowerCase().equals("png")
                || extension2.toLowerCase().equals("gif")) {
              jjPicture.doChangeSizeOfPic(file, file2, 250);
            }
          }
        }
      }
    } catch (Exception ex) {
      Server.ErrorHandler(ex);
    }
    out.flush();
    out.close();
  }
Пример #18
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);
    }
  }
Пример #19
0
  // public List getUserStoryList(String sessionId,String iterationId,ServletOutputStream out) {
  public List getUserStoryList(String sessionId, String iterationId, PrintWriter out) {

    List<Map> list = new ArrayList<Map>();

    statusMap.put(sessionId, "0");

    try {

      String apiURL =
          rallyApiHost
              + "/hierarchicalrequirement?"
              + "query=(Iteration%20=%20"
              + rallyApiHost
              + "/iteration/"
              + iterationId
              + ")&fetch=true&start=1&pagesize=100";

      log.info("getUserStoryList apiURL=" + apiURL);

      String responseXML = getRallyXML(apiURL);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      int totalSteps = xlist.size() + 1;
      int currentStep = 0;

      List taskRefLink = new ArrayList();

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {
        double totalTimeSpent = 0.0D;

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String planEstimate = item.getChildText("PlanEstimate");
        String formattedId = item.getChildText("FormattedID");

        String taskActualTotal = item.getChildText("TaskActualTotal");
        String taskEstimateTotal = item.getChildText("TaskEstimateTotal");
        String taskRemainingTotal = item.getChildText("TaskRemainingTotal");
        String scheduleState = item.getChildText("ScheduleState");

        Element ownerElement = item.getChild("Owner");

        String owner = "";
        String ownerRef = "";

        if (ownerElement != null) {
          owner = ownerElement.getAttributeValue("refObjectName");
        }

        Element taskElements = item.getChild("Tasks");
        // List taskElementList=taskElements.getContent();
        List taskElementList = taskElements.getChildren();

        List taskList = new ArrayList();

        log.info("taskElements.getChildren=" + taskElements);
        log.info("taskList=" + taskElementList);

        for (int i = 0; i < taskElementList.size(); i++) {
          Element taskElement = (Element) taskElementList.get(i);

          String taskRef = taskElement.getAttributeValue("ref");

          String[] objectIdArr = taskRef.split("/");
          String objectId = objectIdArr[objectIdArr.length - 1];

          log.info("objectId=" + objectId);

          // Map taskMap=getTaskMap(taskRef);
          Map taskMap = getTaskMapBatch(objectId);

          double taskTimeSpentTotal =
              Double.parseDouble((String) taskMap.get("taskTimeSpentTotal"));
          totalTimeSpent += taskTimeSpentTotal;
          taskList.add(taskMap);
        }

        map.put("type", "userstory");
        map.put("formattedId", formattedId);
        map.put("name", name);
        map.put("taskStatus", scheduleState);
        map.put("owner", owner);
        map.put("planEstimate", planEstimate);
        map.put("taskEstimateTotal", taskEstimateTotal);
        map.put("taskRemainingTotal", taskRemainingTotal);
        map.put("taskTimeSpentTotal", "" + totalTimeSpent);

        list.add(map);
        list.addAll(taskList);

        ++currentStep;
        double percentage = 100.0D * currentStep / totalSteps;
        String status = "" + Math.round(percentage);
        statusMap.put(sessionId, status);

        out.println("<script>parent.updateProcessStatus('" + status + "%')</script>" + status);
        out.flush();
        log.info("out.flush..." + status);

        // log.info("status="+status+" sessionId="+sessionId);
        // log.info("L1 statusMap="+statusMap+" "+statusMap.hashCode());

      }

      double planEstimate = 0.0D;
      double taskEstimateTotal = 0.0D;
      double taskRemainingTotal = 0.0D;
      double taskTimeSpentTotal = 0.0D;
      Map iterationMap = new HashMap();
      for (Map map : list) {
        String type = (String) map.get("type");

        String planEstimateStr = (String) map.get("planEstimate");

        log.info("planEstimateStr=" + planEstimateStr);

        if ("userstory".equals(type)) {

          if (planEstimateStr != null) {
            planEstimate += Double.parseDouble(planEstimateStr);
          }
          taskEstimateTotal += Double.parseDouble((String) map.get("taskEstimateTotal"));
          taskRemainingTotal += Double.parseDouble((String) map.get("taskRemainingTotal"));
          taskTimeSpentTotal += Double.parseDouble((String) map.get("taskTimeSpentTotal"));
        }
      }

      apiURL = rallyApiHost + "/iteration/" + iterationId + "?fetch=true";
      log.info("iteration apiURL=" + apiURL);
      responseXML = getRallyXML(apiURL);

      bSAX = new org.jdom.input.SAXBuilder();
      doc = bSAX.build(new StringReader(responseXML));
      root = doc.getRootElement();

      xpath = XPath.newInstance("//Iteration");
      xlist = xpath.selectNodes(root);

      String projName = "";
      String iterName = "";
      String iterState = "";

      iter = xlist.iterator();
      while (iter.hasNext()) {
        Element item = (Element) iter.next();

        iterName = item.getChildText("Name");
        iterState = item.getChildText("State");
        Element projElement = item.getChild("Project");
        projName = projElement.getAttributeValue("refObjectName");
      }

      iterationMap.put("type", "iteration");
      iterationMap.put("formattedId", "");
      iterationMap.put("name", projName + " - " + iterName);
      iterationMap.put("taskStatus", iterState);
      iterationMap.put("owner", "");

      iterationMap.put("planEstimate", "" + planEstimate);
      iterationMap.put("taskEstimateTotal", "" + taskEstimateTotal);
      iterationMap.put("taskRemainingTotal", "" + taskRemainingTotal);
      iterationMap.put("taskTimeSpentTotal", "" + taskTimeSpentTotal);

      list.add(0, iterationMap);

      statusMap.put(sessionId, "100");

      log.info("L2 statusMap=" + statusMap);

      log.info("L2 verify=" + getProcessStatus(sessionId));
      log.info("-----------");

      // String jsonData=JsonUtil.encodeObj(list);
      String jsonData = JSONValue.toJSONString(list);

      out.println("<script>parent.tableResult=" + jsonData + "</script>");
      out.println("<script>parent.showTableResult()</script>");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    TableSQLData tableSQL = null;
    VariablesSecureApp vars = new VariablesSecureApp(request);
    Boolean saveRequest = (Boolean) request.getAttribute("autosave");

    if (saveRequest != null && saveRequest) {
      String currentOrg = vars.getStringParameter("inpadOrgId");
      String currentClient = vars.getStringParameter("inpadClientId");
      boolean editableTab =
          (!org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(
                  this, vars.getRole(), tabId)
              && (currentOrg.equals("")
                  || Utility.isElementInList(
                      Utility.getContext(this, vars, "#User_Org", windowId, accesslevel),
                      currentOrg))
              && (currentClient.equals("")
                  || Utility.isElementInList(
                      Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                      currentClient)));

      OBError myError = new OBError();
      String commandType = request.getParameter("inpCommandType");
      String strcBpGroupId = request.getParameter("inpcBpGroupId");

      if (editableTab) {
        int total = 0;

        if (commandType.equalsIgnoreCase("EDIT") && !strcBpGroupId.equals(""))
          total = saveRecord(vars, myError, 'U');
        else total = saveRecord(vars, myError, 'I');

        if (!myError.isEmpty() && total == 0) throw new OBException(myError.getMessage());
      }
      vars.setSessionValue(request.getParameter("mappingName") + "|hash", vars.getPostDataHash());
      vars.setSessionValue(tabId + "|Header.view", "EDIT");

      return;
    }

    try {
      tableSQL =
          new TableSQLData(
              vars,
              this,
              tabId,
              Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel),
              Utility.getContext(this, vars, "#User_Client", windowId),
              Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y"));
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    String strOrderBy = vars.getSessionValue(tabId + "|orderby");
    if (!strOrderBy.equals("")) {
      vars.setSessionValue(tabId + "|newOrder", "1");
    }

    if (vars.commandIn("DEFAULT")) {

      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      if (strView.equals("")) {
        strView = defaultTabView;

        if (strView.equals("EDIT")) {
          if (strC_BP_Group_ID.equals("")) strC_BP_Group_ID = firstElement(vars, tableSQL);
          if (strC_BP_Group_ID.equals("")) strView = "RELATION";
        }
      }
      if (strView.equals("EDIT"))
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);
      else printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("DIRECT")) {
      String strC_BP_Group_ID = vars.getStringParameter("inpDirectKey");

      if (strC_BP_Group_ID.equals(""))
        strC_BP_Group_ID =
            vars.getRequiredGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID");
      else vars.setSessionValue(windowId + "|C_BP_Group_ID", strC_BP_Group_ID);

      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "EDIT");

      printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

    } else if (vars.commandIn("TAB")) {

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      String strC_BP_Group_ID = "";
      if (strView.equals("")) {
        strView = defaultTabView;
        if (strView.equals("EDIT")) {
          strC_BP_Group_ID = firstElement(vars, tableSQL);
          if (strC_BP_Group_ID.equals("")) strView = "RELATION";
        }
      }
      if (strView.equals("EDIT")) {

        if (strC_BP_Group_ID.equals("")) strC_BP_Group_ID = firstElement(vars, tableSQL);
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

      } else printPageDataSheet(response, vars, "", tableSQL);
    } else if (vars.commandIn("SEARCH")) {
      vars.getRequestGlobalVariable("inpParamName", tabId + "|paramName");

      vars.getRequestGlobalVariable("inpParamUpdated", tabId + "|paramUpdated");
      vars.getRequestGlobalVariable("inpParamUpdatedBy", tabId + "|paramUpdatedBy");
      vars.getRequestGlobalVariable("inpParamCreated", tabId + "|paramCreated");
      vars.getRequestGlobalVariable("inpparamCreatedBy", tabId + "|paramCreatedBy");

      vars.removeSessionValue(windowId + "|C_BP_Group_ID");
      String strC_BP_Group_ID = "";

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      if (strView.equals("")) strView = defaultTabView;

      if (strView.equals("EDIT")) {
        strC_BP_Group_ID = firstElement(vars, tableSQL);
        if (strC_BP_Group_ID.equals("")) {
          // filter returns empty set
          strView = "RELATION";
          // switch to grid permanently until the user changes the view again
          vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", strView);
        }
      }

      if (strView.equals("EDIT"))
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);
      else printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("RELATION")) {

      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "RELATION");
      printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("NEW")) {

      printPageEdit(response, request, vars, true, "", tableSQL);

    } else if (vars.commandIn("EDIT")) {

      @SuppressWarnings("unused") // In Expense Invoice tab this variable is not used, to be fixed
      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "EDIT");

      setHistoryCommand(request, "EDIT");
      printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

    } else if (vars.commandIn("NEXT")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");

      String strNext = nextElement(vars, strC_BP_Group_ID, tableSQL);

      printPageEdit(response, request, vars, false, strNext, tableSQL);
    } else if (vars.commandIn("PREVIOUS")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");

      String strPrevious = previousElement(vars, strC_BP_Group_ID, tableSQL);

      printPageEdit(response, request, vars, false, strPrevious, tableSQL);
    } else if (vars.commandIn("FIRST_RELATION")) {

      vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", "0");
      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("PREVIOUS_RELATION")) {

      String strInitRecord =
          vars.getSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber");
      String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId);
      int intRecordRange = strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange);
      if (strInitRecord.equals("") || strInitRecord.equals("0")) {
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", "0");
      } else {
        int initRecord = (strInitRecord.equals("") ? 0 : Integer.parseInt(strInitRecord));
        initRecord -= intRecordRange;
        strInitRecord = ((initRecord < 0) ? "0" : Integer.toString(initRecord));
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", strInitRecord);
      }
      vars.removeSessionValue(windowId + "|C_BP_Group_ID");

      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("NEXT_RELATION")) {

      String strInitRecord =
          vars.getSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber");
      String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId);
      int intRecordRange = strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange);
      int initRecord = (strInitRecord.equals("") ? 0 : Integer.parseInt(strInitRecord));
      if (initRecord == 0) initRecord = 1;
      initRecord += intRecordRange;
      strInitRecord = ((initRecord < 0) ? "0" : Integer.toString(initRecord));
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", strInitRecord);
      vars.removeSessionValue(windowId + "|C_BP_Group_ID");

      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("FIRST")) {

      String strFirst = firstElement(vars, tableSQL);

      printPageEdit(response, request, vars, false, strFirst, tableSQL);
    } else if (vars.commandIn("LAST_RELATION")) {

      String strLast = lastElement(vars, tableSQL);
      printPageDataSheet(response, vars, strLast, tableSQL);
    } else if (vars.commandIn("LAST")) {

      String strLast = lastElement(vars, tableSQL);

      printPageEdit(response, request, vars, false, strLast, tableSQL);
    } else if (vars.commandIn("SAVE_NEW_RELATION", "SAVE_NEW_NEW", "SAVE_NEW_EDIT")) {

      OBError myError = new OBError();
      int total = saveRecord(vars, myError, 'I');
      if (!myError.isEmpty()) {
        response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
      } else {
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsInserted");
          myError.setMessage(total + " " + myError.getMessage());
          vars.setMessage(tabId, myError);
        }
        if (vars.commandIn("SAVE_NEW_NEW"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
        else if (vars.commandIn("SAVE_NEW_EDIT"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
      }
    } else if (vars.commandIn(
        "SAVE_EDIT_RELATION", "SAVE_EDIT_NEW", "SAVE_EDIT_EDIT", "SAVE_EDIT_NEXT")) {

      String strC_BP_Group_ID =
          vars.getRequiredGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID");
      OBError myError = new OBError();
      int total = saveRecord(vars, myError, 'U');
      if (!myError.isEmpty()) {
        response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
      } else {
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsUpdated");
          myError.setMessage(total + " " + myError.getMessage());
          vars.setMessage(tabId, myError);
        }
        if (vars.commandIn("SAVE_EDIT_NEW"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
        else if (vars.commandIn("SAVE_EDIT_EDIT"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        else if (vars.commandIn("SAVE_EDIT_NEXT")) {
          String strNext = nextElement(vars, strC_BP_Group_ID, tableSQL);
          vars.setSessionValue(windowId + "|C_BP_Group_ID", strNext);
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        } else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
      }
    } else if (vars.commandIn("DELETE")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");
      // BusinessPartnerCategoryData data = getEditVariables(vars);
      int total = 0;
      OBError myError = null;
      if (org.openbravo.erpCommon.utility.WindowAccessData.hasNotDeleteAccess(
          this, vars.getRole(), tabId)) {
        myError =
            Utility.translateError(
                this,
                vars,
                vars.getLanguage(),
                Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
        vars.setMessage(tabId, myError);
      } else {
        try {
          total =
              BusinessPartnerCategoryData.delete(
                  this,
                  strC_BP_Group_ID,
                  Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                  Utility.getContext(this, vars, "#User_Org", windowId, accesslevel));
        } catch (ServletException ex) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
          if (!myError.isConnectionAvailable()) {
            bdErrorConnection(response);
            return;
          } else vars.setMessage(tabId, myError);
        }
        if (myError == null && total == 0) {
          myError =
              Utility.translateError(
                  this,
                  vars,
                  vars.getLanguage(),
                  Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
          vars.setMessage(tabId, myError);
        }
        vars.removeSessionValue(windowId + "|cBpGroupId");
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "RELATION");
      }
      if (myError == null) {
        myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsDeleted");
        myError.setMessage(total + " " + myError.getMessage());
        vars.setMessage(tabId, myError);
      }
      response.sendRedirect(strDireccion + request.getServletPath());

    } else if (vars.commandIn("SAVE_XHR")) {

      OBError myError = new OBError();
      JSONObject result = new JSONObject();
      String commandType = vars.getStringParameter("inpCommandType");
      char saveType = "NEW".equals(commandType) ? 'I' : 'U';
      try {
        int total = saveRecord(vars, myError, saveType);
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsUpdated");
          myError.setMessage(total + " " + myError.getMessage());
          myError.setType("Success");
        }
        result.put("oberror", myError.toMap());
        result.put("tabid", vars.getStringParameter("tabID"));
        result.put("redirect", strDireccion + request.getServletPath() + "?Command=" + commandType);
      } catch (Exception e) {
        log4j.error("Error saving record (XHR request): " + e.getMessage(), e);
        myError.setType("Error");
        myError.setMessage(e.getMessage());
      }

      response.setContentType("application/json");
      PrintWriter out = response.getWriter();
      out.print(result.toString());
      out.flush();
      out.close();
    } else if (vars.getCommand().toUpperCase().startsWith("BUTTON")
        || vars.getCommand().toUpperCase().startsWith("SAVE_BUTTON")) {
      pageErrorPopUp(response);
    } else pageError(response);
  }
Пример #21
0
 public void flush() throws IOException {
   if (wrappedWriter != null) {
     wrappedWriter.flush();
   }
   wrappedOut.finish();
 }
Пример #22
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    String support = "support"; // valid username

    HttpSession session = null;
    session = req.getSession(false); // Get user's session object (no new one)
    if (session == null) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String userName = (String) session.getAttribute("user"); // get username

    if (!userName.equals(support)) {

      invalidUser(out); // Intruder - reject
      return;
    }

    Connection con1 = null; // init DB objects
    Connection con2 = null;
    Statement stmt1 = null;
    Statement stmt2 = null;
    ResultSet rs1 = null;
    ResultSet rs2 = null;

    out.println("<HTML><HEAD><TITLE>Database Query</TITLE></HEAD>");
    out.println("<BODY><H3>List Each Club With a Custom Style Sheet</H3>");
    out.println(
        "<table border=1><tr><td><b>Site</b></td><td><b>Club Name</b></td><td><b>Style Sheet</b></td></tr>");
    out.flush();

    String club = "";
    String fullname = "";
    String styles = "";

    try {

      con1 = Connect.getCon(rev); // connect to v5

    } catch (Exception exc) {

      // Error connecting to db....
      out.println("<BR><BR>Unable to connect to the DB.");
      out.println("<BR>Exception: " + exc.getMessage());
      out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>.");
      out.println("</BODY></HTML>");
      return;
    }

    //
    // Get the club names from the 'clubs' table
    //
    //  Process each club in the table
    //
    try {

      stmt1 = con1.createStatement();
      rs1 =
          stmt1.executeQuery(
              "SELECT clubname, fullname FROM v5.clubs WHERE inactive=0 ORDER BY clubname");

      while (rs1.next()) {

        club = rs1.getString(1); // get a club name
        fullname = rs1.getString(2); // get club's full name

        if (!club.startsWith("demo")) { // if NOT a demo site

          con2 = Connect.getCon(club); // get a connection to this club's db
          stmt2 = con2.createStatement(); // create a statement

          try {

            rs2 = stmt2.executeQuery("SELECT custom_styles FROM club5");

            if (rs2.next()) {

              styles = rs2.getString("custom_styles"); // get the custom styles name, if any

              if (!styles.equals("")) {

                out.println(
                    "<tr><td>"
                        + club
                        + "</td><td>"
                        + fullname
                        + "</td><td>"
                        + styles
                        + "</td></tr>");
              }
            }

          } catch (Exception exc) {
            out.println(club + " failed!!!!!!!!!!!!!!!!!!!! " + exc.toString());
          }

          stmt2.close();
          con2.close();
        }
      } // end if WHILE clubs

      out.println("</table>");

    } catch (Exception exc) {

      // Error connecting to db....
      out.println("<BR><BR>Unable to connect to the DB.");
      out.println("<BR>Exception: " + exc.getMessage());
      out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>.");
      out.println("</BODY></HTML>");
      return;
    }

    try {
      stmt1.close();
      con1.close();
    } catch (Exception ignore) {
    }

    out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>.");
    out.println("</BODY></HTML>");
    out.close();
  }
  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) {
      }
    }
  }
Пример #24
0
  private void doUpdate(PrintWriter out) {

    Connection con1 = null; // init DB objects
    Connection con2 = null;
    PreparedStatement pstmt = null;
    Statement stmt1 = null;
    Statement stmt1a = null;
    Statement stmt2 = null;
    Statement stmt3 = null;
    ResultSet rs1 = null;
    ResultSet rs2 = null;
    ResultSet rs3 = null;

    out.println("<HTML><HEAD><TITLE>Database Query</TITLE></HEAD>");
    out.println("<BODY><H3>Starting Job to Check for Clubster Users</H3>");
    out.flush();

    String club = "";
    String name = "";

    try {

      con1 = dbConn.Connect(rev);
    } catch (Exception exc) {

      // Error connecting to db....
      out.println("<BR><BR>Unable to connect to the DB.");
      out.println("<BR>Exception: " + exc.getMessage());
      out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>.");
      out.println("</BODY></HTML>");
      return;
    }

    //
    // Get the club names from the 'clubs' table
    //
    //  Process each club in the table
    //
    int x1 = 0;
    int x2 = 0;
    int i = 0;

    boolean skip = true;

    try {

      stmt1 = con1.createStatement();
      rs1 = stmt1.executeQuery("SELECT clubname, fullname FROM clubs ORDER BY clubname");

      while (rs1.next()) {

        x1++;
        club = rs1.getString(1); // get a club name
        name = rs1.getString(2); // get full club name

        con2 = dbConn.Connect(club); // get a connection to this club's db

        stmt2 = con2.createStatement();

        rs2 = stmt2.executeQuery("SELECT date FROM sessionlog WHERE msg LIKE '%clubster'");

        if (rs2.next()) {

          out.println("<br><br>");
          out.print("Club found: " + club + ", " + name);
        }

        stmt2.close();
        con2.close();
      }

      stmt1.close();
      con1.close();

    } catch (Exception e) {

      // Error connecting to db....

      out.println("<BR><BR><H3>Fatal Error!</H3>");
      out.println("Error performing update to club '" + club + "'.");
      out.println("<BR>Exception: " + e.getMessage());
      out.println("<BR>Message: " + e.toString());
      out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>.");
      out.println("</BODY></HTML>");
      out.close();
      Connect.close(stmt2, con2);
      Connect.close(stmt1, con1);
      return;
    }

    Connect.close(stmt2, con2);
    Connect.close(stmt1, con1);

    out.print("<BR><BR>Done, " + x1 + "clubs checked.");
    out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>");
    out.println("</CENTER></BODY></HTML>");
    // out.flush();
    // out.close();

  }
Пример #25
0
  /**
   * This method handles PUT requests from the client. PUT requests will come from the applet
   * portion of this application and are the way that images and other files can be posted to the
   * server.
   *
   * @param request the HTTP request object
   * @param response the HTTP response object
   * @exception ServletException
   * @exception IOException
   */
  public void doPut(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    /*
     * The Scan applet will zip all the files together to create a
     * faster upload and to use just one server connection.
     */
    ZipInputStream in = new ZipInputStream(request.getInputStream());

    /*
     * This will write all the files to a directory on the server.
     */
    try {
      try {

        File file = new File("scan");
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        String fileSize = null;
        while (true) {
          ZipEntry entry = in.getNextEntry();
          if (entry == null) {
            break;
          }
          File f = File.createTempFile("translate", entry.getName());
          FileOutputStream out = new FileOutputStream(f);
          FileInputStream inStream = null;
          try {
            int read;
            byte[] buf = new byte[2024];

            while ((read = in.read(buf)) > 0) {
              out.write(buf, 0, read);
            }
            out.close();
            inStream = new FileInputStream(f);
            System.out.println(entry.getSize());
            byte[] b = new byte[inStream.available()];
            inStream.read(b);
            System.out.println(b.length);
            com.itextpdf.text.Image image1 = com.itextpdf.text.Image.getInstance(b);
            image1.scalePercent(30);
            image1.setCompressionLevel(9);
            document.add(image1);
          } finally {
          }
        }
        document.close();
        //                fileSize = CommonUtils.getFileSize(file);
        //                DocumentStoreLogDAO documentStoreLogDAO = new DocumentStoreLogDAO();
        //                DocumentStoreLog documentStoreLog = null;
        //                DocumentStoreLog documentStore =
        // (DocumentStoreLog)session.getAttribute(CommonConstants.DOCUMENT_STORE_LOG);
        //                if(null != documentStore) {
        //                    documentStore.setFileSize(fileSize);
        //                }
        //                Transaction tx = documentStoreLogDAO.getSession().getTransaction();
        //                tx.begin();
        //                documentStoreLogDAO.save(documentStore);
        //                tx.commit();
      } catch (ZipException ze) {
        /*
         * We want to catch each sip exception separately because
         * there is a possibility that we can read more files from
         * the archive even if one of them is corrupted.
         */
        ze.printStackTrace();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      in.close();
    }

    /*
     * Now that we have finished uploading the files
     * we will send a reponse to the server indicating
     * our success.
     */

    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html><head><title>ImageSrv</title></head></html>");
    out.flush();
    out.close();
    response.setStatus(HttpServletResponse.SC_OK);
  }
Пример #26
0
  /**
   * ************************************************************************ Default handler for
   * OPeNDAP ascii requests. Returns OPeNDAP DAP2 data in comma delimited ascii columns for
   * ingestion into some not so OPeNDAP enabled application such as MS-Excel. Accepts constraint
   * expressions in exactly the same way as the regular OPeNDAP dataserver.
   *
   * @param request
   * @param response
   * @param dataSet
   * @throws opendap.dap.DAP2Exception
   * @throws ParseException
   */
  public void sendASCII(HttpServletRequest request, HttpServletResponse response, String dataSet)
      throws DAP2Exception, ParseException {

    if (Debug.isSet("showResponse"))
      System.out.println(
          "Sending OPeNDAP ASCII Data For: "
              + dataSet
              + "    CE: '"
              + request.getQueryString()
              + "'");

    String requestURL, ce;
    DConnect2 url;
    DataDDS dds;

    if (request.getQueryString() == null) {
      ce = "";
    } else {
      ce = "?" + request.getQueryString();
    }

    int suffixIndex = request.getRequestURL().toString().lastIndexOf(".");

    requestURL = request.getRequestURL().substring(0, suffixIndex);

    if (Debug.isSet("showResponse")) {
      System.out.println("New Request URL Resource: '" + requestURL + "'");
      System.out.println("New Request Constraint Expression: '" + ce + "'");
    }

    try {

      if (_Debug) System.out.println("Making connection to .dods service...");
      url = new DConnect2(requestURL, true);

      if (_Debug) System.out.println("Requesting data...");
      dds = url.getData(ce, null, new asciiFactory());

      if (_Debug) System.out.println(" ASC DDS: ");
      if (_Debug) dds.print(System.out);

      PrintWriter pw = new PrintWriter(response.getOutputStream());
      PrintWriter pwDebug = new PrintWriter(System.out);

      if (dds != null) {
        dds.print(pw);
        pw.println("---------------------------------------------");

        String s = "";
        Enumeration e = dds.getVariables();

        while (e.hasMoreElements()) {
          BaseType bt = (BaseType) e.nextElement();
          if (_Debug) ((toASCII) bt).toASCII(pwDebug, true, null, true);
          // bt.toASCII(pw,addName,getNAme(),true);
          ((toASCII) bt).toASCII(pw, true, null, true);
        }
      } else {

        String betterURL =
            request.getRequestURL().substring(0, request.getRequestURL().lastIndexOf("."))
                + ".dods?"
                + request.getQueryString();

        pw.println("-- ASCII RESPONSE HANDLER PROBLEM --");
        pw.println("");
        pw.println("The ASCII response handler was unable to obtain requested data set.");
        pw.println("");
        pw.println("Because this handler calls it's own OPeNDAP server to get the requested");
        pw.println("data the source error is obscured.");
        pw.println("");
        pw.println("To get a better idea of what is going wrong, try requesting the URL:");
        pw.println("");
        pw.println("    " + betterURL);
        pw.println("");
        pw.println("And then look carefully at the returned document. Note that if you");
        pw.println("are using a browser to access the URL the returned document will");
        pw.println("more than likely be treated as a download and written to your");
        pw.println("local disk. It should be a file with the extension \".dods\"");
        pw.println("");
        pw.println("Locate it, open it with a text editor, and find your");
        pw.println("way to happiness and inner peace.");
        pw.println("");
      }

      // pw.println("</pre>");
      pw.flush();
      if (_Debug) pwDebug.flush();

    } catch (FileNotFoundException fnfe) {
      System.out.println("OUCH! FileNotFoundException: " + fnfe.getMessage());
      fnfe.printStackTrace(System.out);
    } catch (MalformedURLException mue) {
      System.out.println("OUCH! MalformedURLException: " + mue.getMessage());
      mue.printStackTrace(System.out);
    } catch (IOException ioe) {
      System.out.println("OUCH! IOException: " + ioe.getMessage());
      ioe.printStackTrace(System.out);
    } catch (Throwable t) {
      System.out.println("OUCH! Throwable: " + t.getMessage());
      t.printStackTrace(System.out);
    }

    if (_Debug) System.out.println(" GetAsciiHandler done");
  }