コード例 #1
0
ファイル: readPostParameters.java プロジェクト: kmizu/spnuts
 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);
     }
   }
 }
コード例 #2
0
ファイル: WebRes.java プロジェクト: duxingzhe311/system4j
  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();
    }
  }
コード例 #3
0
  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());
    }
  }
コード例 #4
0
ファイル: WebRes.java プロジェクト: duxingzhe311/system4j
  /**
   * 根据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();
    }
  }
コード例 #5
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;
 }
コード例 #6
0
ファイル: WebRes.java プロジェクト: duxingzhe311/system4j
  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();
    }
  }
コード例 #7
0
ファイル: RadarServer.java プロジェクト: feihugis/NetCDF
  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;
  }
コード例 #8
0
ファイル: JasperReport.java プロジェクト: jackrain/framework
  /**
   * 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");
    }
  }
コード例 #9
0
ファイル: PlatformSPFilter.java プロジェクト: ossbase/p1
  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);
    }
  }
コード例 #10
0
ファイル: UploadImage.java プロジェクト: dragonlet/C391Proj
  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();
    }
  }
コード例 #11
0
ファイル: RadarServer.java プロジェクト: feihugis/NetCDF
  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;
  }