Java Code Examples for javax.servlet.http.HttpServletResponse#setBufferSize()

The following examples show how to use javax.servlet.http.HttpServletResponse#setBufferSize() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: olat   File: StaticsLegacyDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Copy the contents of the file to the servlet's outputstream.
 * 
 * @param response
 * @throws IOException
 */
private void copyContent(final HttpServletResponse response, final InputStream istream) throws IOException {

    // Copy resource to output stream
    ServletOutputStream ostream = null;
    try {
        response.setBufferSize(outputBufferSize);
        ostream = response.getOutputStream();

        int len;
        final byte buffer[] = new byte[inputBufferSize];
        while ((len = istream.read(buffer)) != -1) {
            ostream.write(buffer, 0, len);
        }
    } finally {
        istream.close();
    }
    ostream.flush();
}
 
Example 2
Source Project: olat   File: StaticsLegacyDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Copy the contents of the file to the servlet's outputstream.
 * 
 * @param response
 * @throws IOException
 */
private void copyContent(final HttpServletResponse response, final InputStream istream) throws IOException {

    // Copy resource to output stream
    ServletOutputStream ostream = null;
    try {
        response.setBufferSize(outputBufferSize);
        ostream = response.getOutputStream();

        int len;
        final byte buffer[] = new byte[inputBufferSize];
        while ((len = istream.read(buffer)) != -1) {
            ostream.write(buffer, 0, len);
        }
    } finally {
        istream.close();
    }
    ostream.flush();
}
 
Example 3
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setBufferSize(bufferSize);

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    resp.setContentLength(responseSize);

    PrintWriter pw = resp.getWriter();
    for (int i = 0; i < responseSize; i++) {
        pw.append('X');
    }
}
 
Example 4
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setBufferSize(bufferSize);

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    resp.setContentLength(responseSize);

    PrintWriter pw = resp.getWriter();
    for (int i = 0; i < responseSize; i++) {
        pw.append('X');
    }
}
 
Example 5
Source Project: mumu   File: ExportController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 导出
 * @param modelName 模型名称
 * @param excelType excel格式
 * @param response
 * @return
 * @throws IOException
 */
@RequestMapping(value = { "/excel/{modelName}","/excel/{modelName}/{excelType}" }, method = RequestMethod.GET)
public void exportExcel(@PathVariable String modelName,@PathVariable(required = false) String excelType, HttpServletResponse response) throws IOException {
    //默认导出xls格式excel
    if(excelType==null||"".equals(excelType)){
        excelType="XLS";
    }
    List<SysExportModel> models = modelService.queryExportModelByCondition(modelName);
    // 模型不存在 直接结束
    if (models == null || models.size() == 0) {
        return;
    }
    // 获取导出数据
    SysExportModel model = models.get(0);
    List<List<Object>> exportData = commonService.getAllData(model.getModelName(), model.getEnames(), null);
    List<String> exportHeaderNames = new ArrayList<String>();
    String[] headerNames = model.getCnames().split(",");
    for (String headerName : headerNames) {
        exportHeaderNames.add(headerName);
    }

    response.reset();
    // 文件下载
    response.setContentType("application/vnd.ms-excel");
    String filename = "报表"+modelName+"("+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ ")";

    filename = new String(filename.getBytes("gbk"), "iso-8859-1");
    response.setHeader("Content-disposition", "attachment;filename="+ filename + "."+excelType.toLowerCase());
    response.setBufferSize(1024);

    //获取excel表单
    ExcelGenerater excelGenerater=new ExcelGenerater();
    ExcelGeneraterBean excelGeneraterBean = excelGenerater.create(modelName, exportHeaderNames, exportData);
    Workbook workbook = excelGeneraterBean.getWorkbook();
    //写入数据 到流
    workbook.write(response.getOutputStream());
    workbook.close();
}
 
Example 6
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setBufferSize(bufferSize);

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    resp.setContentLength(responseSize);

    PrintWriter pw = resp.getWriter();
    for (int i = 0; i < responseSize; i++) {
        pw.append('X');
    }
}
 
Example 7
/**
 * Sends content by copying all bytes from the input stream to the response setting the preferred buffer
 * size. At the end, it flushes response buffer. Passed in {@link InputStream} is fully consumed and closed.
 * The passed in {@link HttpServletResponse} after this call returns is committed and flushed.
 */
public static void sendContent(final InputStream input, final HttpServletResponse response) throws IOException {
  int bufferSize = BUFFER_SIZE;
  if (bufferSize < 1) {
    // if no user override, ask container for bufferSize
    bufferSize = response.getBufferSize();
    if (bufferSize < 1) {
      bufferSize = 8192;
      response.setBufferSize(bufferSize);
    }
  }
  else {
    // user override present, tell container what buffer size we'd like
    response.setBufferSize(bufferSize);
  }
  try (final InputStream from = input; final OutputStream to = response.getOutputStream()) {
    final byte[] buf = new byte[bufferSize];
    while (true) {
      int r = from.read(buf);
      if (r == -1) {
        break;
      }
      to.write(buf, 0, r);
    }
    response.flushBuffer();
  }
}
 
Example 8
private String doDownload() {
    String errorMsg = null;
    DocStoreClient client = ResourceManager.getInstance().getClients().getDocStoreClient();
    if (client != null) {
        try {
            YDocument doc = client.getDocument(docID, client.getHandle());
            if (doc.getDocument() != null) {
                FacesContext context = FacesContext.getCurrentInstance();
                HttpServletResponse response =
                        ( HttpServletResponse ) context.getExternalContext().getResponse();
                response.setContentType("multipart/form-data");
                response.setBufferSize(doc.getDocumentSize());
                response.setHeader("Content-Disposition",
                        "attachment;filename=\"" + docName + "\"");
                OutputStream os = response.getOutputStream();
                os.write(doc.getDocument());
                os.flush();
                os.close();
                FacesContext.getCurrentInstance().responseComplete();
            }
            else errorMsg = "Unable to download document: unknown document id.";
        }
        catch (IOException ioe) {
            errorMsg = "Unable to download document. Please see the log for details.";
        }
    }
    else errorMsg = "Unable to download document: missing Document Store.";

    return errorMsg;
}
 
Example 9
/**
 * Writes a binary file to a response's output stream
 *
 * @param res the response
 * @param doc a YDocument wrapper containing the binary file
 * @throws IOException if there's a problem writing to the stream
 */
private void writeDocument(HttpServletResponse res, YDocument doc) throws IOException {
    if (doc != null) {
        res.setContentType("multipart/form-data");
        res.setBufferSize(doc.getDocumentSize());
        ServletOutputStream out = res.getOutputStream();
        out.write(doc.getDocument());
        out.flush();
        out.close();
    }
}
 
Example 10
/**
 * Copy the contents of the specified input stream to the specified output stream, and ensure that
 * both streams are closed before returning (even in the face of an exception).
 *
 * @param repoItemHttpElem
 *          The cache entry for the source resource
 * @param response
 *          The response we are writing to
 * @param range
 *          Range asked by the client
 * @exception IOException
 *              if an input/output error occurs
 */
protected void copy(RepositoryHttpEndpointImpl repoItemHttpElem, HttpServletResponse response,
    Range range) throws IOException {

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

  IOException exception;

  try (ServletOutputStream ostream = response.getOutputStream()) {
    try (InputStream istream = new BufferedInputStream(
        repoItemHttpElem.createRepoItemInputStream(), INPUT_BUFFER_SIZE)) {

      if (range != null) {
        exception = copyStreamsRange(istream, ostream, range);
      } else {
        exception = copyStreams(istream, ostream);
      }

    }
  }

  // Rethrow any exception that has occurred
  if (exception != null) {
    throw exception;
  }
}
 
Example 11
/**
 * <p>
 * Write response with target relation and publishes events concerning the
 * download progress based on given update action status.
 * </p>
 *
 * <p>
 * The request supports RFC7233 range requests.
 * </p>
 *
 * @param artifact
 *            the artifact
 * @param filename
 *            to be written to the client response
 * @param lastModified
 *            unix timestamp of the artifact
 * @param response
 *            to be sent back to the requesting client
 * @param request
 *            from the client
 * @param progressListener
 *            to write progress updates to
 *
 * @return http response
 *
 * @see <a href="https://tools.ietf.org/html/rfc7233">https://tools.ietf.org
 *      /html/rfc7233</a>
 * 
 * @throws FileStreamingFailedException
 *             if streaming fails
 */
public static ResponseEntity<InputStream> writeFileResponse(final AbstractDbArtifact artifact,
        final String filename, final long lastModified, final HttpServletResponse response,
        final HttpServletRequest request, final FileStreamingProgressListener progressListener) {

    ResponseEntity<InputStream> result;

    final String etag = artifact.getHashes().getSha1();
    final long length = artifact.getSize();

    response.reset();
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
    response.setHeader(HttpHeaders.ETAG, etag);
    response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
    // set the x-content-type options header to prevent browsers from doing
    // MIME-sniffing when downloading an artifact, as this could cause a
    // security vulnerability
    response.setHeader(com.google.common.net.HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff");
    if (lastModified > 0) {
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
    }

    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    response.setBufferSize(BUFFER_SIZE);

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

    // Validate and process Range and If-Range headers.
    final String range = request.getHeader("Range");
    if (lastModified > 0 && range != null) {
        LOG.debug("range header for filename ({}) is: {}", filename, range);

        // Range header matches"bytes=n-n,n-n,n-n..."
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length);
            LOG.debug("range header for filename ({}) is not satisfiable: ", filename);
            return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
        }

        // RFC: if the representation is unchanged, send me the part(s) that
        // I am requesting in
        // Range; otherwise, send me the entire representation.
        checkForShortcut(request, etag, lastModified, full, ranges);

        // it seems there are valid ranges
        result = extractRange(response, length, ranges, range);
        // return if range extraction turned out to be invalid
        if (result != null) {
            return result;
        }
    }

    // full request - no range
    if (ranges.isEmpty() || ranges.get(0).equals(full)) {
        LOG.debug("filename ({}) results into a full request: ", filename);
        result = handleFullFileRequest(artifact, filename, response, progressListener, full);
    }
    // standard range request
    else if (ranges.size() == 1) {
        LOG.debug("filename ({}) results into a standard range request: ", filename);
        result = handleStandardRangeRequest(artifact, filename, response, progressListener, ranges);
    }
    // multipart range request
    else {
        LOG.debug("filename ({}) results into a multipart range request: ", filename);
        result = handleMultipartRangeRequest(artifact, filename, response, progressListener, ranges);
    }

    return result;
}
 
Example 12
/**
 * Copy the contents of the specified input stream to the specified output stream, and ensure that
 * both streams are closed before returning (even in the face of an exception).
 *
 * @param repoItemHttpElem
 *          The cache entry for the source resource
 * @param response
 *          The response we are writing to
 * @param ranges
 *          Enumeration of the ranges the client wanted to retrieve
 * @param contentType
 *          Content type of the resource
 * @exception IOException
 *              if an input/output error occurs
 */
protected void copy(RepositoryHttpEndpointImpl repoItemHttpElem, HttpServletResponse response,
    List<Range> ranges, String contentType) throws IOException {

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

  IOException exception = null;
  try (ServletOutputStream ostream = response.getOutputStream()) {

    for (Range currentRange : ranges) {

      try (InputStream istream = new BufferedInputStream(
          repoItemHttpElem.createRepoItemInputStream(), INPUT_BUFFER_SIZE)) {

        // Writing MIME header.
        ostream.println();
        ostream.println("--" + MIME_SEPARATION);

        if (contentType != null) {
          ostream.println("Content-Type: " + contentType);
        }

        ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end
            + "/" + currentRange.length);
        ostream.println();

        exception = copyStreamsRange(istream, ostream, currentRange);

        if (exception != null) {
          break;
        }
      }
    }

    ostream.println();
    ostream.print("--" + MIME_SEPARATION + "--");
  }
  // Rethrow any exception that has occurred
  if (exception != null) {
    throw exception;
  }

}