private void processEncrypt(final ServletRequest servletRequest ,final HttpServletRequest httpRequest,final ServletResponse servletResponse,
                          final FilterChain filterChain)throws IOException, ServletException{


        InputStream inputStream = servletRequest.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int letti=-1;
        while ((letti = inputStream.read(buf)) > 0){
            byteArrayOutputStream.write(buf, 0, letti);
        }
        final BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpRequest,doEncrypt(byteArrayOutputStream));

        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        final ByteArrayPrintWriter pw = new ByteArrayPrintWriter();
        HttpServletResponse wrappedResp = new HttpServletResponseWrapper(response) {
            public PrintWriter getWriter() {
                return pw.getWriter();
            }
            public ServletOutputStream getOutputStream() {
                return pw.getStream();
            }
        };

        filterChain.doFilter(bufferedRequest, wrappedResp);


    }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    super.doPost(request, response);

    try {
      if (!ServletFileUpload.isMultipartContent(request)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
      }

      ServletFileUpload sfU = new ServletFileUpload();
      FileItemIterator items = sfU.getItemIterator(request);
      while (items.hasNext()) {
        FileItemStream item = items.next();
        if (!item.isFormField()) {
          InputStream stream = item.openStream();
          Document doc = editor.toDocument(stream);
          stream.close();
          handleDocument(request, response, doc);
          return;
        }
      }

      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded");
    } catch (FileUploadException fuE) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage());
    } catch (JDOMException jE) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage());
    }
  }
예제 #3
0
  public int doEndTag() throws JspException {
    if ((jspFile.indexOf("..") >= 0)
        || (jspFile.toUpperCase().indexOf("/WEB-INF/") != 0)
        || (jspFile.toUpperCase().indexOf("/META-INF/") != 0))
      throw new JspTagException("Invalid JSP file " + jspFile);

    InputStream in = pageContext.getServletContext().getResourceAsStream(jspFile);

    if (in == null) throw new JspTagException("Unable to find JSP file: " + jspFile);

    InputStreamReader reader = new InputStreamReader(in);
    JspWriter out = pageContext.getOut();

    try {
      out.println("<body>");
      out.println("<pre>");
      for (int ch = in.read(); ch != -1; ch = in.read())
        if (ch == '<') out.print("&lt;");
        else out.print((char) ch);
      out.println("</pre>");
      out.println("</body>");
    } catch (IOException ex) {
      throw new JspTagException("IOException: " + ex.toString());
    }
    return super.doEndTag();
  }
예제 #4
0
  public static String getResTxtContent(ClassLoader cl, String p) throws IOException {
    String s = res2txt_cont.get(p);
    if (s != null) return s;

    InputStream is = null;
    try {
      is = cl.getResourceAsStream(p);
      // is = this.getClass().getResourceAsStream(p);
      if (is == null) return null;

      byte[] buf = new byte[1024];
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len;
      while ((len = is.read(buf)) >= 0) {
        baos.write(buf, 0, len);
      }

      byte[] cont = baos.toByteArray();
      s = new String(cont, "UTF-8");

      res2txt_cont.put(p, s);
      return s;
    } finally {
      if (is != null) is.close();
    }
  }
예제 #5
0
 protected Object exec(Object[] args, Context context) {
   int nargs = args.length;
   if (nargs != 1 && nargs != 2) {
     undefined(args, context);
     return null;
   }
   HttpServletRequest request = (HttpServletRequest) args[0];
   String enc;
   if (nargs == 1) {
     enc = ServletEncoding.getDefaultInputEncoding(context);
   } else {
     enc = (String) args[1];
   }
   String contentType = request.getContentType();
   if (contentType != null && contentType.startsWith("multipart/form-data")) {
     throw new RuntimeException("not yet implemented");
   } else {
     try {
       ByteArrayOutputStream bout = new ByteArrayOutputStream();
       byte[] buf = new byte[512];
       int n;
       InputStream in = request.getInputStream();
       while ((n = in.read(buf, 0, buf.length)) != -1) {
         bout.write(buf, 0, n);
       }
       in.close();
       String qs = new String(bout.toByteArray());
       Map map = URLEncoding.parseQueryString(qs, enc);
       return new ServletParameter(map);
     } catch (IOException e) {
       throw new PnutsException(e, context);
     }
   }
 }
 public BufferedRequestWrapper(HttpServletRequest req) throws IOException {
     super(req);
     InputStream is = req.getInputStream();
     baos = new ByteArrayOutputStream();
     byte buf[] = new byte[1024];
     int letti;
     while ((letti = is.read(buf)) > 0) {
         baos.write(buf, 0, letti);
     }
     buffer = baos.toByteArray();
 }
예제 #7
0
  /**
   * 根据XORM定义和对应的文件属性列,输出文件内容.
   *
   * @param resp
   * @param filename
   * @param xorm_c
   * @param xorm_prop
   * @param xorm_pk
   */
  public static void renderFile(
      HttpServletResponse resp, String filename, Class xorm_c, String xorm_prop, long xorm_pk)
      throws Exception {
    InputStream is = null;
    try {
      is = GDB.getInstance().getXORMFileStreamByPkId(xorm_c, xorm_prop, xorm_pk);
      if (is == null) return;

      renderFile(resp, filename, is);
    } finally {
      if (is != null) is.close();
    }
  }
예제 #8
0
  public static void renderFile(
      HttpServletResponse resp,
      String filename,
      InputStream cont_stream,
      boolean showpic,
      boolean ignorespace)
      throws IOException {
    if (cont_stream == null) return;

    if (ignorespace) filename = filename.replace(" ", "");

    if (!showpic)
      resp.addHeader(
          "Content-Disposition",
          "attachment; filename=" + new String(filename.getBytes(), "iso8859-1"));

    resp.setContentType(Mime.getContentType(filename));
    ServletOutputStream os = resp.getOutputStream();
    byte[] buf = new byte[1024];
    int len = 0;
    while ((len = cont_stream.read(buf)) != -1) {
      os.write(buf, 0, len);
    }

    os.flush();
  }
예제 #9
0
 private static synchronized String getJavascript() {
   if (jstext == null) {
     InputStream istr = null;
     try {
       ClassLoader loader = Thread.currentThread().getContextClassLoader();
       istr = loader.getResourceAsStream(JAVASCRIPT_RESOURCE);
       jstext = StringUtil.fromInputStream(istr);
       istr.close();
     } catch (Exception e) {
       log.error("Can't load javascript", e);
     } finally {
       IOUtil.safeClose(istr);
     }
   }
   return jstext;
 }
예제 #10
0
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, java.io.IOException {
    String p = req.getParameter("r");
    if (p == null || (p = p.trim()).equals("")) {
      String pi = req.getPathInfo();

      return;
    }

    byte[] cont = res2cont.get(p);
    if (cont != null) {
      resp.setContentType(Mime.getContentType(p));
      ServletOutputStream os = resp.getOutputStream();
      os.write(cont);
      os.flush();
      return;
    }

    InputStream is = null;
    try {
      is = appCL.getResourceAsStream(p); // getInputStreamByPath(p) ;
      if (is == null) {
        is = new Object().getClass().getResourceAsStream(p);
        if (is == null) return;
      }

      byte[] buf = new byte[1024];
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len;
      while ((len = is.read(buf)) >= 0) {
        baos.write(buf, 0, len);
      }

      cont = baos.toByteArray();
      res2cont.put(p, cont);
      resp.setContentType(Mime.getContentType(p));
      ServletOutputStream os = resp.getOutputStream();
      os.write(cont);
      os.flush();
      return;
    } finally {
      if (is != null) is.close();
    }
  }
예제 #11
0
  public static void main(String args[]) throws IOException {

    // Function References
    String path =
        "http://motherlode.ucar.edu:8081/thredds/radarServer/nexrad/level3/IDD/dataset.xml";

    try {
      catURI = new URI(StringUtil2.escape(path, "/:-_."));
    } catch (URISyntaxException e) {
      System.out.println("radarServer main: URISyntaxException=" + e.getMessage());
      return;
    }

    // read the catalog
    System.out.println("radarServer main: full path=" + path);
    InputStream ios = null;
    try {

      URL url = new URL(path);
      ios = url.openStream();
      // ios = new FileInputStream(path);
      // acat = factory.readXML(ios, catURI );
      BufferedReader dataIS = new BufferedReader(new InputStreamReader(ios));

      while (true) {
        String line = dataIS.readLine();
        if (line == null) break;
        System.out.println(line);
      }

    } catch (Throwable t) {
      System.out.println("radarServer main: Exception on catalog=" + path + " " + t.getMessage());
      return;
    } finally {
      if (ios != null) {
        try {
          ios.close();
        } catch (IOException e) {
          System.out.println("radarServer main: error closing" + path);
        }
      }
    }
    return;
  }
예제 #12
0
  /**
   * return OutputStream of JasperReport object, this page could only be viewed from localhost for
   * security concern. parameter can be (id), or (table and type)
   *
   * @param id - report id, or
   * @param table - table name
   * @param type - reporttype "s","l","o", case insensitive
   * @param client(*) - client domain
   * @param version - version number, default to -1
   */
  public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String clientName = request.getParameter("client");
    int objectId = ParamUtils.getIntAttributeOrParameter(request, "id", -1);
    if (objectId == -1) {
      // try using table and type
      objectId =
          getReportId(clientName, request.getParameter("table"), request.getParameter("type"));
    }
    if (objectId == -1) {
      logger.error("report not found, request is:" + Tools.toString(request));
      throw new NDSException("report not found");
    }
    int version = ParamUtils.getIntAttributeOrParameter(request, "version", -1);
    File reportXMLFile = new File(ReportTools.getReportFile(objectId, clientName));
    if (reportXMLFile.exists()) {
      // generate jasperreport if file not exists or not newer
      String reportName =
          reportXMLFile.getName().substring(0, reportXMLFile.getName().lastIndexOf("."));
      File reportJasperFile = new File(reportXMLFile.getParent(), reportName + ".jasper");
      if (!reportJasperFile.exists()
          || reportJasperFile.lastModified() < reportXMLFile.lastModified()) {
        JasperCompileManager.compileReportToFile(
            reportXMLFile.getAbsolutePath(), reportJasperFile.getAbsolutePath());
      }
      InputStream is = new FileInputStream(reportJasperFile);
      response.setContentType("application/octetstream;");
      response.setContentLength((int) reportJasperFile.length());

      // response.setHeader("Content-Disposition","inline;filename=\""+reportJasperFile.getName()+"\"");
      ServletOutputStream os = response.getOutputStream();

      byte[] b = new byte[8192];
      int bInt;
      while ((bInt = is.read(b, 0, b.length)) != -1) {
        os.write(b, 0, bInt);
      }
      is.close();
      os.flush();
      os.close();
    } else {
      throw new NDSException("Not found report template");
    }
  }
예제 #13
0
  protected void processConfiguration(FilterConfig filterConfig) {
    InputStream is;

    if (isNullOrEmpty(this.configFile)) {
      is = servletContext.getResourceAsStream(CONFIG_FILE_LOCATION);
    } else {
      try {
        is = new FileInputStream(this.configFile);
      } catch (FileNotFoundException e) {
        throw logger.samlIDPConfigurationError(e);
      }
    }

    PicketLinkType picketLinkType;

    String configurationProviderName = filterConfig.getInitParameter(CONFIGURATION_PROVIDER);

    if (configurationProviderName != null) {
      try {
        Class<?> clazz = SecurityActions.loadClass(getClass(), configurationProviderName);

        if (clazz == null) {
          throw new ClassNotFoundException(ErrorCodes.CLASS_NOT_LOADED + configurationProviderName);
        }

        this.configProvider = (SAMLConfigurationProvider) clazz.newInstance();
      } catch (Exception e) {
        throw new RuntimeException(
            "Could not create configuration provider [" + configurationProviderName + "].", e);
      }
    }

    try {
      // Work on the IDP Configuration
      if (configProvider != null) {
        try {
          if (is == null) {
            // Try the older version
            is =
                servletContext.getResourceAsStream(
                    GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION);

            // Additionally parse the deprecated config file
            if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) {
              ((AbstractSAMLConfigurationProvider) configProvider).setConfigFile(is);
            }
          } else {
            // Additionally parse the consolidated config file
            if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) {
              ((AbstractSAMLConfigurationProvider) configProvider).setConsolidatedConfigFile(is);
            }
          }

          picketLinkType = configProvider.getPicketLinkConfiguration();
          picketLinkType.setIdpOrSP(configProvider.getSPConfiguration());
        } catch (ProcessingException e) {
          throw logger.samlSPConfigurationError(e);
        } catch (ParsingException e) {
          throw logger.samlSPConfigurationError(e);
        }
      } else {
        if (is != null) {
          try {
            picketLinkType = ConfigurationUtil.getConfiguration(is);
          } catch (ParsingException e) {
            logger.trace(e);
            throw logger.samlSPConfigurationError(e);
          }
        } else {
          is = servletContext.getResourceAsStream(GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION);
          if (is == null) {
            throw logger.configurationFileMissing(configFile);
          }

          picketLinkType = new PicketLinkType();

          picketLinkType.setIdpOrSP(ConfigurationUtil.getSPConfiguration(is));
        }
      }

      // Close the InputStream as we no longer need it
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          // ignore
        }
      }

      Boolean enableAudit = picketLinkType.isEnableAudit();

      // See if we have the system property enabled
      if (!enableAudit) {
        String sysProp = SecurityActions.getSystemProperty(GeneralConstants.AUDIT_ENABLE, "NULL");
        if (!"NULL".equals(sysProp)) {
          enableAudit = Boolean.parseBoolean(sysProp);
        }
      }

      if (enableAudit) {
        if (auditHelper == null) {
          String securityDomainName = PicketLinkAuditHelper.getSecurityDomainName(servletContext);

          auditHelper = new PicketLinkAuditHelper(securityDomainName);
        }
      }

      SPType spConfiguration = (SPType) picketLinkType.getIdpOrSP();
      processIdPMetadata(spConfiguration);

      this.serviceURL = spConfiguration.getServiceURL();
      this.canonicalizationMethod = spConfiguration.getCanonicalizationMethod();
      this.picketLinkConfiguration = picketLinkType;

      this.issuerID = filterConfig.getInitParameter(ISSUER_ID);
      this.characterEncoding = filterConfig.getInitParameter(CHARACTER_ENCODING);
      this.samlHandlerChainClass = filterConfig.getInitParameter(SAML_HANDLER_CHAIN_CLASS);

      logger.samlSPSettingCanonicalizationMethod(canonicalizationMethod);
      XMLSignatureUtil.setCanonicalizationMethodType(canonicalizationMethod);

      try {
        this.initKeyProvider();
        this.initializeHandlerChain(picketLinkType);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      logger.trace("Identity Provider URL=" + getConfiguration().getIdentityURL());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
예제 #14
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Variable initializations.
    HttpSession session = request.getSession();
    FileItem image_file = null;
    int record_id = 0;
    int image_id;

    // Check if a record ID has been entered.
    if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) {
      // If no ID has been entered, send message to jsp.
      response_message =
          "<p><font color=FF0000>No Record ID Detected, Please Enter One.</font></p>";
      session.setAttribute("msg", response_message);
      response.sendRedirect("UploadImage.jsp");
    }

    try {
      // Parse the HTTP request to get the image stream.
      DiskFileUpload fu = new DiskFileUpload();
      // Will get multiple image files if that happens and can be accessed through FileItems.
      List<FileItem> FileItems = fu.parseRequest(request);

      // Connect to the database and create a statement.
      conn = getConnected(drivername, dbstring, username, password);
      stmt = conn.createStatement();

      // Process the uploaded items, assuming only 1 image file uploaded.
      Iterator<FileItem> i = FileItems.iterator();

      while (i.hasNext()) {
        FileItem item = (FileItem) i.next();

        // Test if item is a form field and matches recordID.
        if (item.isFormField()) {
          if (item.getFieldName().equals("recordID")) {
            // Covert record id from string to integer.
            record_id = Integer.parseInt(item.getString());

            String sql = "select count(*) from radiology_record where record_id = " + record_id;
            int count = 0;

            try {
              rset = stmt.executeQuery(sql);

              while (rset != null && rset.next()) {
                count = (rset.getInt(1));
              }
            } catch (SQLException e) {
              response_message = e.getMessage();
            }

            // Check if recordID is in the database.
            if (count == 0) {
              // Invalid recordID, send message to jsp.
              response_message =
                  "<p><font color=FF0000>Record ID Does Not Exist In Database.</font></p>";
              session.setAttribute("msg", response_message);
              // Close connection.
              conn.close();
              response.sendRedirect("UploadImage.jsp");
            }
          }
        } else {
          image_file = item;

          if (image_file.getName().equals("")) {
            // No file, send message to jsp.
            response_message = "<p><font color=FF0000>No File Selected For Record ID.</font></p>";
            session.setAttribute("msg", response_message);
            // Close connection.
            conn.close();
            response.sendRedirect("UploadImage.jsp");
          }
        }
      }

      // Get the image stream.
      InputStream instream = image_file.getInputStream();

      BufferedImage full_image = ImageIO.read(instream);
      BufferedImage thumbnail = shrink(full_image, 10);
      BufferedImage regular_image = shrink(full_image, 5);

      // First, to generate a unique img_id using an SQL sequence.
      rset1 = stmt.executeQuery("SELECT image_id_sequence.nextval from dual");
      rset1.next();
      image_id = rset1.getInt(1);

      // Insert an empty blob into the table first. Note that you have to
      // use the Oracle specific function empty_blob() to create an empty blob.
      stmt.execute(
          "INSERT INTO pacs_images VALUES("
              + record_id
              + ","
              + image_id
              + ", empty_blob(), empty_blob(), empty_blob())");

      // to retrieve the lob_locator
      // Note that you must use "FOR UPDATE" in the select statement
      String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE";
      rset = stmt.executeQuery(cmd);
      rset.next();
      BLOB myblobFull = ((OracleResultSet) rset).getBLOB(5);
      BLOB myblobThumb = ((OracleResultSet) rset).getBLOB(3);
      BLOB myblobRegular = ((OracleResultSet) rset).getBLOB(4);

      // Write the full size image to the blob object.
      OutputStream fullOutstream = myblobFull.getBinaryOutputStream();
      ImageIO.write(full_image, "jpg", fullOutstream);
      // Write the thumbnail size image to the blob object.
      OutputStream thumbOutstream = myblobThumb.getBinaryOutputStream();
      ImageIO.write(thumbnail, "jpg", thumbOutstream);
      // Write the regular size image to the blob object.
      OutputStream regularOutstream = myblobRegular.getBinaryOutputStream();
      ImageIO.write(regular_image, "jpg", regularOutstream);

      // Commit the changes to database.
      stmt.executeUpdate("commit");
      response_message = "<p><font color=00CC00>Upload Successful.</font></p>";
      session.setAttribute("msg", response_message);

      instream.close();
      fullOutstream.close();
      thumbOutstream.close();
      regularOutstream.close();

      // Close connection.
      conn.close();
      response.sendRedirect("UploadImage.jsp");

      instream.close();
      fullOutstream.close();
      thumbOutstream.close();
      regularOutstream.close();

      // Close connection.
      conn.close();
    } catch (Exception ex) {
      response_message = ex.getMessage();
    }
  }
예제 #15
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;
  }
예제 #16
0
package com.jspsmart.upload;
  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();
  }