Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:org.efs.openreports.actions.ReportViewerAction.java

public String execute() {
    JasperPrint jasperPrint = (JasperPrint) ActionContext.getContext().getSession().get(ORStatics.JASPERPRINT);

    report = (Report) ActionContext.getContext().getSession().get(ORStatics.REPORT);

    if (jasperPrint != null && jasperPrint.getPages() != null) {
        pageCount = jasperPrint.getPages().size();
    }//  w ww .  j av a  2  s. co  m

    if (!"image".equals(submitType))
        return SUCCESS;

    byte[] imageData = null;

    if (jasperPrint != null) {
        try {
            BufferedImage image = (BufferedImage) JasperPrintManager.printPageToImage(jasperPrint,
                    pageIndex - 1, zoom);
            imageData = new SunPNGEncoderAdapter().encode(image);
        } catch (Exception e) {
            addActionError(e.getMessage());
            log.error(e.toString());
        }
    }

    if (imageData != null) {

        HttpServletResponse response = ServletActionContext.getResponse();

        try {
            response.setContentLength(imageData.length);
            ServletOutputStream ouputStream = response.getOutputStream();
            ouputStream.write(imageData, 0, imageData.length);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException ioe) {
            log.warn(ioe.toString());
        }
    }

    return NONE;
}

From source file:com.galenframework.storage.controllers.api.PageApiController.java

private void initElementImages() {
    get("/api/projects/:projectName/pages/:pageName/objects/:elementName/images", (req, res) -> {
        String projectName = req.params("projectName");
        String pageName = req.params("projectName");
        String elementName = req.params("elementName");

        Long projectId = obtainProjectId(projectName);
        Optional<Page> page = pageRepository.findPage(projectId, pageName);
        if (page.isPresent()) {
            Optional<PageObject> pageObject = objectRepository.findObject(page.get().getPageId(), elementName);
            if (pageObject.isPresent()) {
                return objectRepository.findAllObjectImages(pageObject.get().getObjectId());
            }//  w w w.j  av  a2  s  .  co  m
        }
        return emptyList();
    }, toJson());

    get("/api/projects/:projectName/pages/:pageName/objects/:elementName/images/:imageId", (req, res) -> {
        Long imageId = Long.parseLong(req.params("imageId"));
        Optional<ObjectImage> objectImage = objectRepository.findObjectImageById(imageId);
        if (objectImage.isPresent()) {
            byte[] imageBytes = fileStorage.readFile(objectImage.get().getImagePath());
            BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(imageBytes));
            ServletOutputStream os = res.raw().getOutputStream();
            IOUtils.copy(inputStream, os);
            os.flush();
            os.close();
            return os;
        } else {
            throw new RuntimeException("Can't find image");
        }
    });
}

From source file:com.predic8.membrane.servlet.embedded.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());
    }/*w w  w. j  ava  2  s.c o  m*/

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

    response.flushBuffer();

    exchange.setTimeResSent(System.currentTimeMillis());
    exchange.collectStatistics();
}

From source file:com.haulmont.cuba.web.controllers.FileDownloadController.java

protected void downloadFromMiddlewareAndWriteResponse(FileDescriptor fd, HttpServletResponse response)
        throws IOException {
    ServletOutputStream os = response.getOutputStream();
    try (InputStream is = fileLoader.openStream(fd)) {
        IOUtils.copy(is, os);//from www  .  j  a  va  2s .  c o  m
        os.flush();
    } catch (FileStorageException e) {
        log.error("Unable to load file from middleware", e);
        error(response);
    }
}

From source file:org.betaconceptframework.astroboa.console.jsf.BinaryChannelLoader.java

public void downloadBinaryChannel() {

    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {

        String selectedBinaryChannelId = JSFUtilities.getRequestParameter("binaryChannelId");

        BinaryChannel binaryChannel;//  w w  w. j  av a 2s. c  om
        //Retrieve the binary data of the Primary Binary Channel selected Content Object. Remember that for efficiency the binary data of binary channels are not retreived when a content object is retreived
        try {
            binaryChannel = getContentService().getBinaryChannelById(selectedBinaryChannelId);
        } catch (CmsException e) {
            throw new RuntimeException(e);
        }

        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

        response.setCharacterEncoding("UTF-8");
        response.setContentType(binaryChannel.getMimeType());
        response.setHeader("Content-Disposition", "attachment;filename=" + binaryChannel.getSourceFilename());

        InputStream contentAsStream = binaryChannel.getContentAsStream();

        response.setContentLength((int) binaryChannel.getSize());

        try {

            if (contentAsStream != null) {
                ServletOutputStream servletOutputStream = response.getOutputStream();

                IOUtils.copy(contentAsStream, servletOutputStream);

                servletOutputStream.flush();

                facesContext.responseComplete();

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            binaryChannel = null;

            //Close Stream
            if (contentAsStream != null)
                try {
                    contentAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
        }

    }

}

From source file:org.efs.openreports.actions.JXLSReportAction.java

public String execute() {
    ReportUser user = (ReportUser) ActionContext.getContext().getSession().get(ORStatics.REPORT_USER);

    report = (Report) ActionContext.getContext().getSession().get(ORStatics.REPORT);

    Map parameters = getReportParameterMap(user);

    ReportLog reportLog = new ReportLog(user, report, new Date());

    Connection conn = null;/*  ww w. ja v a 2s .com*/

    try {
        log.debug("Starting JXLS Report: " + report.getName());

        reportLogProvider.insertReportLog(reportLog);

        ReportEngineInput input = new ReportEngineInput(report, parameters);

        JXLSReportEngine reportEngine = new JXLSReportEngine(dataSourceProvider, directoryProvider,
                propertiesProvider);

        ReportEngineOutput output = reportEngine.generateReport(input);

        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition",
                "inline; filename=" + StringUtils.deleteWhitespace(report.getName()) + ".xls");

        ServletOutputStream out = response.getOutputStream();

        out.write(output.getContent(), 0, output.getContent().length);

        out.flush();
        out.close();

        reportLog.setEndTime(new Date());
        reportLog.setStatus(ReportLog.STATUS_SUCCESS);
        reportLogProvider.updateReportLog(reportLog);

        log.debug("Finished JRXLS Report: " + report.getName());
    } catch (Exception e) {
        addActionError(e.getMessage());

        log.error(e.getMessage());

        reportLog.setMessage(e.getMessage());
        reportLog.setStatus(ReportLog.STATUS_FAILURE);

        reportLog.setEndTime(new Date());

        try {
            reportLogProvider.updateReportLog(reportLog);
        } catch (Exception ex) {
            log.error("Unable to create ReportLog: " + ex.getMessage());
        }

        return ERROR;
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception c) {
            log.error("Error closing");
        }
    }

    return NONE;
}

From source file:org.b5chat.crossfire.web.FaviconServlet.java

/**
 * Writes out a <code>byte</code> to the ServletOuputStream.
 *
 * @param bytes the bytes to write to the <code>ServletOutputStream</code>.
 *///from   www . j a v a 2s  .  com
private void writeBytesToStream(byte[] bytes, HttpServletResponse response) {
    response.setContentType(CONTENT_TYPE);

    // Send image
    try {
        ServletOutputStream sos = response.getOutputStream();
        sos.write(bytes);
        sos.flush();
        sos.close();
    } catch (IOException e) {
        // Do nothing
    }
}

From source file:org.nuxeo.ecm.platform.groups.audit.seam.ExportGroupManagementActions.java

public String downloadExcelAllGroupsExport() throws ClientException {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext econtext = context.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) econtext.getResponse();
    File excelReport = excelExportAllGroupsDefinition();

    response.setContentType(new MimetypesFileTypeMap().getContentType(excelReport));
    response.setHeader("Content-disposition", "attachment; filename=\"" + excelReport.getName() + "\"");
    response.setHeader("Content-Length", String.valueOf(excelReport.length()));
    try {//from   w ww.  j a v  a2 s  . c om
        ServletOutputStream os = response.getOutputStream();
        InputStream in = new FileInputStream(excelReport);
        FileUtils.copy(in, os);
        os.flush();
        in.close();
        os.close();
        context.responseComplete();
    } catch (Exception e) {
        log.error("Failure : " + e.getMessage());
    }
    return null;
}

From source file:org.nuxeo.ecm.platform.groups.audit.seam.ExportGroupManagementActions.java

public String downloadExcelListedGroupsExport() throws ClientException {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext econtext = context.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) econtext.getResponse();
    File excelReport = excelExportListedGroupsDefinition();

    response.setContentType(new MimetypesFileTypeMap().getContentType(excelReport));
    response.setHeader("Content-disposition", "attachment; filename=\"" + excelReport.getName() + "\"");
    response.setHeader("Content-Length", String.valueOf(excelReport.length()));
    try {/*from   w  w  w.  ja  v  a 2  s.  c  o m*/
        ServletOutputStream os = response.getOutputStream();
        InputStream in = new FileInputStream(excelReport);
        FileUtils.copy(in, os);
        os.flush();
        in.close();
        os.close();
        context.responseComplete();
    } catch (Exception e) {
        log.error("Failure : " + e.getMessage());
    }
    return null;
}

From source file:cn.shengyuan.yun.admin.system.controller.CommonController.java

@RequestMapping(value = "/captchaImage", method = RequestMethod.GET)
public String captchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {

    response.setDateHeader("Expires", 0);
    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");
    // return a jpeg
    response.setContentType("image/jpeg");
    // create the text for the image
    String capText = captchaProducer.createText();
    // store the text in the session
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    // create the image with the text
    BufferedImage bi = captchaProducer.createImage(capText);
    ServletOutputStream out = response.getOutputStream();
    // write the data out
    ImageIO.write(bi, "jpg", out);
    try {//w  ww  .java2s. c  o m
        out.flush();
    } finally {
        out.close();
    }
    return null;

}