Example usage for java.io ByteArrayOutputStream writeTo

List of usage examples for java.io ByteArrayOutputStream writeTo

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream writeTo.

Prototype

public synchronized void writeTo(OutputStream out) throws IOException 

Source Link

Document

Writes the complete contents of this ByteArrayOutputStream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count) .

Usage

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String generateBillofLadingReport() {

    Documents documentEntity = documentsService.findDocumentById(documentIdParam);
    String orderId = (documentEntity.getReferenceId()).toString();

    Map<String, String> params = new HashMap();
    params.put("orderId", orderId);

    ByteArrayOutputStream byteArray = null;
    BufferedOutputStream responseOut = null;

    try {//w  w  w  . ja v  a  2  s. c o m
        // Create an output filename
        final File outputFile = new File("Bill of Lading.pdf");
        // Generate the report
        MasterReport report = houseBillofLadingReportService.generateReport(params);

        HttpServletResponse response = ServletActionContext.getResponse();
        responseOut = new BufferedOutputStream(response.getOutputStream());
        byteArray = new ByteArrayOutputStream();

        boolean isRendered = PdfReportUtil.createPDF(report, byteArray);
        byteArray.writeTo(responseOut);

        byteArray.close();
        responseOut.close();

    } catch (Exception re) {
        re.printStackTrace();
    }
    return null;
}

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String generateBookingRequestReport() {

    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>documentIdParam " + documentIdParam);

    Documents documentEntity = documentsService.findDocumentById(documentIdParam);
    String orderId = (documentEntity.getReferenceId()).toString();

    Map<String, String> params = new HashMap();
    params.put("orderId", orderId);

    ByteArrayOutputStream byteArray = null;
    BufferedOutputStream responseOut = null;

    try {//from  w  ww . j a  va 2s.c  o  m
        // Create an output filename
        final File outputFile = new File("Booking Request Form.pdf");
        // Generate the report
        MasterReport report = bookingRequestReportService.generateReport(params);

        HttpServletResponse response = ServletActionContext.getResponse();
        responseOut = new BufferedOutputStream(response.getOutputStream());
        byteArray = new ByteArrayOutputStream();

        boolean isRendered = PdfReportUtil.createPDF(report, byteArray);
        byteArray.writeTo(responseOut);

        byteArray.close();
        responseOut.close();

    } catch (Exception re) {
        re.printStackTrace();
    }
    return null;
}

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String generateAcceptanceReceiptReport() {

    Documents documentEntity = documentsService.findDocumentById(documentIdParam);
    String orderId = (documentEntity.getReferenceId()).toString();
    String documentId = (documentEntity.getDocumentId().toString());

    Map<String, String> params = new HashMap();
    params.put("orderId", orderId);
    params.put("documentId", documentId);

    ByteArrayOutputStream byteArray = null;
    BufferedOutputStream responseOut = null;

    try {//from w w w.ja  v  a  2s.co  m
        // Create an output filename
        final File outputFile = new File("Acceptance Receipt.pdf");
        // Generate the report
        MasterReport report = acceptanceReceiptReportService.generateReport(params);

        HttpServletResponse response = ServletActionContext.getResponse();
        responseOut = new BufferedOutputStream(response.getOutputStream());
        byteArray = new ByteArrayOutputStream();

        boolean isRendered = PdfReportUtil.createPDF(report, byteArray);
        byteArray.writeTo(responseOut);

        byteArray.close();
        responseOut.close();

    } catch (Exception re) {
        re.printStackTrace();
    }
    return null;
}

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String generateConsolidationManifestReport() {

    Documents documentEntity = documentsService.findDocumentById(documentIdParam);
    String containerId = (documentEntity.getReferenceId()).toString();

    Map<String, String> params = new HashMap();
    params.put("documentId", documentIdParam.toString());
    params.put("containerId", containerId);

    ByteArrayOutputStream byteArray = null;
    BufferedOutputStream responseOut = null;

    try {//from   w  w  w .  j a  v a2  s.com
        // Create an output filename
        final File outputFile = new File("Consolidation Manifest.pdf");
        // Generate the report
        MasterReport report = consolidationManifestReportService.generateReport(params);

        HttpServletResponse response = ServletActionContext.getResponse();
        responseOut = new BufferedOutputStream(response.getOutputStream());
        byteArray = new ByteArrayOutputStream();

        boolean isRendered = PdfReportUtil.createPDF(report, byteArray);
        byteArray.writeTo(responseOut);

        byteArray.close();
        responseOut.close();

    } catch (Exception re) {
        re.printStackTrace();
    }
    return null;
}

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String generateHouseWayBillDestinationReport() {

    Documents documentEntity = documentsService.findDocumentById(documentIdParam);
    String orderId = (documentEntity.getReferenceId()).toString();
    String documentId = (documentEntity.getDocumentId().toString());

    Map<String, String> params = new HashMap();
    params.put("orderId", orderId);
    params.put("documentId", documentId);

    ByteArrayOutputStream byteArray = null;
    BufferedOutputStream responseOut = null;

    try {//w ww . j a  va2 s. c  om
        // Create an output filename
        final File outputFile = new File("Way Bill Destination.pdf");
        // Generate the report
        MasterReport report = houseWayBillDestinationReportService.generateReport(params);

        HttpServletResponse response = ServletActionContext.getResponse();
        responseOut = new BufferedOutputStream(response.getOutputStream());
        byteArray = new ByteArrayOutputStream();

        boolean isRendered = PdfReportUtil.createPDF(report, byteArray);
        byteArray.writeTo(responseOut);

        byteArray.close();
        responseOut.close();

    } catch (Exception re) {
        re.printStackTrace();
    }
    return null;
}

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String generateAuthorizationToWithdrawReport() {

    Documents documentEntity = documentsService.findDocumentById(documentIdParam);
    String orderId = (documentEntity.getReferenceId()).toString();
    String documentId = (documentEntity.getDocumentId()).toString();

    Map<String, String> params = new HashMap();
    params.put("orderId", orderId);
    params.put("documentId", documentId);

    ByteArrayOutputStream byteArray = null;
    BufferedOutputStream responseOut = null;

    try {//  w w w  . j a v a 2  s  .  c o m
        // Create an output filename
        final File outputFile = new File("Authorization to Withdraw.pdf");
        // Generate the report
        MasterReport report = authorizationToWithdrawReportService.generateReport(params);

        HttpServletResponse response = ServletActionContext.getResponse();
        responseOut = new BufferedOutputStream(response.getOutputStream());
        byteArray = new ByteArrayOutputStream();

        boolean isRendered = PdfReportUtil.createPDF(report, byteArray);
        byteArray.writeTo(responseOut);

        byteArray.close();
        responseOut.close();

    } catch (Exception re) {
        re.printStackTrace();
    }

    return null;
}

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String generateEIR1RequestReport() {

    Documents documentEntity = documentsService.findDocumentById(documentIdParam);
    String containerId = (documentEntity.getReferenceId()).toString();

    Map<String, String> params = new HashMap();
    params.put("containerId", containerId);

    ByteArrayOutputStream byteArray = null;
    BufferedOutputStream responseOut = null;

    try {/*from ww  w . j av a2  s. c o m*/
        // Create an output filename
        final File outputFile = new File("Equipment Interchange Receipt 1.pdf");
        // Generate the report
        MasterReport report = equipmentInterchangeReceipt1ReportService.generateReport(params);

        HttpServletResponse response = ServletActionContext.getResponse();
        responseOut = new BufferedOutputStream(response.getOutputStream());
        byteArray = new ByteArrayOutputStream();

        boolean isRendered = PdfReportUtil.createPDF(report, byteArray);
        byteArray.writeTo(responseOut);

        byteArray.close();
        responseOut.close();

    } catch (Exception re) {
        re.printStackTrace();
    }
    return null;
}

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String generateEIR2RequestReport() {

    Documents documentEntity = documentsService.findDocumentById(documentIdParam);
    String containerId = (documentEntity.getReferenceId()).toString();

    Map<String, String> params = new HashMap();
    params.put("containerId", containerId);

    ByteArrayOutputStream byteArray = null;
    BufferedOutputStream responseOut = null;

    try {//from www  .  ja va2s  . c om
        // Create an output filename
        final File outputFile = new File("Equipment Interchange Receipt 2.pdf");
        // Generate the report
        MasterReport report = equipmentInterchangeReceipt2ReportService.generateReport(params);

        HttpServletResponse response = ServletActionContext.getResponse();
        responseOut = new BufferedOutputStream(response.getOutputStream());
        byteArray = new ByteArrayOutputStream();

        boolean isRendered = PdfReportUtil.createPDF(report, byteArray);
        byteArray.writeTo(responseOut);

        byteArray.close();
        responseOut.close();

    } catch (Exception re) {
        re.printStackTrace();
    }
    return null;
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given {@link HttpServletResponse}
 * /*  w  w w. j  a  v  a2 s.  c  o  m*/
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied response back to the client
 * @param digest
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, String user, String password, ProxyInfo proxyInfo)
        throws IOException, ServletException {

    if (user != null && password != null) {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, upc);
    }

    httpMethodProxyRequest.setFollowRedirects(false);

    InputStream inputStreamServerResponse = null;
    ByteArrayOutputStream baos = null;

    try {

        // //////////////////////////
        // Execute the request
        // //////////////////////////

        int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

        onRemoteResponse(httpMethodProxyRequest);

        // ////////////////////////////////////////////////////////////////////////////////
        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        // ////////////////////////////////////////////////////////////////////////////////

        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {

            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(Utils.LOCATION_HEADER).getValue();

            if (stringLocation == null) {
                throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                        + Utils.LOCATION_HEADER + " header was found in the response");
            }

            // /////////////////////////////////////////////
            // Modify the redirect to go to this proxy
            // servlet rather that the proxied host
            // /////////////////////////////////////////////

            String stringMyHostName = httpServletRequest.getServerName();

            if (httpServletRequest.getServerPort() != 80) {
                stringMyHostName += ":" + httpServletRequest.getServerPort();
            }

            stringMyHostName += httpServletRequest.getContextPath();
            httpServletResponse.sendRedirect(stringLocation.replace(
                    Utils.getProxyHostAndPort(proxyInfo) + proxyInfo.getProxyPath(), stringMyHostName));

            return;

        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {

            // ///////////////////////////////////////////////////////////////
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            // ///////////////////////////////////////////////////////////////

            httpServletResponse.setIntHeader(Utils.CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

            return;
        }

        // /////////////////////////////////////////////
        // Pass the response code back to the client
        // /////////////////////////////////////////////

        httpServletResponse.setStatus(intProxyResponseCode);

        // /////////////////////////////////////////////
        // Pass response headers back to the client
        // /////////////////////////////////////////////

        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();

        for (Header header : headerArrayResponse) {

            // /////////////////////////
            // Skip GZIP Responses
            // /////////////////////////

            if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_ACCEPT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING))
                continue;
            //                else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_WWW_AUTHENTICATE))
            //                    continue;                
            else
                httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // ///////////////////////////////////
        // Send the content to the client
        // ///////////////////////////////////

        inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();

        if (inputStreamServerResponse != null) {
            byte[] b = new byte[proxyConfig.getDefaultStreamByteSize()];

            baos = new ByteArrayOutputStream(b.length);

            int read = 0;
            while ((read = inputStreamServerResponse.read(b)) > 0) {
                baos.write(b, 0, read);
                baos.flush();
            }

            baos.writeTo(httpServletResponse.getOutputStream());
        }

    } catch (HttpException e) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error executing HTTP method ", e);
    } finally {
        try {
            if (inputStreamServerResponse != null)
                inputStreamServerResponse.close();
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing request input stream ", e);
            throw new ServletException(e.getMessage());
        }

        try {
            if (baos != null) {
                baos.flush();
                baos.close();
            }
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing response stream ", e);
            throw new ServletException(e.getMessage());
        }

        httpMethodProxyRequest.releaseConnection();
    }
}

From source file:org.sakaiproject.calendar.impl.BaseCalendarService.java

protected void handleAccessPdf(HttpServletRequest req, HttpServletResponse res, Reference ref, String calRef)
        throws EntityPermissionException, EntityNotDefinedException {
    try {/* ww w.j ava2 s.com*/
        Properties options = new Properties();
        Enumeration e = req.getParameterNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String[] values = req.getParameterValues(key);
            if (values.length == 1) {
                options.put(key, values[0]);
            } else {
                StringBuilder buf = new StringBuilder();
                for (int i = 0; i < values.length; i++) {
                    buf.append(values[i] + "^");
                }
                options.put(key, buf.toString());
            }
        }

        // We need to write to a temporary stream for better speed, plus
        // so we can get a byte count. Internet Explorer has problems
        // if we don't make the setContentLength() call.
        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        res.addHeader("Content-Disposition", "inline; filename=\"schedule.pdf\"");
        res.setContentType(PDF_MIME_TYPE);
        printSchedule(options, outByteStream);
        res.setContentLength(outByteStream.size());

        if (outByteStream.size() > 0) {
            // Increase the buffer size for more speed.
            res.setBufferSize(outByteStream.size());
        }

        OutputStream out = null;
        try {
            out = res.getOutputStream();
            if (outByteStream.size() > 0) {
                outByteStream.writeTo(out);
            }
            out.flush();
            out.close();
        } catch (Throwable ignore) {
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Throwable ignore) {
                }
            }
        }
    } catch (Throwable t) {
        throw new EntityNotDefinedException(ref.getReference());
    }
}