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.ReportRunAction.java

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

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

    int exportType = Integer
            .parseInt((String) ActionContext.getContext().getSession().get(ORStatics.EXPORT_TYPE));

    Map reportParameters = getReportParameterMap(user, report, exportType);
    Map imagesMap = getImagesMap();

    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    // set headers to disable caching      
    response.setHeader("Pragma", "public");
    response.setHeader("Cache-Control", "max-age=0");

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

    JRVirtualizer virtualizer = null;/*from ww  w.  j a v  a 2  s .c o m*/

    try {
        if (exportType == ReportEngine.EXPORT_PDF) {
            // Handle "contype" request from Internet Explorer
            if ("contype".equals(request.getHeader("User-Agent"))) {
                response.setContentType("application/pdf");
                response.setContentLength(0);

                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.close();

                return NONE;
            }
        }

        log.debug("Filling report: " + report.getName());

        reportLogProvider.insertReportLog(reportLog);

        if (report.isVirtualizationEnabled() && exportType != ReportEngine.EXPORT_IMAGE) {
            log.debug("Virtualization Enabled");
            virtualizer = new JRFileVirtualizer(2, directoryProvider.getTempDirectory());
            reportParameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
        }

        ReportEngineInput reportInput = new ReportEngineInput(report, reportParameters);
        reportInput.setExportType(exportType);
        reportInput.setImagesMap(imagesMap);

        // add any charts
        if (report.getReportChart() != null) {
            log.debug("Adding chart: " + report.getReportChart().getName());

            ChartReportEngine chartEngine = new ChartReportEngine(dataSourceProvider, directoryProvider,
                    propertiesProvider);

            ChartEngineOutput chartOutput = (ChartEngineOutput) chartEngine.generateReport(reportInput);

            reportParameters.put("ChartImage", chartOutput.getContent());
        }

        ReportEngineOutput reportOutput = null;
        JasperPrint jasperPrint = null;

        if (report.isJasperReport()) {
            JasperReportEngine jasperEngine = new JasperReportEngine(dataSourceProvider, directoryProvider,
                    propertiesProvider);

            jasperPrint = jasperEngine.fillReport(reportInput);

            log.debug("Report filled - " + report.getName() + " : size = " + jasperPrint.getPages().size());

            log.debug("Exporting report: " + report.getName());

            reportOutput = jasperEngine.exportReport(jasperPrint, exportType, report.getReportExportOption(),
                    imagesMap, false);
        } else {
            ReportEngine reportEngine = ReportEngineHelper.getReportEngine(report, dataSourceProvider,
                    directoryProvider, propertiesProvider);
            reportOutput = reportEngine.generateReport(reportInput);
        }

        response.setContentType(reportOutput.getContentType());

        if (exportType != ReportEngine.EXPORT_HTML && exportType != ReportEngine.EXPORT_IMAGE) {
            response.setHeader("Content-disposition", "inline; filename="
                    + StringUtils.deleteWhitespace(report.getName()) + reportOutput.getContentExtension());
        }

        if (exportType == ReportEngine.EXPORT_IMAGE) {
            if (jasperPrint != null) {
                ActionContext.getContext().getSession().put(ORStatics.JASPERPRINT, jasperPrint);
            }
        } else {
            byte[] content = reportOutput.getContent();

            response.setContentLength(content.length);

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

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

        log.debug("Finished report: " + report.getName());
    } catch (Exception e) {
        if (e.getMessage() != null && e.getMessage().indexOf("Empty") > 0) {
            addActionError(LocalStrings.getString(LocalStrings.ERROR_REPORT_EMPTY));
            reportLog.setStatus(ReportLog.STATUS_EMPTY);
        } else {
            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 {
        if (virtualizer != null) {
            reportParameters.remove(JRParameter.REPORT_VIRTUALIZER);
            virtualizer.cleanup();
        }
    }

    if (exportType == ReportEngine.EXPORT_IMAGE)
        return SUCCESS;

    return NONE;
}

From source file:com.rplt.studioMusik.controller.OperatorController.java

@RequestMapping(value = "/cetakNota", method = RequestMethod.GET)
public String cetakNota(HttpServletResponse response) {
    Connection conn = DatabaseConnection.getmConnection();
    //            File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file
    File reportFile = new File(
            servletConfig.getServletContext().getRealPath("/resources/report/nota_persewaan.jasper"));

    Map parameters = new HashMap();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("P_KODESEWA", request.getParameter("kodeSewa"));
    byte[] bytes = null;
    try {/* ww w. ja  va2 s.c  o  m*/
        bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn);
    } catch (JRException ex) {
        Logger.getLogger(OperatorController.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.setContentType("application/pdf");
    response.setContentLength(bytes.length);

    try {
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(bytes, 0, bytes.length);
        outStream.flush();
        outStream.close();
    } catch (IOException ex) {
        Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "halaman-cetakNota-operator";
}

From source file:com.indoqa.httpproxy.HttpClientProxy.java

private void writeResponseBody(InputStream responseBody, ServletOutputStream outputStream) throws IOException {
    try {/*  w  ww.  ja v a 2s  . c  o m*/
        byte[] buffer = new byte[STREAMCOPY_BUFFER_SIZE];
        int n;

        while ((n = responseBody.read(buffer)) > STREAMCOPY_EOF) {
            outputStream.write(buffer, 0, n);
        }
    } finally {
        responseBody.close();
        outputStream.close();
    }
}

From source file:org.foxbpm.web.controller.AbstWebController.java

/**
 * ?// w ww.  j a va 2 s.  c  o m
 * 
 * @param response
 *            ?
 * @param in
 *            ??
 */
public void doResponse(HttpServletResponse response, InputStream in) {
    try {
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("application/octet-stream;charset=UTF-8");
        byte[] buff = new byte[2048];
        int size = 0;
        while (in != null && (size = in.read(buff)) != -1) {
            out.write(buff, 0, size);
        }
        out.flush();
    } catch (Exception e) {
        throw new FoxbpmWebException(e);
    }
}

From source file:net.sourceforge.hunterj.javadocViewer.JavadocViewerServlet.java

/**
 * /*from   w w  w .  j  ava 2 s . com*/
 * @param response
 * @param url
 * @throws IOException
 */
private void doGetRemoteResource(HttpServletResponse response, String url) throws IOException {
    URL remoteResource = new URL(url);
    try (BufferedInputStream in = new BufferedInputStream(remoteResource.openStream())) {
        int length = -1;
        int bufferSize = 1024 * 2;
        byte[] buffer = new byte[bufferSize];

        ServletOutputStream out = response.getOutputStream();
        while ((length = in.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.close();
    }
}

From source file:org.wso2.carbon.registry.resource.servlets.ResourceServlet.java

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

    try {//from ww  w  .j ava 2  s .  c om
        UserRegistry registry = (UserRegistry) request.getSession()
                .getAttribute(RegistryConstants.ROOT_REGISTRY_INSTANCE);
        String path = request.getParameter("path");
        if (path == null) {
            String msg = "Could not get the resource content. Path is not specified.";
            log.error(msg);
            response.setStatus(400);
            return;
        }

        Resource resource = null;
        try {
            resource = registry.get(path);
        } catch (RegistryException e) {
            String msg = "Error retrieving the resource " + path + ". " + e.getMessage();
            log.error(msg, e);
            throw e;
        }

        if (resource instanceof Collection) {
            String msg = "Could not get the resource content. Path " + path + " refers to a collection.";
            log.error(msg);
            response.setStatus(501);
            return;
        }

        response.setDateHeader("Last-Modified", resource.getLastModified().getTime());

        if (resource.getMediaType() != null && resource.getMediaType().length() > 0) {
            response.setContentType(resource.getMediaType());
        } else {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + RegistryUtils.getResourceName(path));
            response.setContentType("application/download");
        }

        InputStream contentStream = resource.getContentStream();
        if (contentStream != null) {

            try {
                ServletOutputStream servletOutputStream = response.getOutputStream();
                byte[] contentChunk = new byte[1024];
                int byteCount;
                while ((byteCount = contentStream.read(contentChunk)) != -1) {
                    servletOutputStream.write(contentChunk, 0, byteCount);
                }

                response.flushBuffer();
                servletOutputStream.flush();

            } finally {
                contentStream.close();
            }

        } else {
            Object content = resource.getContent();
            if (content != null) {

                if (content instanceof byte[]) {
                    ServletOutputStream servletOutputStream = response.getOutputStream();
                    servletOutputStream.write((byte[]) content);
                    response.flushBuffer();
                    servletOutputStream.flush();
                } else {
                    PrintWriter writer = response.getWriter();
                    writer.write(content.toString());
                    writer.flush();
                }
            }
        }

        resource.discard();

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

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

protected void handlePreview(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("application/json");
    Gson gson = new Gson();

    BufferedReader reader = req.getReader();
    String msg = IOUtils.toString(reader);
    System.out.println("Msg: " + msg);

    Map<String, Object> params = gson.fromJson(msg, Map.class);
    String url = req.getPathInfo();
    System.out.println("Path: " + url);

    params.put(QUEUE_PREPEND + "action", "preview");

    int idx = url.indexOf("/", 1);
    String kernel_name = url.substring(1, idx);

    System.out.println("kernel: " + kernel_name);
    System.out.println("que: " + QUEUE_PREPEND + kernel_name);
    String qurl = queUrlMap.get(QUEUE_PREPEND + kernel_name);

    if (qurl == null) {
        System.out.println("Unknown que");
        issueError("Unknown queue: " + kernel_name, resp);
        return;/* w ww. jav  a 2  s .  c  om*/
    }

    // TODO: Need to insure < 64K
    msg = gson.toJson(params);
    SQSEnqueueTask task = new SQSEnqueueTask(sqs, qurl, msg);
    threadPool.submit(task);

    Map<String, Object> result = new HashMap<String, Object>();

    result.put("result", "success");

    String json = gson.toJson(result);

    resp.setContentLength(json.length());
    resp.setStatus(HttpServletResponse.SC_OK);

    ServletOutputStream sos = resp.getOutputStream();
    byte[] ba = json.getBytes();
    sos.write(ba, 0, ba.length);

    resp.flushBuffer();
}

From source file:shapeways.api.robocreator.RoboCreatorWeb.java

protected void handleOrder(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("application/json");
    Gson gson = new Gson();

    BufferedReader reader = req.getReader();
    String msg = IOUtils.toString(reader);
    System.out.println("Msg: " + msg);

    Map<String, Object> params = gson.fromJson(msg, Map.class);
    String url = req.getPathInfo();
    System.out.println("Path: " + url);

    params.put(QUEUE_PREPEND + "action", "order");

    int idx = url.indexOf("/", 1);
    String kernel_name = url.substring(1, idx);

    System.out.println("kernel: " + kernel_name);
    System.out.println("que: " + QUEUE_PREPEND + kernel_name);
    String qurl = queUrlMap.get(QUEUE_PREPEND + kernel_name);

    if (qurl == null) {
        System.out.println("Unknown que");
        issueError("Unknown queue: " + kernel_name, resp);
        return;/*from   www  .  java2  s  . c  o m*/
    }

    // TODO: Need to insure < 64K
    msg = gson.toJson(params);
    SQSEnqueueTask task = new SQSEnqueueTask(sqs, qurl, msg);
    threadPool.submit(task);

    Map<String, Object> result = new HashMap<String, Object>();

    result.put("result", "success");

    String json = gson.toJson(result);

    resp.setContentLength(json.length());
    resp.setStatus(HttpServletResponse.SC_OK);

    ServletOutputStream sos = resp.getOutputStream();
    byte[] ba = json.getBytes();
    sos.write(ba, 0, ba.length);

    resp.flushBuffer();

}

From source file:edu.usu.sdl.openstorefront.web.action.resolution.RangeResolution.java

@Override
protected void stream(HttpServletResponse response) throws Exception {
    int bufferLength;
    if (in != null && totalLength >= 0) {
        byte[] buffer = new byte[512];
        long count = 0;

        try {/* w ww .  j  a va  2s.  c o  m*/
            ServletOutputStream out = response.getOutputStream();

            List<Range<Long>> byteRanges = parseRangeHeader(request.getHeader("Range"));
            if (byteRanges == null) {
                while ((bufferLength = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bufferLength);
                }
            } else {
                for (Range<Long> byteRange : byteRanges) {
                    // See RFC 2616 section 14.16
                    if (byteRanges.size() > 1) {
                        out.print("--" + MULTIPART_BOUNDARY + "\r\n");
                        out.print("Content-Type: " + contentType + "\r\n");
                        out.print("Content-Range: bytes " + byteRange.getStart() + "-" + byteRange.getEnd()
                                + "/" + totalLength + "\r\n");
                        out.print("\r\n");
                    }
                    if (count < byteRange.getStart()) {
                        long skip;

                        skip = byteRange.getStart() - count;
                        long actualbytesSkiped = in.skip(skip);
                        log.log(Level.FINEST, MessageFormat.format("Actual Bytes Skipped from range: {0}",
                                actualbytesSkiped));
                        count += skip;
                    }
                    while ((bufferLength = in.read(buffer, 0,
                            (int) Math.min(buffer.length, byteRange.getEnd() + 1 - count))) != -1) {
                        try {
                            out.write(buffer, 0, bufferLength);
                        } catch (IOException io) {
                            //Client Abort
                            break;
                        }
                        count += bufferLength;
                        if (byteRange.getEnd() + 1 == count) {
                            break;
                        }
                    }
                    if (byteRanges.size() > 1) {
                        out.print("\r\n");
                    }
                }
                if (byteRanges.size() > 1) {
                    out.print("--" + MULTIPART_BOUNDARY + "--\r\n");
                }
            }
        } catch (IOException io) {
            //Ignore Client Abort
            log.log(Level.FINEST, "Range Resolution Error ", io);
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                log.log(Level.WARNING, "Error closing input stream", e);
            }
        }
    }

}

From source file:com.concursive.connect.web.modules.documents.beans.FileDownload.java

/**
 * Description of the Method/*from  ww  w  .j a  v  a  2  s. co m*/
 *
 * @param context     Description of the Parameter
 * @param bytes       Description of the Parameter
 * @param contentType Description of the Parameter
 * @throws Exception Description of the Exception
 */
public void sendFile(ActionContext context, byte[] bytes, String contentType) throws Exception {
    context.getResponse().setContentType(contentType);
    if (contentType.startsWith("application")) {
        context.getResponse().setHeader("Content-Disposition", "attachment; filename=\"" + displayName + "\";");
        context.getResponse().setContentLength(bytes.length);
    }
    ServletOutputStream outputStream = context.getResponse().getOutputStream();
    outputStream.write(bytes, 0, bytes.length);
    outputStream.flush();
    outputStream.close();
}