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:ca.uhn.fhir.rest.server.servlet.ServletRestfulResponse.java

@Override
public Object sendAttachmentResponse(IBaseBinary bin, int stausCode, String contentType) throws IOException {
    addHeaders();//from   ww  w .  j ava 2s. c o m
    HttpServletResponse theHttpResponse = getRequestDetails().getServletResponse();
    theHttpResponse.setStatus(stausCode);
    theHttpResponse.setContentType(contentType);
    if (bin.getContent() == null || bin.getContent().length == 0) {
        return null;
    } else {
        theHttpResponse.setContentLength(bin.getContent().length);
        ServletOutputStream oos = theHttpResponse.getOutputStream();
        oos.write(bin.getContent());
        oos.close();
        return null;
    }
}

From source file:org.teiid.olingo.web.gzip.TestGzipMessageResponse.java

@Test
public void testWriteToOutputStream() throws Exception {
    ServletOutputStream sos = response.getOutputStream();
    sos.write(TEST_STRING.getBytes());//from w w w . ja v  a 2  s. c  om
    sos.close();
    Assert.assertArrayEquals("Expected output in GZIP.", TEST_STRING_IN_GZIP,
            ArrayUtils.toPrimitive(streamBytes.toArray(new Byte[streamBytes.size()])));
}

From source file:com.fanya.p2p.front.user.jcaptcha.JCaptchaFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    response.setDateHeader("Expires", 0L);
    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 id = request.getRequestedSessionId();
    BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id);

    ServletOutputStream out = response.getOutputStream();

    ImageIO.write(bi, "jpg", out);
    try {//from   ww w .  ja va 2 s  . c o  m
        out.flush();
    } finally {
        out.close();
    }
}

From source file:no.feide.moria.servlet.PictureServlet.java

/**
 * Implements the HttpServlet.doGet method.
 * @param request//  ww  w.  j  a va 2s .co  m
 *            The HTTP request.
 * @param response
 *            The HTTP response.
 * @throws IOException
 * @throws ServletException
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    try {

        int idx = 0;
        String index = request.getParameter("index");
        if (index != null) {
            idx = Integer.parseInt(index);
        }

        // login.feide.no/Picture can be entered as an URL without any further arguments.
        // That will lead to a null pointer exception, caught by the catch-clause below, but 
        // we really should avoid creating such errors. For one, they end up in the log file looking
        // horribly serious, when there is little reason to worry.

        response.setContentType("image/jpeg");
        String[] picture = (String[]) request.getSession().getAttribute(PICTURE_ATTRIBUTE);

        if (picture == null) {
            log.logWarn("PictureServlet called without picture context. Nothing to display");
        } else {
            byte[] decoded = Base64.decodeBase64(picture[idx].getBytes("ISO-8859-1"));

            ServletOutputStream writer = response.getOutputStream();
            writer.write(decoded);
            writer.close();
        }

    } catch (Throwable t) {
        log.logWarn("Picture display failed", t);
    }

}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static void sendBytes(byte[] bytes, String filename, String contentType) {
    if (bytes != null) {
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();

        response.setContentType(contentType);
        response.addHeader("Content-disposition", "attachment; filename=" + filename);
        response.addHeader("Content-Length", String.valueOf(bytes.length));
        ServletOutputStream os = null;
        try {//from  w w  w  . j  a  v a 2s.  c  o  m
            os = response.getOutputStream();
            os.write(bytes);
            os.flush();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (IOException e) {
            LOGGER.error("Sending content failed {0}", filename, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close stream after sending", e);
                }
            }
        }
    }
}

From source file:ru.ksu.niimm.cll.mocassin.frontend.server.PdfDownloadServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    String requestURI = req.getRequestURI();
    logger.info("The requested URI: {}", requestURI);
    String parameter = requestURI.substring(requestURI.lastIndexOf(ARXIVID_ENTRY) + ARXIVID_ENTRY_LENGTH);
    int signIndex = parameter.indexOf(StringUtil.ARXIVID_SEGMENTID_DELIMITER);
    String arxivId = signIndex != -1 ? parameter.substring(0, signIndex) : parameter;
    String segmentId = signIndex != -1 ? parameter.substring(signIndex + 1) : null;

    if (arxivId == null) {
        logger.error("The request with an empty arxiv id parameter");
        return;/*from w  ww  .j  av a2 s  .co m*/
    }
    String filePath = segmentId == null
            ? format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf"))
            : "/opt/mocassin/pdf/" + StringUtil.segmentid2filename(arxivId, Integer.parseInt(segmentId), "pdf");
    if (!new File(filePath).exists()) {
        filePath = format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf"));
    }
    try {
        FileInputStream fileInputStream = new FileInputStream(filePath);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        IOUtils.copy(fileInputStream, byteArrayOutputStream);
        resp.setContentType("application/pdf");
        resp.setHeader("Content-disposition",
                String.format("attachment; filename=%s", StringUtil.arxivid2filename(arxivId, "pdf")));
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(byteArrayOutputStream.toByteArray());
        outputStream.close();
    } catch (FileNotFoundException e) {
        logger.error("Error while downloading: PDF file= '{}' not found", filePath);
    } catch (IOException e) {
        logger.error("Error while downloading the PDF file", e);
    }
}

From source file:org.qifu.util.JReportUtils.java

public static void fillReportToResponse(String reportId, Map<String, Object> paramMap,
        HttpServletResponse response) throws ServiceException, Exception {
    if (StringUtils.isBlank(reportId)) {
        throw new java.lang.IllegalArgumentException("error, reportId is blank");
    }//w  w  w .  ja v a  2  s  .  c  o  m
    TbSysJreport sysJreport = new TbSysJreport();
    sysJreport.setReportId(reportId);
    DefaultResult<TbSysJreport> result = sysJreportService.findEntityByUK(sysJreport);
    if (result.getValue() == null) {
        throw new ServiceException(result.getSystemMessage().getValue());
    }
    sysJreport = result.getValue();
    String jasperFileFullPath = Constants.getDeployJasperReportDir() + "/" + sysJreport.getReportId() + "/"
            + sysJreport.getReportId() + ".jasper";
    File jasperFile = new File(jasperFileFullPath);
    if (!jasperFile.exists()) {
        jasperFile = null;
        throw new Exception("error, Files are missing : " + jasperFileFullPath);
    }
    InputStream reportSource = new FileInputStream(jasperFile);
    Connection conn = null;
    try {
        conn = DataUtils.getConnection();
        ServletOutputStream ouputStream = response.getOutputStream();
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportSource, paramMap, conn);
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline; filename=" + sysJreport.getReportId() + ".pdf");
        JRPdfExporter jrPdfExporter = new JRPdfExporter();
        jrPdfExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        jrPdfExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(ouputStream));
        SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
        jrPdfExporter.setConfiguration(configuration);
        configuration.setOwnerPassword(Constants.getEncryptorKey1());
        jrPdfExporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        DataUtils.doReleaseConnection(conn);
        if (null != reportSource) {
            try {
                reportSource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        reportSource = null;
        jasperFile = null;
    }
}

From source file:de.fau.amos4.web.PrintDataController.java

@RequestMapping("/employee/download/text")
public ModelAndView EmployeeDownloadText(HttpServletResponse response,
        @RequestParam(value = "id", required = true) long employeeId) throws IOException {
    // Use the service to get the Employee in the LODAS format
    final String employeeAsLodas = employeeService.getLodasRepresentation(employeeId);

    if (employeeAsLodas == null) {
        return new ModelAndView("redirect:/client/dashboard");
    }//from w w  w .  j  ava2  s .c o m

    // We want to have a txt file download
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition", "attachment;filename=employee_as_lodas.txt");
    response.setCharacterEncoding("UTF-8");

    // Write the data out
    ServletOutputStream out = response.getOutputStream();
    out.write(employeeAsLodas.getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:it.jugpadova.controllers.JCaptchaController.java

@RequestMapping
public void image(HttpServletRequest req, HttpServletResponse res) throws IOException {
    byte[] captchaChallengeAsJpeg = null;
    // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

    // get the session id that will identify the generated captcha.
    //the same id must be used to validate the res, the session id is a good candidate!
    String captchaId = req.getSession().getId();

    // call the ImageCaptchaService getChallenge method
    BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, req.getLocale());

    // a jpeg encoder
    JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
    jpegEncoder.encode(challenge);//from ww  w  .  j a v a 2 s  . co m

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // flush it in the res
    res.setHeader("Cache-Control", "no-store");
    res.setHeader("Pragma", "no-cache");
    res.setDateHeader("Expires", 0);
    res.setContentType("image/jpeg");
    ServletOutputStream resOutputStream = res.getOutputStream();
    resOutputStream.write(captchaChallengeAsJpeg);
    resOutputStream.flush();
    resOutputStream.close();
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.PosterImageServlet.java

/**
 * Returns poster image/*w  ww. j  ava2s. c  om*/
 *
 * @param request the request
 * @param response the response
 * @throws ServletException the servlet exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sIdProduct = request.getParameter(PARAMETER_PRODUCT_ID);

    if (StringUtils.isNotEmpty(sIdProduct)) {
        Integer idProduct = Integer.parseInt(sIdProduct);
        boolean isThumbnail = (request.getParameter(PARAMETER_TB) != null)
                && request.getParameter(PARAMETER_TB).equals(String.valueOf(true));
        byte[] bImage;

        if (isThumbnail) {
            bImage = _productService.getTbImage(idProduct);
        } else {
            bImage = _productService.getImage(idProduct);
        }

        response.setContentLength(bImage.length);
        response.setContentType(CONTENT_TYPE_IMAGE_JPEG);

        ServletOutputStream os = response.getOutputStream();
        IOUtils.write(bImage, os);
        os.flush();
        os.close();
    } else {
        LOGGER.error(ERROR_MESSAGE);
    }
}