Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

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

Prototype

public void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this output stream.

Usage

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;//from   ww  w. ja v a  2 s. c om

    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:us.mn.state.health.lims.reports.action.CommonReportPrintAction.java

@SuppressWarnings("unchecked")
@Override/*from  w w w. j  av a 2s  . c  o  m*/
protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    BaseActionForm dynaForm = (BaseActionForm) form;

    PropertyUtils.setProperty(dynaForm, "reportType", request.getParameter("type"));

    IReportCreator reportCreator = ReportImplementationFactory.getReportCreator(request.getParameter("report"));

    String forward = FWD_FAIL;

    if (reportCreator != null) {
        reportCreator.initializeReport(dynaForm);
        reportCreator.setReportPath(getReportPath());

        HashMap<String, String> parameterMap = (HashMap<String, String>) reportCreator.getReportParameters();
        parameterMap.put("SUBREPORT_DIR", getReportPath());

        try {

            response.setContentType(reportCreator.getContentType());
            String responseHeaderName = reportCreator.getResponseHeaderName();
            String responseHeaderContent = reportCreator.getResponseHeaderContent();
            if (!GenericValidator.isBlankOrNull(responseHeaderName)
                    && !GenericValidator.isBlankOrNull(responseHeaderContent)) {
                response.setHeader(responseHeaderName, responseHeaderContent);
            }

            byte[] bytes = reportCreator.runReport();

            response.setContentLength(bytes.length);

            ServletOutputStream servletOutputStream = response.getOutputStream();

            servletOutputStream.write(bytes, 0, bytes.length);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (Exception e) {
            LogEvent.logErrorStack("CommonReportPrintAction", "performAction", e);
            e.printStackTrace();
        }
    }

    if ("patient".equals(request.getParameter("type"))) {
        trackReports(reportCreator, request.getParameter("report"), ReportType.PATIENT);
    }

    return mapping.findForward(forward);
}

From source file:br.com.hslife.orcamento.controller.DocumentoController.java

public void baixarArquivo() {
    if (entity.getArquivo() == null || entity.getArquivo().getDados() == null
            || entity.getArquivo().getDados().length == 0) {
        warnMessage("Nenhum arquivo adicionado!");
    } else {/*w ww.j a va 2  s  .  c  om*/
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        try {
            response.setContentType(entity.getArquivo().getContentType());
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + entity.getArquivo().getNomeArquivo());
            response.setContentLength(entity.getArquivo().getDados().length);
            ServletOutputStream output = response.getOutputStream();
            output.write(entity.getArquivo().getDados(), 0, entity.getArquivo().getDados().length);
            FacesContext.getCurrentInstance().responseComplete();
        } catch (Exception e) {
            errorMessage(e.getMessage());
        }
    }
}

From source file:org.efs.openreports.actions.admin.ReportUploadAction.java

@Override
public String execute() {
    try {/*from  ww  w  .  j  a v  a  2 s.  com*/
        if ("upload".equals(command)) {
            if (reportFile != null) {
                File destinationFile = new File(directoryProvider.getReportDirectory() + reportFileFileName);

                try {
                    if (destinationFile.exists()) {
                        int revisionCount = reportProvider.getReportTemplate(reportFileFileName)
                                .getRevisionCount();
                        File versionedFile = new File(directoryProvider.getReportDirectory()
                                + reportFileFileName + "." + revisionCount);
                        FileUtils.copyFile(destinationFile, versionedFile);
                    }

                    FileUtils.copyFile(reportFile, destinationFile);
                } catch (IOException ioe) {
                    addActionError(ioe.toString());
                    return SUCCESS;
                }
            } else {
                addActionError("Invalid File.");
            }
        }

        if ("download".equals(command)) {
            String templateFileName = revision;

            // if there is a revision at the end of the file name, strip it off
            if (StringUtils.countMatches(templateFileName, ".") > 1) {
                templateFileName = revision.substring(0, revision.lastIndexOf("."));
            }

            File templateFile = new File(directoryProvider.getReportDirectory() + revision);
            byte[] template = FileUtils.readFileToByteArray(templateFile);

            HttpServletResponse response = ServletActionContext.getResponse();
            response.setHeader("Content-disposition", "inline; filename=" + templateFileName);
            response.setContentType("application/octet-stream");
            response.setContentLength(template.length);

            ServletOutputStream out = response.getOutputStream();
            out.write(template, 0, template.length);
            out.flush();
            out.close();
        }

        if ("revert".equals(command)) {
            String templateFileName = revision.substring(0, revision.lastIndexOf("."));

            File revisionFile = new File(directoryProvider.getReportDirectory() + revision);
            File currentFile = new File(directoryProvider.getReportDirectory() + templateFileName);

            // create a new revision from the current version
            int revisionCount = reportProvider.getReportTemplate(templateFileName).getRevisionCount();
            File versionedFile = new File(
                    directoryProvider.getReportDirectory() + templateFileName + "." + revisionCount);
            FileUtils.copyFile(currentFile, versionedFile);

            // copy the selected revision to the current version
            FileUtils.copyFile(revisionFile, currentFile);
        }

        reportTemplates = reportProvider.getReportTemplates();
    } catch (Exception pe) {
        addActionError(pe.getMessage());
    }

    return SUCCESS;
}

From source file:info.magnolia.cms.servlets.Spool.java

/**
 * @param resource File to be returned to the client
 * @param response HttpServletResponse//from  w  w  w.  j ava2 s.c o  m
 * @return <code>true</code> if the file has been written to the servlet output stream without errors
 * @throws IOException for error in accessing the resource or the servlet output stream
 */
private boolean spool(File resource, HttpServletResponse response) throws IOException {
    FileInputStream in = new FileInputStream(resource);

    try {
        ServletOutputStream os = response.getOutputStream();
        byte[] buffer = new byte[8192];
        int read = 0;
        while ((read = in.read(buffer)) > 0) {
            os.write(buffer, 0, read);
        }
        os.flush();
        IOUtils.closeQuietly(os);
    } catch (IOException e) {
        // only log at debug level, tomcat usually throws a ClientAbortException anytime the user stop loading the
        // page
        if (log.isDebugEnabled())
            log.debug("Unable to spool resource due to a " + e.getClass().getName() + " exception", e); //$NON-NLS-1$ //$NON-NLS-2$
        return false;
    } finally {
        IOUtils.closeQuietly(in);
    }
    return true;
}

From source file:org.apache.myfaces.custom.skin.webapp.CachingStyleSheetLoader.java

/**
 * Sends the file into the OutputStream of the response. 
 * @param file The stylesheet file.//from w w w  .  ja v a  2 s .  c  o  m
 * @param response
 * @throws IOException
 */
private void writeFile(File file, HttpServletResponse response) throws IOException {
    response.setContentType(STYLE_TYPE_TEXT_CSS);

    InputStream in = new FileInputStream(file);
    ServletOutputStream out = response.getOutputStream();

    byte[] buffer = new byte[1024];
    for (int size = in.read(buffer); size != -1; size = in.read(buffer)) {
        out.write(buffer, 0, size);
    }
    out.flush();
    in.close();
}

From source file:info.magnolia.cms.servlets.ResourceDispatcher.java

/**
 * Send data as is.// w  w w  . j a v  a  2 s. com
 *
 * @param is  Input stream for the resource
 * @param res HttpServletResponse as received by the service method
 * @throws IOException standard servlet exception
 */
private void sendUnCompressed(InputStream is, HttpServletResponse res) throws IOException {
    ServletOutputStream os = res.getOutputStream();
    byte[] buffer = new byte[8192];
    int read = 0;
    while ((read = is.read(buffer)) > 0) {
        os.write(buffer, 0, read);
    }
    os.flush();
    IOUtils.closeQuietly(os);
}

From source file:eu.europa.ejusticeportal.dss.controller.action.DownloadSealedPdf.java

/**
 * Send the PDF to the http response// ww w . ja  va  2  s. co m
 * @param is the stream containing the PDF
 * @param pdfName the name of the PDF
 * @param response the HttpServletResponse to which the PDF will be written
 * @throws IOException
 */
private void sendPdf(InputStream is, String pdfName, HttpServletResponse response) throws IOException {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + pdfName + "\"");

    ServletOutputStream outs = null;
    try {
        outs = response.getOutputStream();
        int r = 0;
        byte[] chunk = new byte[8192];
        while ((r = is.read(chunk)) != -1) {
            outs.write(chunk, 0, r);
        }
        outs.flush();
    } finally {
        IOUtils.closeQuietly(outs);
    }

}

From source file:sf.net.experimaestro.server.ContentServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    URL url = ContentServlet.class.getResource(format("/web%s", request.getRequestURI()));

    if (url != null) {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(url.toExternalForm());
        if (file.getType() == FileType.FOLDER) {
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", format("%sindex.html", request.getRequestURI()));
            return;
        }/*ww w. java  2s .  c om*/

        String filename = url.getFile();
        if (filename.endsWith(".html"))
            response.setContentType("text/html");
        else if (filename.endsWith(".png"))
            response.setContentType("image/png");
        else if (filename.endsWith(".css"))
            response.setContentType("text/css");
        response.setStatus(HttpServletResponse.SC_OK);

        final ServletOutputStream out = response.getOutputStream();
        InputStream in = url.openStream();
        byte[] buffer = new byte[8192];
        int read;
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.flush();
        in.close();
        return;
    }

    // Not found
    error404(request, response);

}