コード例 #1
0
  /**
   * This method will open the sample report pdf.
   *
   * @param reportFilePath - full path of the sample report to be shown.
   * @param request - instance of HttpServletRequest
   * @param response - instance of HttpServletResponse
   * @throws ServletException - error
   * @throws IOException - error
   */
  private static void showSampleReport(
      String reportFilePath, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (null != request.getSession().getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT)
        && request
            .getSession()
            .getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT)
            .toString()
            .equalsIgnoreCase("Y")) {
      ServletOutputStream output = null;
      try {

        FileInputStream fis = new FileInputStream(reportFilePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        try {
          for (int readNum; (readNum = fis.read(buf)) != -1; ) {
            baos.write(buf, 0, readNum); // no doubt here is 0
            // Writes len bytes from the specified byte array starting at offset off to this byte
            // array output stream.
          }

        } catch (IOException ex) {
          ex.printStackTrace();
        }

        if (null != baos) {

          // Init servlet response.
          response.reset();
          response.setContentType("application/pdf");
          response.setContentLength(baos.size());
          response.setHeader("Content-disposition", "inline; filename=\"" + reportFilePath);
          response.setHeader("Expires", "0");
          response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
          //                  response.setHeader("Transfer-Encoding", "identity");
          output = response.getOutputStream();

          output.write(baos.toByteArray(), 0, baos.size());

          // Finalize task.
          output.flush();
        }
      } catch (Exception exception) {
        OPPE_LOG.error("ERROR.SHOW_PDF.ERROR", exception);
      } finally {

        // Gently close streams.
        close((Closeable) output);
      }
    }
  }
コード例 #2
0
ファイル: GZIPResponseStream.java プロジェクト: isl/FeXML
  public void close() throws IOException {
    if (closed) {
      throw new IOException("This output stream has already been closed");
    }
    gzipstream.finish();

    byte[] bytes = baos.toByteArray();

    response.addHeader("Content-Length", Integer.toString(bytes.length));
    response.addHeader("Content-Encoding", "gzip");
    output.write(bytes);
    output.flush();
    output.close();
    closed = true;
  }
コード例 #3
0
ファイル: CDCClientServlet.java プロジェクト: aldaris/opensso
 /**
  * Shows Application Error message to the user.
  *
  * @param response an HttpServletResponse object that contains the response the servlet sends to
  *     the client.
  * @param msg Message to be displayed.
  */
 private void showError(HttpServletResponse response, String msg) {
   ServletOutputStream out = null;
   if (msg == null || msg.equals("")) {
     msg = "ERROR: An application error has occured.";
   }
   try {
     out = response.getOutputStream();
     out.println(msg);
     out.flush();
   } catch (IOException e) {
     debug.error("CDCClientServlet.showError::Could not show error " + "message to the user " + e);
   } finally {
     try {
       out.close();
     } catch (IOException ignore) {
     }
   }
 }
コード例 #4
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");
    }
  }
コード例 #5
0
  /**
   * Shows Application Error message to the user.
   *
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @param msg Message to be displayed.
   */
  private void showError(HttpServletResponse response, String msg) throws IOException {
    ServletOutputStream out = null;
    if (msg == null || msg.equals("") || msg.contains(SERVER_ERROR_STR_MATCH)) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      return;
    }

    try {
      out = response.getOutputStream();
      out.println(msg);
      out.flush();
    } catch (IOException e) {
      debug.error("CDCClientServlet.showError::Could not show error " + "message to the user " + e);
    } finally {
      try {
        out.close();
      } catch (IOException ignore) {
      }
    }
  }
コード例 #6
0
  /**
   * This method handles response of showing pdf servlet.
   *
   * @param request - instance of HttpServletRequest
   * @param response - instance of HttpServletResponse
   * @throws ServletException - error
   * @throws IOException - error
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String preview = request.getParameter(PREVIEW_REPORT_PARAMETER);
    String sampleReportParam = request.getParameter(SAMPLE_REPORT_PARAM);
    if (null != sampleReportParam) {
      String sampleReportPath = "";
      if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.PROVIDER_SUMMARY)) {
        sampleReportPath =
            WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.PROVIDER_SUMMARY_SAMPLE_FILE;
        showSampleReport(sampleReportPath, request, response);
      } else if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.COMPARATIVE_SUMMARY)) {
        sampleReportPath =
            WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.COMPARITIVE_SUMMARY_SAMPLE_FILE;
        showSampleReport(sampleReportPath, request, response);
      } else if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.EXECUTIVE_SUMMARY)) {
        sampleReportPath =
            WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.EXECUTIVE_SUMMARY_SAMPLE_FILE;
        showSampleReport(sampleReportPath, request, response);
      }
    } else if (null != preview && STR_TRUE.equals(preview)) {
      // report generation using OracleBI
      ServletOutputStream output = null;
      byte[] rawBinaryFile = null;
      Map<String, String> parameterMap = null;
      PublicReportServicePortClient client = null;
      FileStream fileStream = null;
      try {

        if (null != request.getSession().getAttribute(REPORTS_PARAMETERS_MAP)) {
          parameterMap =
              (Map<String, String>) request.getSession().getAttribute(REPORTS_PARAMETERS_MAP);
          //                    request.getSession().removeAttribute(REPORTS_PARAMETERS_MAP);
        }

        if (null != parameterMap && parameterMap.containsKey("REPORT_PATH")) {
          client = new PublicReportServicePortClient();
          fileStream = client.generateReport(parameterMap);
          rawBinaryFile = fileStream.getFileContent();
        }

        if (null != rawBinaryFile) {

          // Init servlet response.
          response.reset();
          response.setContentType("application/pdf");
          response.setContentLength(rawBinaryFile.length);
          response.setHeader(
              "Content-disposition", "inline; filename=\"" + fileStream.getFileName() + ".pdf\"");
          response.setHeader("Expires", "0");
          response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
          //                  response.setHeader("Transfer-Encoding", "identity");
          output = response.getOutputStream();

          output.write(rawBinaryFile, 0, rawBinaryFile.length);

          // Finalize task.
          output.flush();
        }
      } catch (Exception exception) {
        OPPE_LOG.error("ERROR.SHOW_PDF.ERROR", exception);
      } finally {

        // Gently close streams.
        close((Closeable) output);
      }
    }
  }
コード例 #7
0
  // authentication request
  public String authRequest(
      String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp)
      throws IOException, ServletException {

    if (OpenIDRealm.instance == null) {
      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print("OpenID realm wasn't initialized.");
      out.print("</h2>");

      // out.print(HTTPUtils.printStackTraceHTML(t));

      out.print("</div></body></html>");
      return null;
    }
    try {
      String returnAfterAuthentication = httpReq.getParameter("return_to");

      // configure the return_to URL where your application will receive
      // the authentication responses from the OpenID provider
      String returnToUrl =
          httpReq.getRequestURL().toString()
              + "?is_return=true&exist_return="
              + returnAfterAuthentication;

      // perform discovery on the user-supplied identifier
      List<?> discoveries = manager.discover(userSuppliedString);

      // attempt to associate with the OpenID provider
      // and retrieve one service endpoint for authentication
      DiscoveryInformation discovered = manager.associate(discoveries);

      // store the discovery information in the user's session
      httpReq.getSession().setAttribute("openid-disc", discovered);

      // obtain a AuthRequest message to be sent to the OpenID provider
      AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

      if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) {
        SRegRequest sregReq = SRegRequest.createFetchRequest();

        sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true);

        authReq.addExtension(sregReq);
      } else {

        FetchRequest fetch = FetchRequest.createFetchRequest();

        fetch.addAttribute(
            AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true);
        fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true);

        // wants up to three email addresses
        fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3);

        authReq.addExtension(fetch);
      }

      if (!discovered.isVersion2()) {
        // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
        // The only method supported in OpenID 1.x
        // redirect-URL usually limited ~2048 bytes
        httpResp.sendRedirect(authReq.getDestinationUrl(true));
        return null;

      } else {
        // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

        Object OPEndpoint = authReq.getDestinationUrl(false);

        ServletOutputStream out = httpResp.getOutputStream();

        httpResp.setContentType("text/html; charset=UTF-8");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        out.println("<head>");
        out.println("    <title>OpenID HTML FORM Redirection</title>");
        out.println("</head>");
        out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
        out.println(
            "    <form name=\"openid-form-redirection\" action=\""
                + OPEndpoint
                + "\" method=\"post\" accept-charset=\"utf-8\">");

        Map<String, String> parameterMap = authReq.getParameterMap();
        for (Entry<String, String> entry : parameterMap.entrySet()) {
          out.println(
              "	<input type=\"hidden\" name=\""
                  + entry.getKey()
                  + "\" value=\""
                  + entry.getValue()
                  + "\"/>");
        }

        out.println("        <button type=\"submit\">Continue...</button>");
        out.println("    </form>");
        out.println("</body>");
        out.println("</html>");

        out.flush();
      }
    } catch (OpenIDException e) {
      // present error to the user
      LOG.debug("OpenIDException", e);

      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print(e.getMessage());
      out.print("</h2>");

      Throwable t = e.getCause();
      if (t != null) {
        // t can be null
        out.print(HTTPUtils.printStackTraceHTML(t));
      }

      out.print("</div></body></html>");
    }

    return null;
  }
コード例 #8
0
  /**
   * Get Query By Form results throught response output stream.
   *
   * @param queryspec Name of XML file containing the Query Specification
   * @param columnlist List of comma separated column names to retrieve
   * @param where SQL WHERE clause to apply
   * @param order by SQL ORDER BY clause to apply
   * @param showas Output format. One of { "CSV" <i>(comma separated)</i>, "TSV" <i>(tabbed
   *     separated)</i>, "XLS" <i>(Excel)</i> }
   * @throws IOException
   * @throws FileNotFoundException
   * @throws ServletException
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, FileNotFoundException, ServletException {
    Class oDriver;
    Connection oConn = null;
    ServletOutputStream oOut = response.getOutputStream();
    QueryByForm oQBF;
    String sQuerySpec;
    String sColumnList;
    String sWhere;
    String sOrderBy;
    String sShowAs;
    String sStorage;

    if (DebugFile.trace) {
      DebugFile.writeln("Begin HttpQueryServlet.doGet(...)");
      DebugFile.incIdent();
    }

    sStorage = Environment.getProfileVar("hipergate", "storage");

    if (DebugFile.trace) DebugFile.writeln("storage=" + sStorage);

    try {
      oDriver = Class.forName(jdbcDriverClassName);
    } catch (ClassNotFoundException ignore) {
      oDriver = null;
      if (DebugFile.trace)
        DebugFile.writeln("Class.forName(" + jdbcDriverClassName + ") : " + ignore.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database driver not found");
    }

    if (null == oDriver) return;

    try {

      sQuerySpec = request.getParameter("queryspec");
      sColumnList = request.getParameter("columnlist");
      if (null == sColumnList) sColumnList = "*";
      sWhere = request.getParameter("where");
      if (null == sWhere) sWhere = "1=1";
      sOrderBy = request.getParameter("orderby");
      if (null == sOrderBy) sOrderBy = "";
      sShowAs = request.getParameter("showas");
      if (null == sShowAs) sShowAs = "CSV";

      if (DebugFile.trace)
        DebugFile.writeln("queryspec=" + sQuerySpec != null ? sQuerySpec : "null");
      if (DebugFile.trace) DebugFile.writeln("where=" + sWhere);
      if (DebugFile.trace) DebugFile.writeln("orderby=" + sOrderBy);

      if (hasSqlSignature(sColumnList)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Column List Syntax");
        return;
      }

      oQBF = new QueryByForm("file://" + sStorage + "/qbf/" + sQuerySpec + ".xml");

      if (DebugFile.trace) DebugFile.writeln("DriverManager.getConnection(" + jdbcURL + ",...)");
      oConn = DriverManager.getConnection(jdbcURL, dbUserName, dbUserPassword);

      // Send some basic http headers to support binary d/l.
      if (sShowAs.equalsIgnoreCase("XLS")) {
        response.setContentType("application/x-msexcel");
        response.setHeader(
            "Content-Disposition",
            "inline; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage()) + " 1.csv\"");
      } else if (sShowAs.equalsIgnoreCase("CSV")) {
        response.setContentType("text/plain");
        response.setHeader(
            "Content-Disposition",
            "attachment; filename=\""
                + oQBF.getTitle(request.getLocale().getLanguage())
                + " 1.csv\"");
      } else if (sShowAs.equalsIgnoreCase("TSV")) {
        response.setContentType("text/tab-separated-values");
        response.setHeader(
            "Content-Disposition",
            "attachment; filename=\""
                + oQBF.getTitle(request.getLocale().getLanguage())
                + " 1.tsv\"");
      } else {
        response.setContentType("text/plain");
        response.setHeader(
            "Content-Disposition",
            "inline; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage()) + " 1.txt\"");
      }

      if (0 == sOrderBy.length())
        oQBF.queryToStream(
            oConn, sColumnList, oQBF.getBaseFilter(request) + " " + sWhere, oOut, sShowAs);
      else
        oQBF.queryToStream(
            oConn,
            sColumnList,
            oQBF.getBaseFilter(request) + " " + sWhere + " ORDER BY " + sOrderBy,
            oOut,
            sShowAs);

      oConn.close();
      oConn = null;

      oOut.flush();
    } catch (SQLException e) {
      if (DebugFile.trace) DebugFile.writeln("SQLException " + e.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (ClassNotFoundException e) {
      if (DebugFile.trace) DebugFile.writeln("ClassNotFoundException " + e.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (IllegalAccessException e) {
      if (DebugFile.trace) DebugFile.writeln("IllegalAccessException " + e.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (Exception e) {
      if (DebugFile.trace) DebugFile.writeln("Exception " + e.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
      try {
        if (null != oConn) if (!oConn.isClosed()) oConn.close();
      } catch (SQLException e) {
        if (DebugFile.trace) DebugFile.writeln("SQLException " + e.getMessage());
      }
    }

    if (DebugFile.trace) {
      DebugFile.decIdent();
      DebugFile.writeln("End HttpQueryServlet.doGet()");
    }
  } // doGet()