Java 类javax.servlet.ServletOutputStream 实例源码

项目:ssm-rbac    文件:PublicController.java   
/**
 * 生成验证码的逻辑
 */
@RequestMapping("verify")
private ModelAndView verify(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("image/jpeg");
    String capText = captchaProducer.createText();
    session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    BufferedImage bi = captchaProducer.createImage(capText);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(bi, "jpg", out);
    try {
        out.flush();
    } finally {
        out.close();
    }
    return null;
}
项目:dremio-oss    文件:AccessLogFilter.java   
@Override
public ServletOutputStream getOutputStream() throws IOException {

  final ServletOutputStream outputStream = d.getOutputStream();
  return new ServletOutputStream() {

    @Override
    public void write(int b) throws IOException {
      respBody.write(b);
      outputStream.write(b);
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {
      outputStream.setWriteListener(writeListener);
    }

    @Override
    public boolean isReady() {
      return outputStream.isReady();
    }
  };
}
项目:plumdo-stock    文件:RequestLogFilter.java   
private void updateResponse(String requestURI, ContentCachingResponseWrapper responseWrapper) throws IOException {
    try {
        HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
        byte[] body = responseWrapper.getContentAsByteArray();
        ServletOutputStream outputStream = rawResponse.getOutputStream();
        if (rawResponse.isCommitted()) {
            if (body.length > 0) {
                StreamUtils.copy(body, outputStream);
            }
        } else {
            if (body.length > 0) {
                rawResponse.setContentLength(body.length);
                StreamUtils.copy(body, rawResponse.getOutputStream());
            }
        }
        finishResponse(outputStream, body);
    } catch (Exception ex) {
        logger.error("请求地址为" + requestURI + "的连接返回报文失败,原因是{}", ex.getMessage());
    }
}
项目:lams    文件:MonitoringAction.java   
/**
    * Exports tool results into excel.
    * 
    * @throws IOException
    */
   private ActionForward exportExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException {

initializeScratchieService();
String sessionMapID = request.getParameter(ScratchieConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
    .getAttribute(sessionMapID);
Scratchie scratchie = (Scratchie) sessionMap.get(ScratchieConstants.ATTR_SCRATCHIE);

LinkedHashMap<String, ExcelCell[][]> dataToExport = service.exportExcel(scratchie.getContentId());

String fileName = "scratchie_export.xlsx";
fileName = FileUtil.encodeFilenameForDownload(request, fileName);

response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

// set cookie that will tell JS script that export has been finished
String downloadTokenValue = WebUtil.readStrParam(request, "downloadTokenValue");
Cookie fileDownloadTokenCookie = new Cookie("fileDownloadToken", downloadTokenValue);
fileDownloadTokenCookie.setPath("/");
response.addCookie(fileDownloadTokenCookie);

// Code to generate file and write file contents to response
ServletOutputStream out = response.getOutputStream();
ExcelUtil.createExcel(out, dataToExport, null, false);

return null;
   }
项目:validator-web    文件:AbstractView.java   
/**
 * Write the given temporary OutputStream to the HTTP response.
 * @param response current HTTP response
 * @param baos the temporary OutputStream to write
 * @throws IOException if writing/flushing failed
 */
protected void writeToResponse(HttpServletResponse response, ByteArrayOutputStream baos) throws IOException {
    // Write content type and also length (determined via byte array).
    response.setContentType(getContentType());
    response.setContentLength(baos.size());

    // Flush byte array to servlet output stream.
    ServletOutputStream out = response.getOutputStream();
    baos.writeTo(out);
    out.flush();
}
项目:my-spring-boot-project    文件:SysLoginController.java   
@RequestMapping("captcha.jpg")
public void captcha(HttpServletResponse response) throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setContentType("image/jpeg");

    //生成文字验证码
    String text = producer.createText();
    //生成图片验证码
    BufferedImage image = producer.createImage(text);
    //保存到shiro session
    ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(image, "jpg", out);
    IOUtils.closeQuietly(out);


}
项目:simple-hostel-management    文件:AdministrationController.java   
@RequestMapping(value = Mappings.ADMINISTRATION_EXPORT_RESERVATIONS_CSV, method = RequestMethod.GET)
public void exportReservationsCsv(
        @RequestParam("begin") String begin,
        @RequestParam("end") String end,
        HttpServletResponse response) throws Exception {

    Date beginDate = Utils.stringToDate(begin);
    Date endDate = Utils.stringToDate(end);

    response.setContentType("text/csv");
    response.setHeader("Content-disposition", "attachment; filename=\"export.csv\"");

    File tempFile = exportService.exportReserationsCsv(beginDate, endDate);

    try (ServletOutputStream out = response.getOutputStream();
         InputStream in = Files.newInputStream(tempFile.toPath())) {
        IOUtils.copy(in, out);
    }

    Files.delete(tempFile.toPath());

}
项目:membrane-spring-boot-starter    文件:HttpServletHandler.java   
@SuppressWarnings("deprecation")
protected void writeResponse(Response res) throws Exception {
    response.setStatus(res.getStatusCode(), res.getStatusMessage());
    for (HeaderField header : res.getHeader().getAllHeaderFields()) {
        if (header.getHeaderName().equals(Header.TRANSFER_ENCODING))
            continue;
        response.addHeader(header.getHeaderName().toString(), header.getValue());
    }

    ServletOutputStream out = response.getOutputStream();
    res.getBody().write(new PlainBodyTransferrer(out));
    out.flush();

    response.flushBuffer();

    exchange.setTimeResSent(System.currentTimeMillis());
    exchange.collectStatistics();
}
项目:jerrydog    文件:DefaultServlet.java   
/**
 * 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 istream The input stream to read from
 * @param ostream The output stream to write to
 * @return Exception which occurred during processing
 */
private IOException copyRange(InputStream istream,
                              ServletOutputStream ostream) {

    // Copy the input stream to the output stream
    IOException exception = null;
    byte buffer[] = new byte[input];
    int len = buffer.length;
    while (true) {
        try {
            len = istream.read(buffer);
            if (len == -1)
                break;
            ostream.write(buffer, 0, len);
        } catch (IOException e) {
            exception = e;
            len = -1;
            break;
        }
    }
    return exception;

}
项目:renren-fast    文件:SysLoginController.java   
@RequestMapping("captcha.jpg")
public void captcha(HttpServletResponse response)throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setContentType("image/jpeg");

    //生成文字验证码
    String text = producer.createText();
    //生成图片验证码
    BufferedImage image = producer.createImage(text);
    //保存到shiro session
    ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(image, "jpg", out);
    IOUtils.closeQuietly(out);
}
项目:maildump    文件:EmailController.java   
@RequestMapping(value = "/email/attachment/{id}",method = RequestMethod.GET)
public void getAttachmentContent(@PathVariable("id") Long id, HttpServletResponse response) {

    final AttachmentEntity attachment = attachmentService.findAttachmentById(id);

    if (attachment != null) {
        try {
            ServletOutputStream stream = response.getOutputStream();
            OutputStream out = new BufferedOutputStream(stream);

            response.resetBuffer();
            response.setBufferSize(attachment.getAttachmentContent().getData().length);
            response.setHeader("Content-Length", String.valueOf(attachment.
                       getAttachmentContent().getData().length));

            out.write(attachment.getAttachmentContent().getData());

            out.close();
            stream.close();
        } catch (final IOException e) {
            log.error("Unable to open file", e);
        }
    } else {
        log.error("File does not exist");
    }
}
项目:ProxyPool    文件:CommonController.java   
@RequestMapping(value="/launchjob")
@ResponseBody
public void startJob(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

    log.info("manual startJob");
    try {
        httpServletResponse.setContentType("text/plain; charset=utf-8");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        if(scheduleJobs.getJobStatus() == ScheduleJobs.JOB_STATUS_RUNNING) {
            responseOutputStream.write("Job正在运行。。。".getBytes("utf-8"));
            responseOutputStream.flush();
            responseOutputStream.close();
        } else {
            log.info("scheduleJobs.cronJob() start by controller...");
            scheduleJobs.cronJob();
        }
    } catch (Exception e) {
        log.info("startJob exception e="+e.getMessage());
    }
}
项目:strictfp-back-end    文件:GetQuiz.java   
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    HashMap<String, Object> status = new HashMap<>();
    JSONObject object = new JSONObject();
    String quizFormName = req.getParameter("name");
    // get main data
    QuizForm qf = allQuizForm.get(quizFormName);
    // build status
    status.put("code", String.valueOf(HttpServletResponse.SC_OK));
    status.put("message", "query quiz form successful");
    status.put("extra", Constant.JSON.EMPTY_OBJECT);
    status.put("security", Constant.JSON.EMPTY_OBJECT);
    // build main object
    object.put("meta", status);
    object.put("data", qf);
    // FIXME 非测试时移去注释 (配合Configuration System把这里设计的合理一点 - 磷)
    // response.setContentType("application/json"); // specific content type
    try (ServletOutputStream out = resp.getOutputStream()) {
        out.write(resp.toString().getBytes(StandardCharsets.UTF_8));
        out.flush();
    } catch (IOException e) {
        LoggerFactory.getLogger(Counter.class).error("IOException thrown: ", e);
    }
}
项目:xmanager    文件:CaptchaUtils.java   
/**
 * 生成验证码
 */
static void generate(HttpServletResponse response, String vCode) {
    BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    response.setHeader("Pragma","no-cache");
    response.setHeader("Cache-Control","no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ServletOutputStream sos = null;
    try {
        drawGraphic(image, vCode);
        sos = response.getOutputStream();
        ImageIO.write(image, "JPEG", sos);
        sos.flush();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(sos);
    }
}
项目:openNaEF    文件:ForwarderServlet.java   
private void doService(HttpMethod method, HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    outputRequestLog(req);

    InputStream iStream = null;
    ServletOutputStream oStream = null;
    try {
        long threadID = Thread.currentThread().getId();
        log.debug("[" + threadID + "] forwarded to " + distributer.getRedirectUrl(req));
        HttpClient client = new HttpClient();
        log.debug("[" + threadID + "]send request.");
        int resultCode = client.executeMethod(method);
        log.debug("[" + threadID + "]got response: result code is " + resultCode);
        res.setStatus(resultCode);
        for (Header header : method.getResponseHeaders()) {
            res.setHeader(header.getName(), header.getValue());
        }
        iStream = method.getResponseBodyAsStream();
        oStream = res.getOutputStream();

        writeOutputStream(iStream, oStream);

        log.debug("[" + threadID + "] response sent to client.");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } finally {
        if (iStream != null) {
            iStream.close();
        }
        if (oStream != null) {
            oStream.close();
        }
    }
}
项目:spring_mybatis_shiro    文件:CommonController.java   
/**
 * 验证码
 */
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtils.isEmpty(captchaId)) {
        captchaId = request.getSession().getId();
    }
    response.addHeader("vincent.li", "vincent.li");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        BufferedImage bufferedImage = (BufferedImage) imageCaptchaService.getChallengeForID(captchaId);
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}
项目:server    文件:PeerServlet.java   
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {

    service.setRemoteHost(request.getRemoteHost());

    InputStream inputStream = request.getInputStream();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[65536];
    int numberOfBytes;
    while ((numberOfBytes = inputStream.read(buffer)) > 0) {

        byteArrayOutputStream.write(buffer, 0, numberOfBytes);

    }
    inputStream.close();

    String responseBody = service.doRequest(byteArrayOutputStream.toString("UTF-8"));
    byte[] responseBytes = responseBody.getBytes("UTF-8");

    response.setContentType("text/plain; charset=UTF-8");
    response.addHeader("Access-Control-Allow-Origin", "*");
    ServletOutputStream servletOutputStream = response.getOutputStream();
    servletOutputStream.write(responseBytes);
    servletOutputStream.close();

}
项目:Equella    文件:DirListViewer.java   
private void viewXml(RenderContext info, HttpServletResponse response) throws IOException
{
    response.setContentType("text/xml");
    ServletOutputStream outputStream = response.getOutputStream();
    outputStream.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    outputStream.println(itemXsltService.getXmlForXslt(info, AbstractParentViewItemSection.getItemInfo(info))
        .toString());
    outputStream.flush();
    outputStream.close();
}
项目:bootstrap    文件:AuthorizingFilterTest.java   
/**
 * Plenty attached authority
 */
@Test
public void doFilterAttachedAuthority3() throws Exception {
    attachRole(DEFAULT_ROLE, "role2");
    addSystemAuthorization(HttpMethod.GET, "role2", "^rest/match$");
    em.flush();
    em.clear();
    cacheResource.invalidate("authorizations");
    final FilterChain chain = Mockito.mock(FilterChain.class);
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final ServletContext servletContext = Mockito.mock(ServletContext.class);
    Mockito.when(servletContext.getContextPath()).thenReturn("/context");
    Mockito.when(request.getRequestURI()).thenReturn("/context/rest/match");
    Mockito.when(request.getQueryString()).thenReturn("query");
    Mockito.when(request.getMethod()).thenReturn("GET");
    final ServletOutputStream outputStream = Mockito.mock(ServletOutputStream.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Mockito.when(response.getOutputStream()).thenReturn(outputStream);
    authorizingFilter.setServletContext(servletContext);
    authorizingFilter.doFilter(request, response, chain);
    Mockito.when(request.getMethod()).thenReturn("HEAD");
    authorizingFilter.doFilter(request, response, chain);
    Mockito.verify(chain, Mockito.atLeastOnce()).doFilter(request, response);
    Mockito.validateMockitoUsage();
}
项目:hermes-java    文件:HermesServlet.java   
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Center center = ApplicationContextHelper.getBean(Constant.CENTERS_BEAN_NAME, Centers.class)
            .getCenterBySessionId(req.getParameter("sessionId"));
    ServletOutputStream out = resp.getOutputStream();
    try {
        // hex to bytes
        byte[] bytes = CoderUtils.hexStringToByteArray(req.getParameter("data"));
        // 解密
        String text = new String(RsaUtils.decryptByPublicKey(bytes, center.getPublicKey()));
        // 通过name选取方法并调用
        Object result = invokeMethodByName(req.getParameter("name"), text);
        byte[] respData = JSON.toJSONString(result).getBytes("utf-8");
        if (respData.length > center.getLength() - Constant.RSA_RESERVED_LENGTH) {
            throw new Exception("response data is too big");
        }
        // 返回加密
        respData = RsaUtils.encryptByPublicKey(respData, center.getPublicKey());
        out.write(respData);
    } catch (Exception e) {
        e.printStackTrace();
        out.write(500);
    } finally {
        out.close();
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:CompressionServletResponseWrapper.java   
/**
 * Return the servlet output stream associated with this Response.
 *
 * @exception IllegalStateException if <code>getWriter</code> has
 *  already been called for this response
 * @exception IOException if an input/output error occurs
 */
@Override
public ServletOutputStream getOutputStream() throws IOException {

    if (writer != null)
        throw new IllegalStateException("getWriter() has already been called for this response");

    if (stream == null)
        stream = createOutputStream();
    if (debug > 1) {
        System.out.println("stream is set to "+stream+" in getOutputStream");
    }

    return (stream);

}
项目:lams    文件:DefaultServlet.java   
/**
 * 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 istream The input stream to read from
 * @param ostream The output stream to write to
 * @return Exception which occurred during processing
 */
protected IOException copyRange(InputStream istream,
                              ServletOutputStream ostream) {

    // Copy the input stream to the output stream
    IOException exception = null;
    byte buffer[] = new byte[input];
    int len = buffer.length;
    while (true) {
        try {
            len = istream.read(buffer);
            if (len == -1)
                break;
            ostream.write(buffer, 0, len);
        } catch (IOException e) {
            exception = e;
            len = -1;
            break;
        }
    }
    return exception;

}
项目:simple-hostel-management    文件:AdministrationController.java   
@RequestMapping(value = Mappings.ADMINISTRATION_EXPORT_SERVICES_CSV, method = RequestMethod.GET)
public void exportServicesCsv(
        @RequestParam("begin") String begin,
        @RequestParam("end") String end,
        HttpServletResponse response) throws Exception {

    Date beginDate = Utils.stringToDate(begin);
    Date endDate = Utils.stringToDate(end);

    response.setContentType("text/csv");
    response.setHeader("Content-disposition", "attachment; filename=\"export.csv\"");

    File tempFile = exportService.exportServicesCsv(beginDate, endDate);

    try (ServletOutputStream out = response.getOutputStream();
         InputStream in = Files.newInputStream(tempFile.toPath())) {
        IOUtils.copy(in, out);
    }

    Files.delete(tempFile.toPath());

}
项目:fwm    文件:Webservice1_0BSController.java   
@RequestMapping(value = "/webservice1_0bs/multimediaImage/null", method = RequestMethod.GET)
@ResponseBody
public void getNullImage(HttpServletResponse response) {
    try {
        byte[] b = new byte[0];
        InputStream i = App.retGlobalResource("/src/main/ui/no_image_icon.png").openStream();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/" + "png");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int read = 0;
        while ((read = i.read(bytes)) != -1) {
            responseOutputStream.write(bytes, 0, read);
        }

        responseOutputStream.flush();
        responseOutputStream.close();
    } catch (IOException e1) {
        log.error(e1);
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (Exception e) {
            log.error(e);
        }
    }
}
项目:renren-msg    文件:SysLoginController.java   
@RequestMapping("captcha.jpg")
public void captcha(HttpServletResponse response) throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setContentType("image/jpeg");

    // 生成文字验证码
    String text = producer.createText();
    // 生成图片验证码
    BufferedImage image = producer.createImage(text);
    // 保存到shiro session
    ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(image, "jpg", out);
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:WritingServlet.java   
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    AsyncContext context = request.startAsync();
    ServletOutputStream output = response.getOutputStream();
    output.setWriteListener(new WritingListener(output, context));
}
项目:apache-tomcat-7.0.73-with-comment    文件:ResponseIncludeWrapper.java   
/**
 * Return a OutputStream, throws and exception if a printwriter already
 * been returned.
 * 
 * @return a OutputStream object
 * @exception java.io.IOException
 *                if the printwriter already been called
 */
@Override
public ServletOutputStream getOutputStream() throws java.io.IOException {
    if (printWriter == null) {
        if (servletOutputStream == null) {
            servletOutputStream = captureServletOutputStream;
        }
        return servletOutputStream;
    }
    throw new IllegalStateException();
}
项目:lazycat    文件:Response.java   
/**
 * Create and return a ServletOutputStream to write the content associated
 * with this Response.
 *
 * @exception IOException
 *                if an input/output error occurs
 */
@Deprecated
public ServletOutputStream createOutputStream() throws IOException {
    // Probably useless
    if (outputStream == null) {
        outputStream = new CoyoteOutputStream(outputBuffer);
    }
    return outputStream;
}
项目:apache-tomcat-7.0.73-with-comment    文件:Response.java   
/**
 * Create and return a ServletOutputStream to write the content
 * associated with this Response.
 *
 * @exception IOException if an input/output error occurs
 */
@Deprecated
public ServletOutputStream createOutputStream()
    throws IOException {
    // Probably useless
    if (outputStream == null) {
        outputStream = new CoyoteOutputStream(outputBuffer);
    }
    return outputStream;
}
项目:parabuild-ci    文件:TestServletTestCase_TestResult.java   
/**
 * Verify that the test result can be returned correctly even when the
 * logic in the method to test takes a long time and thus it verifies that
 * the test result is only returned after it has been written in the
 * application scope on the server side.
 */
public void testLongProcess() throws Exception
{
    ServletOutputStream os = response.getOutputStream();
    os.print("<html><head><Long Process></head><body>");
    os.flush();

    // do some processing that takes a while ...
    Thread.sleep(3000);
    os.println("Some data</body></html>");
}
项目:csap-core    文件:FileRequests.java   
private void writeFileToOutputStream ( HttpServletResponse response, File targetFile )
        throws IOException {
    try (DataInputStream in = new DataInputStream( new FileInputStream(
        targetFile.getAbsolutePath() ) );
            ServletOutputStream servletOutputStream = response.getOutputStream();) {

        byte[] bbuf = new byte[ BYTE_DOWNLOAD_CHUNK ];

        int numBytesRead;
        long startingMax = targetFile.length();
        long totalBytesRead = 0L; // hook for files that are being updated

        while ((in != null) && ((numBytesRead = in.read( bbuf )) != -1)
                && (startingMax > totalBytesRead)) {

            totalBytesRead += numBytesRead;
            servletOutputStream.write( bbuf, 0, numBytesRead );
            servletOutputStream.flush();
        }

    } catch (Exception e) {
        String reason = CSAP.getCsapFilteredStackTrace( e );
        logger.error( "Failed accessing file: {}", reason );
        response.getWriter().println(
            "Failed accessing file: " + targetFile + "\n Validate OS file system permissions" );
    }
}
项目:tomcat7    文件:DefaultServlet.java   
/**
 * 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 cacheEntry The cache entry for the source resource
 * @param is The input stream to read the source resource from
 * @param ostream The output stream to write to
 *
 * @exception IOException if an input/output error occurs
 */
protected void copy(CacheEntry cacheEntry, InputStream is,
                  ServletOutputStream ostream)
    throws IOException {

    IOException exception = null;
    InputStream resourceInputStream = null;

    // Optimization: If the binary content has already been loaded, send
    // it directly
    if (cacheEntry.resource != null) {
        byte buffer[] = cacheEntry.resource.getContent();
        if (buffer != null) {
            ostream.write(buffer, 0, buffer.length);
            return;
        }
        resourceInputStream = cacheEntry.resource.streamContent();
    } else {
        resourceInputStream = is;
    }

    InputStream istream = new BufferedInputStream
        (resourceInputStream, input);

    // Copy the input stream to the output stream
    exception = copyRange(istream, ostream);

    // Clean up the input stream
    istream.close();

    // Rethrow any exception that has occurred
    if (exception != null)
        throw exception;

}
项目:lazycat    文件:ExpiresFilter.java   
public XServletOutputStream(ServletOutputStream servletOutputStream, HttpServletRequest request,
        XHttpServletResponse response) {
    super();
    this.servletOutputStream = servletOutputStream;
    this.response = response;
    this.request = request;
}
项目:Yidu    文件:GZIPResponseWrapper.java   
/**
 * 获取ServletOutputStream对象
 * 
 * @return ServletOutputStream对象
 * @throws IOException
 *             IO异常
 */
public ServletOutputStream getOutputStream() throws IOException {
    if (writer != null) {
        throw new IllegalStateException("getWriter() has already been called!");
    }

    if (stream == null) {
        stream = createOutputStream();
    }
    return (stream);
}
项目:tomcat7    文件:ExpiresFilter.java   
@Override
public ServletOutputStream getOutputStream() throws IOException {
    if (servletOutputStream == null) {
        servletOutputStream = new XServletOutputStream(
                super.getOutputStream(), request, this);
    }
    return servletOutputStream;
}
项目:tomcat7    文件:ExpiresFilter.java   
public XServletOutputStream(ServletOutputStream servletOutputStream,
        HttpServletRequest request, XHttpServletResponse response) {
    super();
    this.servletOutputStream = servletOutputStream;
    this.response = response;
    this.request = request;
}
项目:parabuild-ci    文件:TestServletTestCase_TestResult.java   
/**
 * Verify that when big amount of data is returned by the servlet output
 * stream, it does not io-block.
 */
public void testLotsOfData() throws Exception
{
    ServletOutputStream os = response.getOutputStream();
    os.println("<html><head>Lots of Data</head><body>");
    os.flush();
    for (int i = 0; i < 5000; i++) {
        os.println("<p>Lots and lots of data here");
    }
    os.println("</body></html>");
}
项目:exam    文件:RemoteServerHelper.java   
public static void writeResponseFromFile(HttpServletResponse response, String filePath) {
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
    try (FileInputStream fis = new FileInputStream(new File(filePath)); ServletOutputStream sos = response.getOutputStream()) {
        IOUtils.copy(fis, sos);
        sos.flush();
    } catch (IOException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
项目:tomcat7    文件:CompressionServletResponseWrapper.java   
/**
 * Create and return a ServletOutputStream to write the content
 * associated with this Response.
 *
 * @exception IOException if an input/output error occurs
 */
public ServletOutputStream createOutputStream() throws IOException {
    if (debug > 1) {
        System.out.println("createOutputStream gets called");
    }

    CompressionResponseStream stream = new CompressionResponseStream(origResponse);
    stream.setDebugLevel(debug);
    stream.setBuffer(threshold);

    return stream;

}
项目:DWSurvey    文件:JcaptchaAction.java   
public String execute() throws Exception {
        HttpServletRequest request = Struts2Utils.getRequest();
        HttpServletResponse response = Struts2Utils.getResponse();
        ByteArrayOutputStream out = null;
        byte[] captchaChallengeAsJpeg = null;  
        // the output stream to render the captcha image as jpeg into  
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();  
        try {  
            // get the session id that will identify the generated captcha.  
            // the same id must be used to validate the response, the session id  
            // is a good candidate!  
            String captchaId = request.getSession().getId();  
            // call the ImageCaptchaService getChallenge method  
            BufferedImage challenge = imageCaptchaService.getImageChallengeForID(captchaId, request.getLocale());
            // a jpeg encoder
/*** jdk1.7之后默认不支持了 **/
//            JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
//            jpegEncoder.encode(challenge);

//            换成新版图片api
            ImageIO.write(challenge, "jpg", jpegOutputStream);

        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();    
        // flush it in the response    
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
        return null;
    }