Exemple #1
0
  // postToRestfulApi -
  // Note: params in the addr field need to be URLEncoded
  private String postToRestfulApi(
      String addr, String data, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);
    String result = "";
    try {
      URLConnection connection = new URL(API_ROOT + addr).openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        connection.setDoInput(true);
      }
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept-Charset", "UTF-8");

      // Post JSON string to URL
      OutputStream os = connection.getOutputStream();
      byte[] b = data.getBytes("UTF-8");
      os.write(b);

      // Receive results back from API
      InputStream is = connection.getInputStream();
      result = IOUtils.toString(is, "UTF-8");

      String newCookie = getConnectionInfiniteCookie(connection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
    } catch (Exception e) {
      // System.out.println("Exception: " + e.getMessage());
    }
    return result;
  } // TESTED
Exemple #2
0
 @Override
 public void write(byte[] b) throws IOException {
   synchronized (statusLock) {
     // Make sure HTTP status and header is specified.
     statusLock.notifyAll();
     committed = true;
   }
   target.write(b);
 }
Exemple #3
0
 @Override
 public void flush() throws IOException {
   synchronized (statusLock) {
     // Make sure HTTP status and header is specified.
     statusLock.notifyAll();
   }
   byte[] b = Arrays.copyOf(buffer, offset);
   target.write(b);
   offset = 0;
 }
Exemple #4
0
  public void download(HttpServletResponse response, String filename) throws IOException {
    StringTokenizer tokenTO = new StringTokenizer(filename, "\\");
    int j = 0;
    String[] filepath1 = new String[10];
    while (tokenTO.hasMoreTokens()) {
      filepath1[j] = tokenTO.nextToken();
      j++;
    }
    String filepath = "";
    for (int m = 0; m < j - 1; m++) {
      filepath = filepath + filepath1[m] + "\\";
    }
    filepath = filepath + filepath1[j - 1];
    File down_file = new java.io.File(filepath);
    long l = down_file.length(); // 文件长度
    InputStream in = new FileInputStream(down_file);

    if (in != null) {
      try {
        String fs = down_file.getName();
        response.reset();
        response.setContentType(null); //
        String s = "attachment; filename=" + fs; //
        response.setHeader("Content-Disposition", s); // 以上输出文件元信息

        OutputStream output = null;
        FileInputStream fis = null;

        output = response.getOutputStream();
        fis = new FileInputStream(filepath);
        response.setContentLength((int) l);
        byte[] b = new byte[2048];
        int i = 0;
        while ((i = fis.read(b)) > 0) {
          output.write(b, 0, i);
        }
        output.flush();
        in.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * This method must be invoked at the end of processing. The streams are closed and their content
   * is analyzed. Actual XSLT processing takes place here.
   */
  @SuppressWarnings("unchecked")
  void finishResponse() throws IOException {
    if (writer != null) {
      writer.close();
    } else {
      if (stream != null) stream.close();
    }

    /*
     * If we're not in passthrough mode, then we need to finalize XSLT transformation.
     */
    if (false == passthrough) {
      if (stream != null) {
        final byte[] bytes = ((DeferredOutputStream) stream).getBytes();
        final boolean processingSuppressed =
            (origRequest.getAttribute(XSLTFilterConstants.NO_XSLT_PROCESSING) != null)
                | (origRequest.getParameter(XSLTFilterConstants.NO_XSLT_PROCESSING) != null);

        if (processingSuppressed) {
          // Just copy the buffered data to the output directly.
          final OutputStream os = origResponse.getOutputStream();
          os.write(bytes);
          os.close();
        } else {
          // Otherwise apply XSLT transformation to it.
          try {
            processWithXslt(
                bytes,
                (Map<String, Object>) origRequest.getAttribute(XSLTFilterConstants.XSLT_PARAMS_MAP),
                origResponse);
          } catch (TransformerException e) {
            final Throwable t = unwrapCause(e);
            if (t instanceof IOException) {
              throw (IOException) t;
            }

            filterError("Error applying stylesheet.", e);
          }
        }
      }
    }
  }
  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) {
      }
    }
  }
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {

    String retval = "<html> <H4>";

    try {
      // Create a message factory.
      MessageFactory mf = MessageFactory.newInstance();

      // Create a message from the message factory.
      SOAPMessage msg = mf.createMessage();

      // Message creation takes care of creating the SOAPPart - a
      // required part of the message as per the SOAP 1.1
      // specification.
      SOAPPart sp = msg.getSOAPPart();

      // Retrieve the envelope from the soap part to start building
      // the soap message.
      SOAPEnvelope envelope = sp.getEnvelope();

      // Create a soap header from the envelope.
      SOAPHeader hdr = envelope.getHeader();

      // Create a soap body from the envelope.
      SOAPBody bdy = envelope.getBody();

      // Add a soap body element to the soap body
      SOAPBodyElement gltp =
          bdy.addBodyElement(
              envelope.createName("GetLastTradePrice", "ztrade", "http://wombat.ztrade.com"));

      gltp.addChildElement(envelope.createName("symbol", "ztrade", "http://wombat.ztrade.com"))
          .addTextNode("SUNW");

      StringBuffer urlSB = new StringBuffer();
      urlSB.append(req.getScheme()).append("://").append(req.getServerName());
      urlSB.append(":").append(req.getServerPort()).append(req.getContextPath());
      String reqBase = urlSB.toString();

      if (data == null) {
        data = reqBase + "/index.html";
      }

      // Want to set an attachment from the following url.
      // Get context
      URL url = new URL(data);

      AttachmentPart ap = msg.createAttachmentPart(new DataHandler(url));

      ap.setContentType("text/html");

      // Add the attachment part to the message.
      msg.addAttachmentPart(ap);

      // Create an endpoint for the recipient of the message.
      if (to == null) {
        to = reqBase + "/receiver";
      }

      URL urlEndpoint = new URL(to);

      System.err.println("Sending message to URL: " + urlEndpoint);
      System.err.println("Sent message is logged in \"sent.msg\"");

      retval += " Sent message (check \"sent.msg\") and ";

      FileOutputStream sentFile = new FileOutputStream("sent.msg");
      msg.writeTo(sentFile);
      sentFile.close();

      // Send the message to the provider using the connection.
      SOAPMessage reply = con.call(msg, urlEndpoint);

      if (reply != null) {
        FileOutputStream replyFile = new FileOutputStream("reply.msg");
        reply.writeTo(replyFile);
        replyFile.close();
        System.err.println("Reply logged in \"reply.msg\"");
        retval += " received reply (check \"reply.msg\").</H4> </html>";

      } else {
        System.err.println("No reply");
        retval += " no reply was received. </H4> </html>";
      }

    } catch (Throwable e) {
      e.printStackTrace();
      logger.severe("Error in constructing or sending message " + e.getMessage());
      retval += " There was an error " + "in constructing or sending message. </H4> </html>";
    }

    try {
      OutputStream os = resp.getOutputStream();
      os.write(retval.getBytes());
      os.flush();
      os.close();
    } catch (IOException e) {
      e.printStackTrace();
      logger.severe("Error in outputting servlet response " + e.getMessage());
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // set the response

    Shepherd myShepherd = new Shepherd();

    Vector rEncounters = new Vector();

    // setup data dir
    String rootWebappPath = getServletContext().getRealPath("/");
    File webappsDir = new File(rootWebappPath).getParentFile();
    File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName());
    // if(!shepherdDataDir.exists()){shepherdDataDir.mkdir();}
    File encountersDir = new File(shepherdDataDir.getAbsolutePath() + "/encounters");
    // if(!encountersDir.exists()){encountersDir.mkdir();}

    // set up the files
    String gisFilename = "geneGIS_export_" + request.getRemoteUser() + ".csv";
    File gisFile = new File(encountersDir.getAbsolutePath() + "/" + gisFilename);

    myShepherd.beginDBTransaction();

    try {

      // set up the output stream
      FileOutputStream fos = new FileOutputStream(gisFile);
      OutputStreamWriter outp = new OutputStreamWriter(fos);

      try {

        EncounterQueryResult queryResult =
            EncounterQueryProcessor.processQuery(
                myShepherd, request, "year descending, month descending, day descending");
        rEncounters = queryResult.getResult();

        int numMatchingEncounters = rEncounters.size();

        // build the CSV file header
        StringBuffer locusString = new StringBuffer("");
        int numLoci = 2; // most covered species will be loci
        try {
          numLoci = (new Integer(CommonConfiguration.getProperty("numLoci"))).intValue();
        } catch (Exception e) {
          System.out.println("numPloids configuration value did not resolve to an integer.");
          e.printStackTrace();
        }

        for (int j = 0; j < numLoci; j++) {
          locusString.append(",Locus" + (j + 1) + " A1,Locus" + (j + 1) + " A2");
        }
        // out.println("<html><body>");
        // out.println("Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub
        // Area,Sex,Haplotype"+locusString.toString());

        outp.write(
            "Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub Area,Sex,Haplotype"
                + locusString.toString()
                + "\n");

        for (int i = 0; i < numMatchingEncounters; i++) {

          Encounter enc = (Encounter) rEncounters.get(i);
          String assembledString = "";
          if (enc.getIndividualID() != null) {
            assembledString += enc.getIndividualID();
          }
          if (enc.getAlternateID() != null) {
            assembledString += "," + enc.getAlternateID();
          } else {
            assembledString += ",";
          }

          String dateString = ",";
          if (enc.getYear() > 0) {
            dateString += enc.getYear();
            if (enc.getMonth() > 0) {
              dateString += ("-" + enc.getMonth());
              if (enc.getDay() > 0) {
                dateString += ("-" + enc.getDay());
              }
            }
          }
          assembledString += dateString;

          String timeString = ",";
          if (enc.getHour() > -1) {
            timeString += enc.getHour() + ":" + enc.getMinutes();
          }
          assembledString += timeString;

          if ((enc.getDecimalLatitude() != null) && (enc.getDecimalLongitude() != null)) {
            assembledString += "," + enc.getDecimalLatitude();
            assembledString += "," + enc.getDecimalLongitude();
          } else {
            assembledString += ",,";
          }

          assembledString += "," + enc.getVerbatimLocality();
          assembledString += "," + enc.getLocationID();
          assembledString += "," + enc.getSex();

          // find and print the haplotype
          String haplotypeString = ",";
          if (enc.getHaplotype() != null) {
            haplotypeString += enc.getHaplotype();
          }

          // find and print the ms markers
          String msMarkerString = "";
          List<TissueSample> samples = enc.getTissueSamples();
          int numSamples = samples.size();
          boolean foundMsMarkers = false;
          for (int k = 0; k < numSamples; k++) {
            if (!foundMsMarkers) {
              TissueSample t = samples.get(k);
              List<GeneticAnalysis> analyses = t.getGeneticAnalyses();
              int aSize = analyses.size();
              for (int l = 0; l < aSize; l++) {
                GeneticAnalysis ga = analyses.get(l);
                if (ga.getAnalysisType().equals("MicrosatelliteMarkers")) {
                  foundMsMarkers = true;
                  MicrosatelliteMarkersAnalysis ga2 = (MicrosatelliteMarkersAnalysis) ga;
                  List<Locus> loci = ga2.getLoci();
                  int localLoci = loci.size();
                  for (int m = 0; m < localLoci; m++) {
                    Locus locus = loci.get(m);
                    if (locus.getAllele0() != null) {
                      msMarkerString += "," + locus.getAllele0();
                    } else {
                      msMarkerString += ",";
                    }
                    if (locus.getAllele1() != null) {
                      msMarkerString += "," + locus.getAllele1();
                    } else {
                      msMarkerString += ",";
                    }
                  }
                }
              }
            }
          }

          // out.println("<p>"+assembledString+haplotypeString+msMarkerString+"</p>");
          outp.write(assembledString + haplotypeString + msMarkerString + "\n");
        }
        outp.close();
        outp = null;

        // now write out the file
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment;filename=" + gisFilename);
        ServletContext ctx = getServletContext();
        // InputStream is = ctx.getResourceAsStream("/encounters/"+gisFilename);
        InputStream is = new FileInputStream(gisFile);

        int read = 0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        OutputStream os = response.getOutputStream();

        while ((read = is.read(bytes)) != -1) {
          os.write(bytes, 0, read);
        }
        os.flush();
        os.close();

      } catch (Exception ioe) {
        ioe.printStackTrace();
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<html><body><p><strong>Error encountered</strong> with file writing. Check the relevant log.</p>");
        out.println(
            "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>");
        out.println(ServletUtilities.getFooter());
        out.close();
        outp.close();
        outp = null;
      }

    } catch (Exception e) {
      e.printStackTrace();
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println(ServletUtilities.getHeader(request));
      out.println("<html><body><p><strong>Error encountered</strong></p>");
      out.println(
          "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>");
      out.println(ServletUtilities.getFooter());
      out.close();
    }
    myShepherd.rollbackDBTransaction();
    myShepherd.closeDBTransaction();
  }
Exemple #9
0
 private static void sendBinaryResponse(HttpServletResponse res, byte[] bytes) throws IOException {
   res.setContentType("application/binary-encoded");
   OutputStream out = res.getOutputStream(); // care to handle errors later?
   out.write(bytes);
   out.flush();
 }