/**
   * generate PDF file containing all site participant
   *
   * @param data
   */
  public void print_participant(String siteId) {

    HttpServletResponse res =
        (HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE);

    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();

    res.addHeader("Content-Disposition", "inline; filename=\"participants.pdf\"");
    res.setContentType("application/pdf");

    Document document = docBuilder.newDocument();

    // get the participant xml document
    generateParticipantXMLDocument(document, siteId);

    generatePDF(document, outByteStream);
    res.setContentLength(outByteStream.size());
    if (outByteStream.size() > 0) {
      // Increase the buffer size for more speed.
      res.setBufferSize(outByteStream.size());
    }

    /*
    // output xml for debugging purpose
    try
    {
    	TransformerFactory transformerFactory = TransformerFactory.newInstance();
           Transformer transformer = transformerFactory.newTransformer();
           DOMSource source = new DOMSource(document);
           StreamResult result =  new StreamResult(System.out);
           transformer.transform(source, result);
    }
    catch (Exception e)
    {

    }*/

    OutputStream out = null;
    try {
      out = res.getOutputStream();
      if (outByteStream.size() > 0) {
        outByteStream.writeTo(out);
      }
      res.setHeader("Refresh", "0");

      out.flush();
      out.close();
    } catch (Throwable ignore) {
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (Throwable ignore) {
        }
      }
    }
  }
示例#2
0
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   // TODO Auto-generated method stub
   HttpServletRequest httprequest = (HttpServletRequest) request;
   HttpServletResponse httpresponse = (HttpServletResponse) response;
   if ("Vision Browser/1.3.3".equals(httprequest.getHeader("User-Agent"))) // 全景30A
   {
     httpresponse.setBufferSize(Integer.parseInt(bufferSize));
   }
   chain.doFilter(request, response); // 继续执行下一个filter,注意filter执行的先后顺序
 }
示例#3
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String imagesPath = applicationConfiguration.getImagesPath();

    // get itemId parameter from request
    String imageName = request.getParameter("name");
    if (imageName == null) {
      return;
    }

    File imageFile = new File(imagesPath, imageName);

    if (imageFile.exists()) {
      // determine the content type of file - if it's not an image quit
      String contentType = getServletContext().getMimeType(imageFile.getName().toLowerCase());
      if (contentType == null || !contentType.startsWith("image")) {
        return;
      }

      // init servlet response
      response.reset();
      response.setBufferSize(DEFAULT_BUFFER_SIZE);
      response.setHeader("Content-Type", contentType);
      response.setHeader("Content-Length", String.valueOf(imageFile.length()));
      response.setHeader("Content-Disposition", "inline; filename=\"" + imageFile.getName() + "\"");

      long expiry = new Date().getTime() + CACHE_AGE * 1000;
      response.setDateHeader("Expires", expiry);
      response.setHeader("Cache-Control", "max-age=" + CACHE_AGE);

      // prepare streams
      BufferedInputStream input = null;
      BufferedOutputStream output = null;

      try {
        // open streams
        input = new BufferedInputStream(new FileInputStream(imageFile), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
        // write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
          output.write(buffer, 0, length);
        }
        // finalize task
        output.flush();
      } finally {
        // close streams
        output.close();
        input.close();
      }
    }
  }
  /**
   * Handle use of the REST api URL pattern /rest/find/[select]?[filter] and
   * /rest/count/[select]?[filter]<br>
   * [select] should be either an entity name like '/rest/find/sample?...' or an enumeration of
   * field names like 'sample.id,sample.name' (not yet implemented!)<br>
   * [filter] should be of form field1>=value1&field2=4&LIMIT=1&SORTASC=field1<br>
   * field names are need to be fully unique within the selection or fully qualified<br>
   * if fields are selected from multiple entities then a join path is automatically calculated
   * unless suitable join rules are defined like 'entity1.field1JOINentity2.field2'
   *
   * <p>Do we need enhancements: Aggregate functions and group by?
   */
  public static void handleRequest(
      HttpServletRequest request, HttpServletResponse response, Database db) {
    // setup the output-stream
    response.setBufferSize(10000);
    response.setContentType("text/html; charset=UTF-8");

    logger.info("starting REST request " + request.getPathInfo());
    long start_time = System.currentTimeMillis();

    if (request.getPathInfo().startsWith("/find") || request.getPathInfo().startsWith("/count"))
      handleRetrievalRequest(request, response, db);

    logger.info("servlet took: " + (System.currentTimeMillis() - start_time));
    logger.info("------------");
  }
示例#5
0
  // 연수행사 첨부파일 다운로드 (새글+답글 모두 이 uri를 이용함)
  @RequestMapping(value = "/trainingEvent_FileDownload.do")
  public void downloadFile(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uploadPath = file_path;
    String requestedFile = request.getParameter("attach_name");
    // String attach_path = request.getParameter("attach_path"); //파일과 모든 경로를 포함한 변수(향후 쓰일 수 있어
    // 주석처리함)

    File uFile = new File(uploadPath, requestedFile); // 경로,파일명으로 파일객체 생성
    int fSize = (int) uFile.length();
    boolean ctrl = uFile.exists(); // 파일존재유무

    if (ctrl) {
      BufferedInputStream in =
          new BufferedInputStream(new FileInputStream(uFile)); // 파일을 읽어오되 // 버퍼에

      String mimetype = "text/html";

      response.setBufferSize(fSize); // 버퍼크기설정
      response.setContentType(mimetype); // 컨텐츠형식설정
      response.setHeader("Content-Disposition", "attachment; filename=\"" + requestedFile + "\"");
      response.setContentLength(fSize); // 컨텐츠 본체의 길이

      FileCopyUtils.copy(in, response.getOutputStream());
      in.close();
      response.getOutputStream().flush();
      response.getOutputStream().close();
    } else { // 에러페이지 화면 구성
      // setContentType을 프로젝트 환경에 맞추어 변경
      response.setContentType("application/x-msdownload");
      PrintWriter printwriter = response.getWriter();
      printwriter.println("<html>");
      printwriter.println("<br><br><br><h2>다음 파일을 찾을 수 없습니다. </h2><br> 파일명 : " + requestedFile);
      printwriter.println(
          "<br><br><br><center><h3>이전페이지로 돌아가시려면 <a href='javascript: history.go(-1)'>여기</a>를 클릭하세요.</h3></center>");
      printwriter.println("<br><br><br>&copy; webAccess");
      printwriter.println("</html>");
      printwriter.flush();
      printwriter.close();
    }
  }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   Long pollid = (Long) req.getSession().getAttribute("pollID");
   List<PollOptionsEntry> votes = DAOProvider.getDao().getOptions(pollid);
   byte[] graphData = createGraphData(votes);
   resp.setContentType("png");
   resp.setBufferSize(graphData.length);
   OutputStream out = null;
   try {
     out = resp.getOutputStream();
     out.write(graphData);
     out.flush();
   } catch (IOException e) {
   } finally {
     if (out != null) {
       out.close();
     }
   }
 }
示例#7
0
 @Override
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String ctlExportKeyBase64 =
       URLDecoder.decode(request.getParameter(CTL_EXPORT_KEY_PARAMETER), "UTF-8");
   try {
     CtlSchemaExportKey key =
         (CtlSchemaExportKey) Base64.decodeToObject(ctlExportKeyBase64, Base64.URL_SAFE, null);
     FileData ctlExportData = cacheService.getExportedCtlSchema(key);
     ServletUtils.prepareDisposition(request, response, ctlExportData.getFileName());
     response.setContentType(ctlExportData.getContentType());
     response.setContentLength(ctlExportData.getFileData().length);
     response.setBufferSize(BUFFER);
     response.getOutputStream().write(ctlExportData.getFileData());
     response.flushBuffer();
   } catch (Exception e) {
     LOG.error("Unexpected error in CtlExportServlet.doGet: ", e);
     response.sendError(
         HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to get file: " + e.getMessage());
   }
 }
示例#8
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    final ServletContext servletContext = getServletContext();
    final ApplicationContext context =
        WebApplicationContextUtils.getWebApplicationContext(servletContext);
    DocumentDAO documentDAO = (DocumentDAO) context.getBean(DOCUMENT_BEAN_NAME);
    DocumentEntity documentEntity = null;
    // Get ID from request.
    String imageId = request.getParameter(ID);

    // Check if ID is supplied to the request.
    if (imageId == null) {
      // Do your thing if the ID is not supplied to the request.
      // Throw an exception, or send 404, or show default/warning image, or just ignore it.
      response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
      return;
    }

    // Lookup Image by ImageId in database.
    // Do your "SELECT * FROM Image WHERE ImageID" thing.
    // Image image = imageDAO.find(imageId);
    try {
      documentEntity = documentDAO.getDocument(imageId);
    } catch (BatchException e) {
      e.printStackTrace();
    }

    // Check if image is actually retrieved from database.
    if (documentEntity == null) {
      // Do your thing if the image does not exist in database.
      // Throw an exception, or send 404, or show default/warning image, or just ignore it.
      response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
      return;
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(documentEntity.getDocFile().length);
    response.setContentType(CONTENT_TYPE);
    response.setHeader(CONTENT_LENGTH, String.valueOf(documentEntity.getDocFile().length));
    // response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;
    InputStream inputStream = null;
    try {
      inputStream = new ByteArrayInputStream(documentEntity.getDocFile());

      // Open streams.
      input = new BufferedInputStream(inputStream);
      output = new BufferedOutputStream(response.getOutputStream());

      // Write file contents to response.
      byte[] buffer = new byte[documentEntity.getDocFile().length];
      int length;
      while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
      }
    } finally {
      // Gently close streams.
      close(output);
      close(input);
    }
  }
示例#9
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Get requested file by path info.
    String requestedFile = request.getPathInfo();

    // Check if file is actually supplied to the request URI.
    if (requestedFile == null) {
      // Do your thing if the file is not supplied to the request URI.
      // Throw an exception, or send 404, or show default/warning page, or just ignore it.
      response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
      return;
    }

    // Decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
      // Do your thing if the file appears to be non-existing.
      // Throw an exception, or send 404, or show default/warning page, or just ignore it.
      response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
      return;
    }

    if (file.isDirectory() && !requestedFile.endsWith("/")) {
      // System.out.println("redir");
      HttpServletResponse resp = (HttpServletResponse) response;
      HttpServletRequest req = (HttpServletRequest) request;
      response.sendRedirect(req.getContextPath() + requestedFile + "/");
    } else if (file.isDirectory()) {
      File defaultFile = getDefaultFile(file.getPath());
      System.out.println("getDefault:" + defaultFile.getPath());
      if (defaultFile.exists()) {
        // response.sendRedirect(defaultFile.getPath().replace(this.filePath,""));
        request
            .getRequestDispatcher(defaultFile.getPath().replace(this.filePath, ""))
            .forward(request, response);
      } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
      }
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName());

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
      contentType = "application/octet-stream";
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    // response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
      // Open streams.
      input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
      output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

      // Write file contents to response.
      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int length;
      while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
      }
    } finally {
      // Gently close streams.
      close(output);
      close(input);
    }
  }
  /**
   * Analyze a request and split this request's URI to get useful information then keep it in
   * following properties of PortalRequestContext :<br>
   * 1. <code>requestURI</code> : The decoded URI of this request <br>
   * 2. <code>portalOwner</code> : The portal name ( "classic" for instance )<br>
   * 3. <code>portalURI</code> : The URI to current portal ( "/portal/public/classic/ for instance )
   * <br>
   * 4. <code>nodePath</code> : The path that is used to reflect to a navigation node
   */
  public PortalRequestContext(
      WebuiApplication app,
      ControllerContext controllerContext,
      String requestSiteType,
      String requestSiteName,
      String requestPath,
      Locale requestLocale)
      throws Exception {
    super(app);

    //
    this.urlFactory = (URLFactoryService) PortalContainer.getComponent(URLFactoryService.class);
    this.controllerContext = controllerContext;

    //
    request_ = controllerContext.getRequest();
    response_ = controllerContext.getResponse();
    response_.setBufferSize(1024 * 100);
    setSessionId(request_.getSession().getId());

    // The encoding needs to be set before reading any of the parameters since the parameters's
    // encoding
    // is set at the first access.

    // TODO use the encoding from the locale-config.xml file
    response_.setContentType("text/html; charset=UTF-8");
    try {
      request_.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
      log.error("Encoding not supported", e);
    }

    // Query parameters from the request will be set in the servlet container url encoding and not
    // necessarly in utf-8 format. So we need to directly parse the parameters from the query
    // string.
    parameterMap = new HashMap<String, String[]>();
    parameterMap.putAll(request_.getParameterMap());
    String queryString = request_.getQueryString();
    if (queryString != null) {
      // The QueryStringParser currently only likes & and not &amp;
      queryString = queryString.replace("&amp;", "&");
      Map<String, String[]> queryParams =
          QueryStringParser.getInstance().parseQueryString(queryString);
      parameterMap.putAll(queryParams);
    }

    ajaxRequest_ = "true".equals(request_.getParameter("ajaxRequest"));
    String cache = request_.getParameter(CACHE_LEVEL);
    if (cache != null) {
      cacheLevel_ = cache;
    }

    requestURI_ = request_.getRequestURI();
    /*
          String decodedURI = URLDecoder.decode(requestURI_, "UTF-8");

          // req.getPathInfo will already have the encoding set from the server.
          // We need to use the UTF-8 value since this is how we store the portal name.
          // Reconstructing the getPathInfo from the non server decoded values.
          String servletPath = URLDecoder.decode(request_.getServletPath(), "UTF-8");
          String contextPath = URLDecoder.decode(request_.getContextPath(), "UTF-8");
          String pathInfo = "/";
          if (requestURI_.length() > servletPath.length() + contextPath.length())
             pathInfo = decodedURI.substring(servletPath.length() + contextPath.length());

          int colonIndex = pathInfo.indexOf("/", 1);
          if (colonIndex < 0)
          {
             colonIndex = pathInfo.length();
          }
          portalOwner_ = pathInfo.substring(1, colonIndex);
          nodePath_ = pathInfo.substring(colonIndex, pathInfo.length());
    */
    //
    this.siteKey = new SiteKey(SiteType.valueOf(requestSiteType.toUpperCase()), requestSiteName);
    this.nodePath_ = requestPath;
    this.requestLocale = requestLocale;

    //
    NodeURL url = createURL(NodeURL.TYPE);
    url.setResource(new NavigationResource(siteKey, ""));
    portalURI = url.toString();

    //
    urlBuilder = new PortalURLBuilder(this, createURL(ComponentURL.TYPE));
  }
 @Override
 public void setBufferSize(int i) {
   response.setBufferSize(i);
 }
示例#12
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    boolean orderCompleted = true;

    // Get the user's session and shopping cart
    HttpSession session = request.getSession(true);
    ResourceBundle messages = (ResourceBundle) session.getAttribute("messages");
    ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");

    if (cart == null) {
      cart = new ShoppingCart();
      session.setAttribute("cart", cart);
    }

    // Update the inventory
    try {
      utx.begin();
      bookDB.buyBooks(cart);
      utx.commit();
    } catch (Exception ex) {
      try {
        utx.rollback();
      } catch (Exception e) {
        System.out.println("Rollback failed: " + e.getMessage());
      }

      System.err.println(ex.getMessage());
      orderCompleted = false;
    }

    // Payment received -- invalidate the session
    session.invalidate();

    // set content type header before accessing the Writer
    response.setContentType("text/html");
    response.setBufferSize(8192);

    PrintWriter out = response.getWriter();

    // then write the response
    out.println(
        "<html>" + "<head><title>" + messages.getString("TitleReceipt") + "</title></head>");

    // Get the dispatcher; it gets the banner to the user
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");

    if (dispatcher != null) {
      dispatcher.include(request, response);
    }

    if (orderCompleted) {
      out.println("<h3>" + messages.getString("ThankYou") + request.getParameter("cardname") + ".");
    } else {
      out.println("<h3>" + messages.getString("OrderError"));
    }

    out.println(
        "<p> &nbsp; <p><strong><a href=\""
            + response.encodeURL(request.getContextPath())
            + "/bookstore\">"
            + messages.getString("ContinueShopping")
            + "</a> &nbsp; &nbsp; &nbsp;"
            + "</body></html>");
    out.close();
  }
示例#13
0
 public void setBufferSize(int size) {
   rawResponse.setBufferSize(size);
 }
示例#14
0
  /**
   * Serve the specified resource, optionally including the data content.
   *
   * @param request The servlet request we are processing
   * @param response The servlet response we are creating
   * @param content Should the content be included?
   * @param encoding The encoding to use if it is necessary to access the source as characters
   *     rather than as bytes
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a servlet-specified error occurs
   */
  protected void serveResource(
      HttpServletRequest request, HttpServletResponse response, boolean content, String encoding)
      throws IOException, ServletException {

    boolean serveContent = content;
    boolean debug = log.isDebug();

    // Identify the requested resource path
    String path = getRelativePath(request);
    if (debug) {
      if (serveContent)
        log.debug(
            "DefaultServlet.serveResource:  Serving resource '" + path + "' headers and data");
      else log.debug("DefaultServlet.serveResource:  Serving resource '" + path + "' headers only");
    }

    WebResourceRoot resources = getResources(request);
    WebResource resource = resources.getResource(path);

    if (!resource.exists()) {
      // Check if we're included so we can return the appropriate
      // missing resource name in the error
      String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
      if (requestUri == null) {
        requestUri = request.getRequestURI();
      } else {
        // We're included
        // SRV.9.3 says we must throw a FNFE
        throw new FileNotFoundException("defaultServlet.missingResource");
      }

      response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
      return;
    }

    // If the resource is not a collection, and the resource path
    // ends with "/" or "\", return NOT FOUND
    if (resource.isFile() && path.endsWith("/") || path.endsWith("\\")) {
      // Check if we're included so we can return the appropriate
      // missing resource name in the error
      String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
      if (requestUri == null) {
        requestUri = request.getRequestURI();
      }
      response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
      return;
    }

    boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;

    boolean included = false;
    // Check if the conditions specified in the optional If headers are
    // satisfied.
    if (resource.isFile()) {
      // Checking If headers
      included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
      if (!included && !isError && !checkIfHeaders(request, response, resource)) {
        return;
      }
    }

    // Find content type.
    String contentType = resource.getMimeType();
    if (contentType == null) {
      contentType = request.getServletContext().getMimeType(resource.getName());
      resource.setMimeType(contentType);
    }

    // These need to reflect the original resource, not the potentially
    // gzip'd version of the resource so get them now if they are going to
    // be needed later
    String eTag = null;
    String lastModifiedHttp = null;
    if (resource.isFile() && !isError) {
      eTag = resource.getETag();
      lastModifiedHttp = resource.getLastModifiedHttp();
    }

    // Serve a gzipped version of the file if present
    boolean usingGzippedVersion = false;
    if (gzip && !included && resource.isFile() && !path.endsWith(".gz")) {
      WebResource gzipResource = resources.getResource(path + ".gz");
      if (gzipResource.exists() && gzipResource.isFile()) {
        Collection<String> varyHeaders = response.getHeaders("Vary");
        boolean addRequired = true;
        for (String varyHeader : varyHeaders) {
          if ("*".equals(varyHeader) || "accept-encoding".equalsIgnoreCase(varyHeader)) {
            addRequired = false;
            break;
          }
        }
        if (addRequired) {
          response.addHeader("Vary", "accept-encoding");
        }
        if (checkIfGzip(request)) {
          response.addHeader("Content-Encoding", "gzip");
          resource = gzipResource;
          usingGzippedVersion = true;
        }
      }
    }

    ArrayList<Range> ranges = null;
    long contentLength = -1L;

    if (resource.isDirectory()) {
      contentType = "text/html;charset=UTF-8";
    } else {
      if (!isError) {
        if (useAcceptRanges) {
          // Accept ranges header
          response.setHeader("Accept-Ranges", "bytes");
        }

        // Parse range specifier
        ranges = parseRange(request, response, resource);

        // ETag header
        response.setHeader("ETag", eTag);

        // Last-Modified header
        response.setHeader("Last-Modified", lastModifiedHttp);
      }

      // Get content length
      contentLength = resource.getContentLength();
      // Special case for zero length files, which would cause a
      // (silent) ISE when setting the output buffer size
      if (contentLength == 0L) {
        serveContent = false;
      }
    }

    ServletOutputStream ostream = null;
    PrintWriter writer = null;

    if (serveContent) {
      // Trying to retrieve the servlet output stream
      try {
        ostream = response.getOutputStream();
      } catch (IllegalStateException e) {
        // If it fails, we try to get a Writer instead if we're
        // trying to serve a text file
        if (!usingGzippedVersion
            && ((contentType == null)
                || (contentType.startsWith("text"))
                || (contentType.endsWith("xml"))
                || (contentType.contains("/javascript")))) {
          writer = response.getWriter();
          // Cannot reliably serve partial content with a Writer
          ranges = FULL;
        } else {
          throw e;
        }
      }
    }

    // Check to see if a Filter, Valve of wrapper has written some content.
    // If it has, disable range requests and setting of a content length
    // since neither can be done reliably.
    ServletResponse r = response;
    long contentWritten = 0;
    while (r instanceof ServletResponseWrapper) {
      r = ((ServletResponseWrapper) r).getResponse();
    }

    if (contentWritten > 0) {
      ranges = FULL;
    }

    if (resource.isDirectory()
        || isError
        || ((ranges == null || ranges.isEmpty()) && request.getHeader("Range") == null)
        || ranges == FULL) {

      // Set the appropriate output headers
      if (contentType != null) {
        if (debug) log.debug("DefaultServlet.serveFile:  contentType='" + contentType + "'");
        response.setContentType(contentType);
      }
      if (resource.isFile() && contentLength >= 0 && (!serveContent || ostream != null)) {
        if (debug) log.debug("DefaultServlet.serveFile:  contentLength=" + contentLength);
        // Don't set a content length if something else has already
        // written to the response.
        if (contentWritten == 0) {
          response.setContentLengthLong(contentLength);
        }
      }

      InputStream renderResult = null;
      if (resource.isDirectory()) {
        if (serveContent) {
          // Serve the directory browser
          renderResult = null; // TODO tomcat render(getPathPrefix(request), resource);
        }
      }

      // Copy the input stream to our output stream (if requested)
      if (serveContent) {
        resource.increaseDownloadCount();

        try {
          response.setBufferSize(output);
        } catch (IllegalStateException e) {
          // Silent catch
        }

        if (ostream == null) {
          // Output via a writer so can't use sendfile or write
          // content directly.
          if (resource.isDirectory()) {
            renderResult = null; // render(getPathPrefix(request), resource);
          } else {
            renderResult = resource.getInputStream();
          }
          copy(resource, renderResult, writer, encoding);
        } else {
          // Output is via an InputStream
          if (resource.isDirectory()) {
            renderResult = null; // render(getPathPrefix(request), resource);
          } else {
            renderResult = resource.getInputStream();
          }
          // If a stream was configured, it needs to be copied to
          // the output (this method closes the stream)
          if (renderResult != null) {
            copy(renderResult, ostream);
          }
        }
      }

    } else {
      // download counter
      resource.increaseDownloadCount();

      if ((ranges == null) || (ranges.isEmpty())) return;

      // Partial content response.

      response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

      if (ranges.size() == 1) {

        Range range = ranges.get(0);
        response.addHeader(
            "Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);
        long length = range.end - range.start + 1;
        response.setContentLengthLong(length);

        if (contentType != null) {
          if (debug) log.debug("DefaultServlet.serveFile:  contentType='" + contentType + "'");
          response.setContentType(contentType);
        }

        if (serveContent) {
          try {
            response.setBufferSize(output);
          } catch (IllegalStateException e) {
            // Silent catch
          }
          if (ostream != null) {
            copy(resource, ostream, range);
          } else {
            // we should not get here
            throw new IllegalStateException();
          }
        }
      } else {
        response.setContentType("multipart/byteranges; boundary=" + mimeSeparation);
        if (serveContent) {
          try {
            response.setBufferSize(output);
          } catch (IllegalStateException e) {
            // Silent catch
          }
          if (ostream != null) {
            copy(resource, ostream, ranges.iterator(), contentType);
          } else {
            // we should not get here
            throw new IllegalStateException();
          }
        }
      }
    }
  }
示例#15
0
  private void processRequest(HttpServletRequest req, HttpServletResponse resp, boolean content)
      throws IOException {
    // Check existence

    final String requestedFile = req.getPathInfo();
    if (requestedFile == null) {
      resp.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    final File file = new File(basePath, URLDecoder.decode(requestedFile, "UTF-8"));
    if (!file.exists()) {
      resp.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // Check if file is not modified

    final String filename = file.getName();
    final long length = file.length();
    final long lastModified = file.lastModified();
    final String etag = filename + "_" + length + "_" + lastModified;

    final String ifNoneMatch = req.getHeader("If-None-Match");
    if (ifNoneMatch != null && FileServeUtil.matches(ifNoneMatch, etag)) {
      resp.setHeader("ETag", etag);
      resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
      return;
    }

    final long ifModifiedSince = req.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
      resp.setHeader("ETag", etag);
      resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
      return;
    }

    // Validate request headers for resume

    final String ifMatch = req.getHeader("If-Match");
    if (ifMatch != null && !FileServeUtil.matches(ifMatch, etag)) {
      resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
      return;
    }

    final long ifUnmodifiedSince = req.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
      resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
      return;
    }

    // Do byte-range requests used in resume

    final Range full = new Range(0, length - 1, length);
    final List<Range> ranges = new ArrayList<Range>();

    final String range = req.getHeader("Range");
    if (range != null) {
      // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
      if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
        resp.setHeader("Content-Range", "bytes */" + length);
        resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        return;
      }

      // If-Range header should either match ETag or be greater then LastModified. If not,
      // then return full file.
      final String ifRange = req.getHeader("If-Range");
      if (ifRange != null && !ifRange.equals(etag)) {
        try {
          final long ifRangeTime = req.getDateHeader("If-Range"); // Throws IAE if invalid.
          if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
            ranges.add(full);
          }
        } catch (IllegalArgumentException ignore) {
          ranges.add(full);
        }
      }

      // If any valid If-Range header, then process each part of byte range.
      if (ranges.isEmpty()) {
        for (String part : range.substring(6).split(",")) {
          // Assuming a file with length of 100, the following examples returns bytes at:
          // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
          long start = FileServeUtil.sublong(part, 0, part.indexOf("-"));
          long end = FileServeUtil.sublong(part, part.indexOf("-") + 1, part.length());

          if (start == -1) {
            start = length - end;
            end = length - 1;
          } else if (end == -1 || end > length - 1) {
            end = length - 1;
          }

          // Check if Range is syntactically valid. If not, then return 416.
          if (start > end) {
            resp.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
          }

          // Add range.
          ranges.add(new Range(start, end, length));
        }
      }
    }

    // Prepare and initialize response

    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = getServletContext().getMimeType(filename);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    if (contentType == null) {
      contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding is supported by
    // the browser and expand content type with the one and right character encoding.
    if (contentType.startsWith("text")) {
      String acceptEncoding = req.getHeader("Accept-Encoding");
      acceptsGzip = acceptEncoding != null && FileServeUtil.accepts(acceptEncoding, "gzip");
      contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content type is supported by
    // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
      String accept = req.getHeader("Accept");
      disposition =
          accept != null && FileServeUtil.accepts(accept, contentType) ? "inline" : "attachment";
    }

    resp.reset();
    resp.setBufferSize(DEFAULT_BUFFER_SIZE);
    resp.setHeader("Content-Disposition", disposition + ";filename=\"" + filename + "\"");
    resp.setHeader("Accept-Ranges", "bytes");
    resp.setHeader("ETag", etag);
    resp.setDateHeader("Last-Modified", lastModified);
    resp.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send the requested file or parts to the client

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
      // Open streams.
      input = new RandomAccessFile(file, "r");
      output = resp.getOutputStream();

      if (ranges.isEmpty() || ranges.get(0) == full) {
        // Return full file.
        Range r = full;
        resp.setContentType(contentType);
        resp.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

        if (content) {
          if (acceptsGzip) {
            // The browser accepts GZIP, so GZIP the content.
            resp.setHeader("Content-Encoding", "gzip");
            output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
          } else {
            // Content length is not directly predictable in case of GZIP.
            // So only add it if there is no means of GZIP, else browser will hang.
            resp.setHeader("Content-Length", String.valueOf(r.length));
          }

          // Copy full range.
          FileServeUtil.copy(input, output, r.start, r.length, DEFAULT_BUFFER_SIZE);
        }
      } else if (ranges.size() == 1) {
        // Return single part of file.
        Range r = ranges.get(0);
        resp.setContentType(contentType);
        resp.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
        resp.setHeader("Content-Length", String.valueOf(r.length));
        resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

        if (content) {
          // Copy single part range.
          FileServeUtil.copy(input, output, r.start, r.length, DEFAULT_BUFFER_SIZE);
        }
      } else {
        // Return multiple parts of file.
        resp.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
        resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

        if (content) {
          // Cast back to ServletOutputStream to get the easy println methods.
          ServletOutputStream sos = (ServletOutputStream) output;

          // Copy multi part range.
          for (Range r : ranges) {
            // Add multipart boundary and header fields for every range.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY);
            sos.println("Content-Type: " + contentType);
            sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

            // Copy single part range of multi part range.
            FileServeUtil.copy(input, output, r.start, r.length, DEFAULT_BUFFER_SIZE);
          }

          // End with multipart boundary.
          sos.println();
          sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
      }
    } finally {
      // Gently close streams.
      FileServeUtil.close(output);
      FileServeUtil.close(input);
    }
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    if (request.isUserInRole(UserManager.MONITOR)
        || request.isUserInRole(UserManager.OPSUISER)
        || request.isUserInRole(UserManager.OPSADMIN)) {
      try {
        // Get request parameters
        String arg0 = request.getParameter("arg0");
        String arg1 = request.getParameter("arg1");
        if (arg0 == null || arg1 == null) {
          response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
          return;
        }
        boolean thresholdOnly = arg0.toUpperCase().equals("TRUE");
        int days = 7;
        try {
          days = Integer.valueOf(arg1);
        } catch (NumberFormatException e) {
          response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
          return;
        }

        // Retrieve data.
        KcbReportBean[] list;
        if (thresholdOnly) {
          list = KcbReportDBWrapper.getDepletionThresholdReportData(days);
        } else {
          list = KcbReportDBWrapper.getDepletionReportData(days);
        }
        byte[] bytes =
            CsvExportUtil.getDepletionReportExportCsvString(Arrays.asList(list), days).getBytes();
        InputStream content = new ByteArrayInputStream(bytes);

        // Init servlet response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType("application/csv");
        response.setHeader("Content-Length", String.valueOf(bytes.length));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + FILE_NAME + "\"");

        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
          // Open streams.
          input = new BufferedInputStream(content, DEFAULT_BUFFER_SIZE);
          output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

          // Write file contents to response.
          byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
          int length;
          while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
          }
        } finally {
          // Gently close streams.
          close(output);
          close(input);
        }

      } catch (DataSourceLookupException e) {
        logger.log(Level.ERROR, "Failed to access database to create export file.");
      } catch (DataAccessException e) {
        logger.log(Level.ERROR, "Failed to retrieve export data from database.");
      }

    } else { // show 404 if user not in valid role.
      response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
      return;
    }
  }
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    // PrintWriter out = response.getWriter();
    try {
      System.out.println("doGet(HttpServletRequest request, HttpServletResponse response)");
      // Get requested file by path info.
      String requestedFile = request.getPathInfo();
      requestedFile = request.getParameter("fileName");

      System.out.println("requestedFile: " + requestedFile);

      // Check if file is actually supplied to the request URI.
      if (requestedFile == null) {
        // Do your thing if the file is not supplied to the request URI.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
      }
      // Decode the file name (might contain spaces and on) and prepare file object.
      File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));

      System.out.println("file: " + file.getAbsolutePath());

      // Check if file actually exists in filesystem.
      if (!file.exists()) {
        System.out.println("file not exists: " + file.getAbsolutePath());
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
      }
      // Get content type by filename.
      String contentType = "text/html";

      // Init servlet response.
      response.reset();
      response.setBufferSize(DEFAULT_BUFFER_SIZE);
      response.setContentType(contentType);
      response.setHeader("Content-Length", String.valueOf(file.length()));

      // This was used for CSV as sent as an attachment
      // response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() +
      // "\"");

      // Prepare streams.
      BufferedInputStream input = null;
      BufferedOutputStream output = null;

      try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
          output.write(buffer, 0, length);
        }
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        // Gently close streams.
        close(output);
        close(input);
      }
    } finally {
      // out.close();
    }
  }
 public synchronized void setBufferSize(int arg0) {
   actualResponse.setBufferSize(arg0);
 }
示例#19
0
  /**
   * Stream invoice
   *
   * @param request request
   * @param response response
   * @return "" or error message
   */
  private String streamInvoice(HttpServletRequest request, HttpServletResponse response) {
    int MIN_SIZE = 2000; // 	if not created size is 1015

    //	Get Invoice ID
    int C_Invoice_ID = WebUtil.getParameterAsInt(request, "Invoice_ID");
    if (C_Invoice_ID == 0) {
      log.fine("No ID)");
      return "No Invoice ID";
    }

    //	Get Invoice
    Properties ctx = JSPEnv.getCtx(request);
    MInvoice invoice = new MInvoice(ctx, C_Invoice_ID, null);
    if (invoice.getC_Invoice_ID() != C_Invoice_ID) {
      if (log.isLoggable(Level.FINE)) log.fine("Invoice not found - ID=" + C_Invoice_ID);
      return "Invoice not found";
    }
    //	Get WebUser & Compare with invoice
    HttpSession session = request.getSession(true);
    WebUser wu = (WebUser) session.getAttribute(WebUser.NAME);
    if (wu.getC_BPartner_ID() != invoice.getC_BPartner_ID()) {
      log.warning(
          "Invoice from BPartner - C_Invoice_ID="
              + C_Invoice_ID
              + " - BP_Invoice="
              + invoice.getC_BPartner_ID()
              + " = BP_Web="
              + wu.getC_BPartner_ID());
      return "Your invoice not found";
    }

    //	Check Directory
    String dirName = ctx.getProperty("documentDir", ".");
    try {
      File dir = new File(dirName);
      if (!dir.exists()) dir.mkdir();
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Could not create directory " + dirName, ex);
      return "Streaming error - directory";
    }
    //	Check if Invoice already created
    String fileName = invoice.getPDFFileName(dirName);
    File file = new File(fileName);
    if (file.exists() && file.isFile() && file.length() > MIN_SIZE) {
      if (log.isLoggable(Level.INFO))
        log.info("Existing: " + file + " - " + new Timestamp(file.lastModified()));
    } else {
      if (log.isLoggable(Level.INFO)) log.info("New: " + fileName);
      file = invoice.createPDF(file);
      if (file != null) {
        invoice.setDatePrinted(new Timestamp(System.currentTimeMillis()));
        invoice.saveEx();
      }
    }
    //	Issue Error
    if (file == null || !file.exists() || file.length() < MIN_SIZE) {
      log.warning("File does not exist - " + file);
      return "Streaming error - file";
    }

    //	Send PDF
    try {
      int bufferSize = 2048; // 	2k Buffer
      int fileLength = (int) file.length();
      //
      response.setContentType("application/pdf");
      response.setBufferSize(bufferSize);
      response.setContentLength(fileLength);
      //
      if (log.isLoggable(Level.FINE)) log.fine(file.getAbsolutePath() + ", length=" + fileLength);
      long time = System.currentTimeMillis(); // 	timer start
      //
      FileInputStream in = new FileInputStream(file);
      ServletOutputStream out = response.getOutputStream();
      byte[] buffer = new byte[bufferSize];
      double totalSize = 0;
      int count = 0;
      do {
        count = in.read(buffer, 0, bufferSize);
        if (count > 0) {
          totalSize += count;
          out.write(buffer, 0, count);
        }
      } while (count != -1);
      out.flush();
      out.close();
      //
      in.close();
      time = System.currentTimeMillis() - time;
      double speed = (totalSize / 1024) / ((double) time / 1000);
      if (log.isLoggable(Level.FINE))
        log.fine("Length=" + totalSize + " - " + time + " ms - " + speed + " kB/sec");
    } catch (IOException ex) {
      log.log(Level.SEVERE, ex.toString());
      return "Streaming error";
    }

    return null;
  } //	streamInvoice
 @Override
 public void setBufferSize(int size) {
   response.setBufferSize(size);
 }