Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:org.myjerry.util.ResponseUtil.java

public static final ModelAndView sendFileToDownload(HttpServletResponse response, String fileToDownload,
        String fileName, String contentType, boolean isHttp11) throws IOException {

    response.reset();/*from   w ww  .j  a  va  2 s .co  m*/

    setNoCache(response, isHttp11);

    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    response.setContentType(contentType);

    ServletOutputStream out;
    out = response.getOutputStream();
    out.print(fileToDownload);
    out.flush();
    out.close();

    return null;
}

From source file:strutter.helper.WSActionHelper.java

public static void writeBody(byte[] val) throws Exception {
    ServletOutputStream writer = ActionHelper.getResponse().getOutputStream();

    writer.write(val);

    writer.close();
}

From source file:com.octo.captcha.module.web.image.ImageToJpegHelper.java

/**
 * retrieve a new ImageCaptcha using ImageCaptchaService and flush it to the response.<br/> Captcha are localized
 * using request locale.<br/>//from   w ww . ja v a  2  s  .co m
 * <p/>
 * This method returns a 404 to the client instead of the image if the request isn't correct (missing parameters,
 * etc...)..<br/> The log may be null.<br/>
 *
 * @param theRequest  the request
 * @param theResponse the response
 * @param log         a commons logger
 * @param service     an ImageCaptchaService instance
 *
 * @throws java.io.IOException if a problem occurs during the jpeg generation process
 */
public static void flushNewCaptchaToResponse(HttpServletRequest theRequest, HttpServletResponse theResponse,
        Log log, ImageCaptchaService service, String id, Locale locale) throws IOException {

    // call the ImageCaptchaService method to retrieve a captcha
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {
        BufferedImage challenge = service.getImageChallengeForID(id, locale);
        // the output stream to render the captcha image as jpeg into

        ImageIO.write(challenge, "jpg", jpegOutputStream);

    } catch (IllegalArgumentException e) {
        //    log a security warning and return a 404...
        if (log != null && log.isWarnEnabled()) {
            log.warn("There was a try from " + theRequest.getRemoteAddr()
                    + " to render an captcha with invalid ID :'" + id + "' or with a too long one");
            theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    theResponse.setHeader("Cache-Control", "no-store");
    theResponse.setHeader("Pragma", "no-cache");
    theResponse.setDateHeader("Expires", 0);

    theResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = theResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:com.octo.captcha.module.web.sound.SoundToWavHelper.java

/**
 * retrieve a new SoundCaptcha using SoundCaptchaService and flush it to the response. <br/> Captcha are localized
 * using request locale. <br/>This method returns a 404 to the client instead of the image if the request isn't
 * correct (missing parameters, etc...).. <br/>The log may be null. <br/>
 *
 * @param theRequest  the request//from w  w  w .ja v  a  2 s  . c  om
 * @param theResponse the response
 * @param log         a commons logger
 * @param service     an SoundCaptchaService instance
 *
 * @throws java.io.IOException if a problem occurs during the jpeg generation process
 */
public static void flushNewCaptchaToResponse(HttpServletRequest theRequest, HttpServletResponse theResponse,
        Log log, SoundCaptchaService service, String id, Locale locale) throws IOException {

    // call the ImageCaptchaService method to retrieve a captcha
    byte[] captchaChallengeAsWav = null;
    ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream();
    try {
        AudioInputStream stream = service.getSoundChallengeForID(id, locale);

        // call the ImageCaptchaService method to retrieve a captcha

        AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream);
        //AudioSystem.(pAudioInputStream, AudioFileFormat.Type.WAVE, pFile);

    } catch (IllegalArgumentException e) {
        //    log a security warning and return a 404...
        if (log != null && log.isWarnEnabled()) {
            log.warn("There was a try from " + theRequest.getRemoteAddr()
                    + " to render an captcha with invalid ID :'" + id + "' or with a too long one");
            theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    } catch (CaptchaServiceException e) {
        // log and return a 404 instead of an image...
        if (log != null && log.isWarnEnabled()) {
            log.warn(

                    "Error trying to generate a captcha and " + "render its challenge as JPEG", e);
        }
        theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    captchaChallengeAsWav = wavOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    theResponse.setHeader("Cache-Control", "no-store");
    theResponse.setHeader("Pragma", "no-cache");
    theResponse.setDateHeader("Expires", 0);

    theResponse.setContentType("audio/x-wav");
    ServletOutputStream responseOutputStream = theResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsWav);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java

private static void writeImageContent(HttpServletResponse response, byte[] imageData, String contentType)
        throws IOException {
    ServletOutputStream os = response.getOutputStream();
    response.setContentType(contentType);
    os.write(imageData);//from   w ww  .  ja  va  2s .c  o  m
    os.flush();
    os.close();
}

From source file:org.oscarehr.admin.traceability.GenerateTraceabilityUtil.java

public static void download(HttpServletResponse response, String fileName, String contentType)
        throws Exception {
    response.setContentType(contentType);
    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    FileInputStream in = new FileInputStream(fileName);
    ServletOutputStream out = response.getOutputStream();
    long buf_size = new File(fileName).length();
    byte[] outputByte = new byte[(int) buf_size];
    while (in.read(outputByte) != -1) {
        out.write(outputByte, 0, (int) buf_size);
    }//from   w w w  . j av a  2 s. c o m
    in.close();
    out.flush();
    out.close();
}

From source file:com.ikon.util.WebUtils.java

/**
 * Send file to client browser.// w  w  w . j a  v  a2 s .c om
 * 
 * @throws IOException If there is a communication error.
 */
public static void sendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline, InputStream is) throws IOException {
    log.debug("sendFile({}, {}, {}, {}, {}, {})",
            new Object[] { request, response, fileName, mimeType, inline, is });
    prepareSendFile(request, response, fileName, mimeType, inline);

    // Set length
    response.setContentLength(is.available());
    log.debug("File: {}, Length: {}", fileName, is.available());

    ServletOutputStream sos = response.getOutputStream();
    IOUtils.copy(is, sos);
    sos.flush();
    sos.close();
}

From source file:com.ikon.util.WebUtils.java

/**
 * Send file to client browser./*from   w  w  w. ja va 2s  .  c  o m*/
 * 
 * @throws IOException If there is a communication error.
 */
public static void sendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline, File input) throws IOException {
    log.debug("sendFile({}, {}, {}, {}, {}, {})",
            new Object[] { request, response, fileName, mimeType, inline, input });
    prepareSendFile(request, response, fileName, mimeType, inline);

    // Set length
    response.setContentLength((int) input.length());
    log.debug("File: {}, Length: {}", fileName, input.length());

    ServletOutputStream sos = response.getOutputStream();
    FileUtils.copy(input, sos);
    sos.flush();
    sos.close();
}

From source file:org.wso2.carbon.registry.reporting.ui.clients.ReportGeneratorServlet.java

public static void getContent(HttpServletRequest request, HttpServletResponse response, ServletConfig config)
        throws Exception {

    try {/*from   w  w  w. ja va 2 s .  c  o  m*/
        ReportGeneratorClient client = new ReportGeneratorClient(request, config);
        ReportConfigurationBean bean = client.getSavedReport(request.getParameter("reportName"));
        String reportTemplate = request.getParameter("reportTemplate");
        if (reportTemplate != null) {
            bean.setTemplate(reportTemplate);
        }
        String reportType = request.getParameter("reportType");
        if (reportType != null) {
            bean.setType(reportType);
        }
        String reportClass = request.getParameter("reportClass");
        if (reportClass != null) {
            bean.setReportClass(reportClass);
        }
        String attributes = request.getParameter("attributes");
        if (attributes != null && attributes.length() > 0) {
            Map<String, String> attributeMap = CommonUtil.attributeArrayToMap(bean.getAttributes());
            attributes = attributes.substring(0, attributes.length() - 1);
            String[] attributeStrings = attributes.split("\\^");
            for (String temp : attributeStrings) {
                String[] pair = temp.split("\\|");
                attributeMap.put(pair[0].substring("attribute".length()), pair[1]);
            }
            bean.setAttributes(CommonUtil.mapToAttributeArray(attributeMap));
        }

        response.setDateHeader("Last-Modified", new Date().getTime());
        String extension;
        String mediaType;
        if (bean.getType().toLowerCase().equals("pdf")) {
            mediaType = "application/pdf";
            extension = ".pdf";
        } else if (bean.getType().toLowerCase().equals("excel")) {
            mediaType = "application/vnd.ms-excel";
            extension = ".xls";
        } else if (bean.getType().toLowerCase().equals("html")) {
            mediaType = "application/html";
            extension = ".html";
        } else {
            mediaType = "application/download";
            extension = "";
        }

        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + bean.getName() + extension + "\"");
        response.setContentType(mediaType);

        ServletOutputStream servletOutputStream = response.getOutputStream();
        try {
            client.getReportBytes(bean).writeTo(servletOutputStream);
            response.flushBuffer();
            servletOutputStream.flush();
        } finally {
            if (servletOutputStream != null) {
                servletOutputStream.close();
            }
        }

    } catch (RegistryException e) {
        String msg = "Failed to get resource content. " + e.getMessage();
        log.error(msg, e);
        response.setStatus(500);
    }
}

From source file:pt.ua.dicoogle.server.web.IndexerServlet.java

/**
 * Writes the specified XML document in String form to a HttpServletResponse
 * object./*from  w  ww  . j a v a2s. co  m*/
 * 
 * @param xml
 *            a XML document in String form.
 * @param response
 *            a HttpServletResponse.
 * @throws IOException
 *             if a error has occurred while writing the response.
 */
private static void writeXMLToResponse(String xml, HttpServletResponse response, boolean allowCache)
        throws IOException {
    // get the returned xml as a UTF-8 byte array
    byte[] data = xml.getBytes("UTF-8");
    if (data == null) {
        response.sendError(500, "Could generate the resulting XML document!");
        return;
    }

    if (!allowCache) {
        response.addHeader("Cache-Control", "no-cache, must-revalidate");
        response.addHeader("Pragma", "no-cache");
    }

    response.setContentType("application/xml"); // set the appropriate type
    // for the XML file
    response.setContentLength(data.length); // set the document size
    // response.setCharacterEncoding("UTF-8"); // set the apropriate
    // encoding type

    // write the XML data to the response output
    ServletOutputStream out = response.getOutputStream();
    out.write(data);
    out.close();
}