예제 #1
0
  /**
   * Called by the server (via the <code>service</code> method) to allow a servlet to handle a TRACE
   * request.
   *
   * <p>A TRACE returns the headers sent with the TRACE request to the client, so that they can be
   * used in debugging. There's no need to override this method.
   *
   * @param req the {@link HttpServletRequest} object that contains the request the client made of
   *     the servlet
   * @param resp the {@link HttpServletResponse} object that contains the response the servlet
   *     returns to the client
   * @exception IOException if an input or output error occurs while the servlet is handling the
   *     TRACE request
   * @exception ServletException if the request for the TRACE cannot be handled
   */
  protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    int responseLength;

    String CRLF = "\r\n";
    StringBuilder buffer =
        new StringBuilder("TRACE ")
            .append(req.getRequestURI())
            .append(" ")
            .append(req.getProtocol());

    Enumeration<String> reqHeaderEnum = req.getHeaderNames();

    while (reqHeaderEnum.hasMoreElements()) {
      String headerName = reqHeaderEnum.nextElement();
      buffer.append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName));
    }

    buffer.append(CRLF);

    responseLength = buffer.length();

    resp.setContentType("message/http");
    resp.setContentLength(responseLength);
    ServletOutputStream out = resp.getOutputStream();
    out.print(buffer.toString());
    out.close();
    return;
  }
예제 #2
0
 public static void setContentLength(HttpServletResponse sres, long length) {
   if (length <= Integer.MAX_VALUE) {
     sres.setContentLength((int) length);
   } else {
     sres.addHeader("Content-Length", Long.toString(length));
   }
 }
  /**
   * 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);
      }
    }
  }
예제 #4
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");
    }
  }
예제 #5
0
파일: down.java 프로젝트: RainerJava/erp-6
  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 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);
      }
    }
  }
  /**
   * Perform form authentication. Called from SecurityHandler.
   *
   * @return UserPrincipal if authenticated else null.
   */
  public Principal authenticate(
      UserRealm realm, String pathInContext, HttpRequest httpRequest, HttpResponse httpResponse)
      throws IOException {
    HttpServletRequest request = (ServletHttpRequest) httpRequest.getWrapper();
    HttpServletResponse response =
        httpResponse == null ? null : (HttpServletResponse) httpResponse.getWrapper();

    // Handle paths
    String uri = pathInContext;

    // Setup session
    HttpSession session = request.getSession(response != null);
    if (session == null) return null;

    // Handle a request for authentication.
    if (uri.substring(uri.lastIndexOf("/") + 1).startsWith(__J_SECURITY_CHECK)) {
      // Check the session object for login info.
      FormCredential form_cred = new FormCredential();
      form_cred.authenticate(
          realm,
          request.getParameter(__J_USERNAME),
          request.getParameter(__J_PASSWORD),
          httpRequest);

      String nuri = (String) session.getAttribute(__J_URI);
      if (nuri == null || nuri.length() == 0) {
        nuri = request.getContextPath();
        if (nuri.length() == 0) nuri = "/";
      }

      if (form_cred._userPrincipal != null) {
        // Authenticated OK
        if (log.isDebugEnabled()) log.debug("Form authentication OK for " + form_cred._jUserName);
        session.removeAttribute(__J_URI); // Remove popped return URI.
        httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
        httpRequest.setAuthUser(form_cred._jUserName);
        httpRequest.setUserPrincipal(form_cred._userPrincipal);
        session.setAttribute(__J_AUTHENTICATED, form_cred);

        // Sign-on to SSO mechanism
        if (realm instanceof SSORealm) {
          ((SSORealm) realm)
              .setSingleSignOn(
                  httpRequest,
                  httpResponse,
                  form_cred._userPrincipal,
                  new Password(form_cred._jPassword));
        }

        // Redirect to original request
        if (response != null) {
          response.setContentLength(0);
          response.sendRedirect(response.encodeRedirectURL(nuri));
        }
      } else if (response != null) {
        if (log.isDebugEnabled())
          log.debug("Form authentication FAILED for " + form_cred._jUserName);
        if (_formErrorPage != null) {
          response.setContentLength(0);
          response.sendRedirect(
              response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formErrorPage)));
        } else {
          response.sendError(HttpResponse.__403_Forbidden);
        }
      }

      // Security check is always false, only true after final redirection.
      return null;
    }

    // Check if the session is already authenticated.
    FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED);

    if (form_cred != null) {
      // We have a form credential. Has it been distributed?
      if (form_cred._userPrincipal == null) {
        // This form_cred appears to have been distributed.  Need to reauth
        form_cred.authenticate(realm, httpRequest);

        // Sign-on to SSO mechanism
        if (form_cred._userPrincipal != null && realm instanceof SSORealm) {
          ((SSORealm) realm)
              .setSingleSignOn(
                  httpRequest,
                  httpResponse,
                  form_cred._userPrincipal,
                  new Password(form_cred._jPassword));
        }
      } else if (!realm.reauthenticate(form_cred._userPrincipal))
        // Else check that it is still authenticated.
        form_cred._userPrincipal = null;

      // If this credential is still authenticated
      if (form_cred._userPrincipal != null) {
        if (log.isDebugEnabled())
          log.debug("FORM Authenticated for " + form_cred._userPrincipal.getName());
        httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
        httpRequest.setAuthUser(form_cred._userPrincipal.getName());
        httpRequest.setUserPrincipal(form_cred._userPrincipal);
        return form_cred._userPrincipal;
      } else session.setAttribute(__J_AUTHENTICATED, null);
    } else if (realm instanceof SSORealm) {
      // Try a single sign on.
      Credential cred = ((SSORealm) realm).getSingleSignOn(httpRequest, httpResponse);

      if (httpRequest.hasUserPrincipal()) {
        form_cred = new FormCredential();
        form_cred._userPrincipal = request.getUserPrincipal();
        form_cred._jUserName = form_cred._userPrincipal.getName();
        if (cred != null) form_cred._jPassword = cred.toString();
        if (log.isDebugEnabled()) log.debug("SSO for " + form_cred._userPrincipal);

        httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
        session.setAttribute(__J_AUTHENTICATED, form_cred);
        return form_cred._userPrincipal;
      }
    }

    // Don't authenticate authform or errorpage
    if (isLoginOrErrorPage(pathInContext)) return SecurityConstraint.__NOBODY;

    // redirect to login page
    if (response != null) {
      if (httpRequest.getQuery() != null) uri += "?" + httpRequest.getQuery();
      session.setAttribute(
          __J_URI,
          request.getScheme()
              + "://"
              + request.getServerName()
              + ":"
              + request.getServerPort()
              + URI.addPaths(request.getContextPath(), uri));
      response.setContentLength(0);
      response.sendRedirect(
          response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formLoginPage)));
    }

    return null;
  }
예제 #8
0
  public void writeLandingPage(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String landingPage = getNewTokenLandingPage();

    /** default to current page * */
    if (landingPage == null) {
      StringBuilder sb = new StringBuilder();

      sb.append(request.getContextPath());
      sb.append(request.getServletPath());

      landingPage = sb.toString();
    }

    /** create auto posting form * */
    StringBuilder sb = new StringBuilder();

    sb.append("<html>\r\n");
    sb.append("<head>\r\n");
    sb.append("<title>OWASP CSRFGuard Project - New Token Landing Page</title>\r\n");
    sb.append("</head>\r\n");
    sb.append("<body>\r\n");
    sb.append("<script type=\"text/javascript\">\r\n");
    sb.append("var form = document.createElement(\"form\");\r\n");
    sb.append("form.setAttribute(\"method\", \"post\");\r\n");
    sb.append("form.setAttribute(\"action\", \"");
    sb.append(landingPage);
    sb.append("\");\r\n");

    /** only include token if needed * */
    if (isProtectedPage(landingPage)) {
      sb.append("var hiddenField = document.createElement(\"input\");\r\n");
      sb.append("hiddenField.setAttribute(\"type\", \"hidden\");\r\n");
      sb.append("hiddenField.setAttribute(\"name\", \"");
      sb.append(getTokenName());
      sb.append("\");\r\n");
      sb.append("hiddenField.setAttribute(\"value\", \"");
      sb.append(getTokenValue(request, landingPage));
      sb.append("\");\r\n");
      sb.append("form.appendChild(hiddenField);\r\n");
    }

    sb.append("document.body.appendChild(form);\r\n");
    sb.append("form.submit();\r\n");
    sb.append("</script>\r\n");
    sb.append("</body>\r\n");
    sb.append("</html>\r\n");

    String code = sb.toString();

    /** setup headers * */
    response.setContentType("text/html");
    response.setContentLength(code.length());

    /** write auto posting form * */
    OutputStream output = null;
    PrintWriter writer = null;

    try {
      output = response.getOutputStream();
      writer = new PrintWriter(output);

      writer.write(code);
      writer.flush();
    } finally {
      Writers.close(writer);
      Streams.close(output);
    }
  }
예제 #9
0
package com.jspsmart.upload;
예제 #10
0
  /**
   * Write a file to the response stream. Handles Range requests.
   *
   * @param req request
   * @param res response
   * @param file must exists and not be a directory
   * @param contentType must not be null
   * @throws IOException or error
   */
  public static void returnFile(
      HttpServletRequest req, HttpServletResponse res, File file, String contentType)
      throws IOException {
    res.setContentType(contentType);

    // see if its a Range Request
    boolean isRangeRequest = false;
    long startPos = 0, endPos = Long.MAX_VALUE;
    String rangeRequest = req.getHeader("Range");
    if (rangeRequest != null) { // bytes=12-34 or bytes=12-
      int pos = rangeRequest.indexOf("=");
      if (pos > 0) {
        int pos2 = rangeRequest.indexOf("-");
        if (pos2 > 0) {
          String startString = rangeRequest.substring(pos + 1, pos2);
          String endString = rangeRequest.substring(pos2 + 1);
          startPos = Long.parseLong(startString);
          if (endString.length() > 0) endPos = Long.parseLong(endString) + 1;
          isRangeRequest = true;
        }
      }
    }

    // set content length
    long fileSize = file.length();
    long contentLength = fileSize;
    if (isRangeRequest) {
      endPos = Math.min(endPos, fileSize);
      contentLength = endPos - startPos;
    }

    if (contentLength > Integer.MAX_VALUE)
      res.addHeader(
          "Content-Length", Long.toString(contentLength)); // allow content length > MAX_INT
    else res.setContentLength((int) contentLength); // note HEAD only allows this

    String filename = file.getPath();
    boolean debugRequest = Debug.isSet("returnFile");
    if (debugRequest)
      log.debug(
          "returnFile(): filename = "
              + filename
              + " contentType = "
              + contentType
              + " contentLength = "
              + contentLength);

    // indicate we allow Range Requests
    res.addHeader("Accept-Ranges", "bytes");

    if (req.getMethod().equals("HEAD")) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, 0));
      return;
    }

    try {

      if (isRangeRequest) {
        // set before content is sent
        res.addHeader("Content-Range", "bytes " + startPos + "-" + (endPos - 1) + "/" + fileSize);
        res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

        FileCacheRaf.Raf craf = null;
        try {
          craf = fileCacheRaf.acquire(filename);
          IO.copyRafB(
              craf.getRaf(), startPos, contentLength, res.getOutputStream(), new byte[60000]);
          log.info(
              "returnFile(): "
                  + UsageLog.closingMessageForRequestContext(
                      HttpServletResponse.SC_PARTIAL_CONTENT, contentLength));
          return;
        } finally {
          if (craf != null) fileCacheRaf.release(craf);
        }
      }

      // Return the file
      ServletOutputStream out = res.getOutputStream();
      IO.copyFileB(file, out, 60000);
      res.flushBuffer();
      out.close();
      if (debugRequest) log.debug("returnFile(): returnFile ok = " + filename);
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, contentLength));
    }

    // @todo Split up this exception handling: those from file access vs those from dealing with
    // response
    //       File access: catch and res.sendError()
    //       response: don't catch (let bubble up out of doGet() etc)
    catch (FileNotFoundException e) {
      log.error("returnFile(): FileNotFoundException= " + filename);
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (java.net.SocketException e) {
      log.info("returnFile(): SocketException sending file: " + filename + " " + e.getMessage());
      log.info("returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0));
    } catch (IOException e) {
      String eName =
          e.getClass().getName(); // dont want compile time dependency on ClientAbortException
      if (eName.equals("org.apache.catalina.connector.ClientAbortException")) {
        log.info(
            "returnFile(): ClientAbortException while sending file: "
                + filename
                + " "
                + e.getMessage());
        log.info(
            "returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0));
        return;
      }

      log.error("returnFile(): IOException (" + e.getClass().getName() + ") sending file ", e);
      log.error(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      if (!res.isCommitted())
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending file: " + e.getMessage());
    }
  }