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:org.chiba.xml.xforms.connector.serializer.FormDataSerializer.java

/**
 * Serialize instance into multipart/form-data stream as defined in
 * http://www.w3.org/TR/xforms/slice11.html#serialize-form-data
 *
 * @param submission//from   w ww . j  a v  a  2s  .  c  om
 * @param instance
 * @param stream
 * @param defaultEncoding
 * @throws Exception on error
 */
public void serialize(Submission submission, Node instance, OutputStream stream, String defaultEncoding)
        throws Exception {
    // sanity checks
    if (instance == null)
        return;

    switch (instance.getNodeType()) {

    case Node.ELEMENT_NODE:
        break;

    case Node.DOCUMENT_NODE:
        instance = ((Document) instance).getDocumentElement();
        break;

    default:
        return;
    }

    String encoding = defaultEncoding;
    if (submission.getEncoding() != null) {
        encoding = submission.getEncoding();
    }

    // generate boundary
    Random rnd = new Random(System.currentTimeMillis());
    String boundary = DigestUtils.md5Hex(getClass().getName() + rnd.nextLong());

    // serialize the instance
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(bos, encoding)));
    serializeElement(writer, (Element) instance, boundary, encoding);
    writer.print("\r\n--" + boundary + "--");
    writer.flush();

    // write to the stream
    String header = "Content-Type: multipart/form-data;\r\n" + "\tcharset=\"" + encoding + "\";\r\n"
            + "\tboundary=\"" + boundary + "\";\r\n" + "Content-Length: " + bos.size() + "\r\n\r\n";
    stream.write(header.getBytes(encoding));
    bos.writeTo(stream);
}

From source file:org.fl.modules.excel.poi.exportExcel.multi.SXSSFWorkBookOperation.java

public void compressFiles2Zip() {
    org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = new org.apache.commons.io.output.ByteArrayOutputStream();
    try {//  w ww  . j  a  va 2 s . c o  m
        byteArrayOutputStream = write(byteArrayOutputStream);
        ZipArchiveOutputStream zaos = null;
        zaos = new ZipArchiveOutputStream(byteArrayOutputStream);
        // Use Zip64 extensions for all entries where they are required
        zaos.setUseZip64(Zip64Mode.AsNeeded);
        if (byteArrayOutputStream != null) {
            ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry("excel");
            zaos.putArchiveEntry(zipArchiveEntry);
            try {
                byteArrayOutputStream.writeTo(zaos);
                zaos.closeArchiveEntry();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.kuali.kfs.kns.util.WebUtils.java

/**
 * A file that is not of type text/plain or text/html can be output through
 * the response using this method./*from w  ww . ja  va  2  s  .c  om*/
 *
 * @param response
 * @param contentType
 * @param byteArrayOutputStream
 * @param fileName
 */
public static void saveMimeOutputStreamAsFile(HttpServletResponse response, String contentType,
        ByteArrayOutputStream byteArrayOutputStream, String fileName) throws IOException {
    // If there are quotes in the name, we should replace them to avoid issues.
    // The filename will be wrapped with quotes below when it is set in the header
    String updateFileName;
    if (fileName.contains("\"")) {
        updateFileName = fileName.replaceAll("\"", "");
    } else {
        updateFileName = fileName;
    }

    // set response
    response.setContentType(contentType);
    response.setHeader("Content-disposition", "attachment; filename=\"" + updateFileName + "\"");
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(byteArrayOutputStream.size());

    // write to output
    OutputStream outputStream = response.getOutputStream();
    byteArrayOutputStream.writeTo(response.getOutputStream());
    outputStream.flush();
    outputStream.close();
}

From source file:org.kuali.rice.kns.util.WebUtils.java

/**
 * A file that is not of type text/plain or text/html can be output through
 * the response using this method./*from w  w w .  ja  va  2  s  .  c  o m*/
 * 
 * @param response
 * @param contentType
 * @param byteArrayOutputStream
 * @param fileName
 */
public static void saveMimeOutputStreamAsFile(HttpServletResponse response, String contentType,
        ByteArrayOutputStream byteArrayOutputStream, String fileName) throws IOException {

    // If there are quotes in the name, we should replace them to avoid issues.
    // The filename will be wrapped with quotes below when it is set in the header
    String updateFileName;
    if (fileName.contains("\"")) {
        updateFileName = fileName.replaceAll("\"", "");
    } else {
        updateFileName = fileName;
    }

    // set response
    response.setContentType(contentType);
    response.setHeader("Content-disposition", "attachment; filename=\"" + updateFileName + "\"");
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(byteArrayOutputStream.size());

    // write to output
    OutputStream outputStream = response.getOutputStream();
    byteArrayOutputStream.writeTo(response.getOutputStream());
    outputStream.flush();
    outputStream.close();
}

From source file:org.mifosplatform.infrastructure.reportmailingjob.service.ReportMailingJobWritePlatformServiceImpl.java

/** 
 * send Pentaho report file to email recipients
 * /*from w  w w.  ja  v a2s  . c  o  m*/
 * @return None
 **/
private void sendPentahoReportFileToEmailRecipients(final ReportMailingJob reportMailingJob,
        final String fileName, final ByteArrayOutputStream byteArrayOutputStream,
        final StringBuilder errorLog) {
    final Set<String> emailRecipients = this.reportMailingJobValidator
            .validateEmailRecipients(reportMailingJob.getEmailRecipients());

    try {
        final File file = new File(fileName);
        final FileOutputStream outputStream = new FileOutputStream(file);
        byteArrayOutputStream.writeTo(outputStream);

        for (String emailRecipient : emailRecipients) {
            final ReportMailingJobEmailData reportMailingJobEmailData = new ReportMailingJobEmailData(
                    emailRecipient, reportMailingJob.getEmailMessage(), reportMailingJob.getEmailSubject(),
                    file);

            this.reportMailingJobEmailService.sendEmailWithAttachment(reportMailingJobEmailData);
        }

    } catch (IOException e) {
        errorLog.append(
                "The ReportMailingJobWritePlatformServiceImpl.executeReportMailingJobs threw an IOException "
                        + "exception: " + e.getMessage() + " ---------- ");
    }
}

From source file:springapp.web.controller.theme.ResourceController.java

public ModelAndView handleRequest(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {
    String thisControllerUrl = httpServletResponse.encodeURL(httpServletRequest.getRequestURI());
    HttpSession session = httpServletRequest.getSession();

    ServletContext servletContext = session.getServletContext();
    WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    //String resourcesPath = (String)context.getBean("resourcesPath");

    ResourcesHolder currentSchema = (ResourcesHolder) session
            .getAttribute(ApplicationConstants.CURRENT_SCHEMA_ATTRIBUTE_NAME);

    String resourcesPath = currentSchema.getResourcesPath();
    String resourcePath = httpServletRequest.getParameter("resourcePath");
    boolean b = null != resourcePath;
    Integer hashCode = null;/* w  w w . j  a  v a 2s . c  om*/
    if (b)
        try {
            hashCode = new Integer(Integer.parseInt(resourcePath));
        } catch (NumberFormatException e) {
            hashCode = new Integer(resourcePath.hashCode());
        }
    //ResourcesHolder resource = currentSchema.findResourceByPath(resourcePath);
    ResourcesHolder resource = currentSchema.findResourceByPathHashCode(hashCode);

    ResourcesLoader loader = loaderFactory.getResourcesLoader(resource, context);
    OutputStream outputStream = loader.outForWeb(resource, thisControllerUrl, resourcesPath);

    if (outputStream instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream byteArrayOutputStream = (ByteArrayOutputStream) outputStream;
        if (resource instanceof CSSHolderImpl)
            httpServletResponse.setContentType("text/css");
        else if (resource instanceof GIFHolderImpl)
            httpServletResponse.setContentType("image/gif");
        else if (resource instanceof PNGHolderImpl)
            httpServletResponse.setContentType("image/png");

        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        httpServletResponse.setHeader("Expires", "-1");
        httpServletResponse.setContentLength(byteArrayOutputStream.size());

        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        byteArrayOutputStream.writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
    }
    logger.info("ResourceController ! ");

    return null;
}

From source file:gov.utah.dts.det.ccl.actions.facility.information.license.LicensesPrintAction.java

@Action(value = "print-license-letter")
public void doPrintLetter() {
    loadLicense();/*from  w  w  w .jav a 2  s .  c o m*/

    try {
        ByteArrayOutputStream ba = LicenseLetter.generate(license, request);
        if (ba != null && ba.size() > 0) {
            // This is where the response is set
            String filename = "license_letter.pdf";
            response.setContentLength(ba.size());
            response.setContentType("application/pdf");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");

            ServletOutputStream out = response.getOutputStream();
            ba.writeTo(out);
            out.flush();
        }
    } catch (Exception ex) {
        // Generate an error pdf
        ByteArrayOutputStream ba = null;
        try {
            ba = new ByteArrayOutputStream();
            Document document = new Document(PageSize.A4, 50, 50, 100, 100);
            @SuppressWarnings("unused")
            PdfWriter writer = PdfWriter.getInstance(document, ba);
            document.open();
            document.add(new Paragraph("An error occurred while generating the letter document.",
                    FontFactory.getFont("Times-Roman", 12, Font.NORMAL)));
            document.close();
            if (ba != null && ba.size() > 0) {
                // This is where the response is set
                // String filename = getTrackingRecordScreening().getPerson().getFirstAndLastName() + " - " +
                // screeningLetter.getLetterType() + ".pdf";
                response.setContentLength(ba.size());
                response.setContentType("application/pdf");
                response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                // response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");
                response.setHeader("Content-disposition", "attachment");

                ServletOutputStream out = response.getOutputStream();
                ba.writeTo(out);
                out.flush();
            }

        } catch (Exception e) {
            log.error("AN ERROR OCCURRED GENERATING ERROR PDF DOCUMENT: " + e);
        }
    }
}

From source file:bd.gov.forms.web.FormBuilder.java

@RequestMapping(value = "/dloadTemplate", method = RequestMethod.GET)
public void pdfTemplate(@RequestParam(value = "formId", required = true) String formId, ModelMap model,
        HttpServletResponse response) throws IOException {
    //response.setContentType("application/pdf");
    //TODO: file name 

    byte[] fileContent = formDao.getTemplateContent(formId);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(fileContent);/*  w  w  w.  j  av  a 2 s .co m*/

    OutputStream os = response.getOutputStream();

    out.writeTo(os);
    os.flush();
}

From source file:gov.utah.dts.det.ccl.actions.facility.information.license.LicensesPrintAction.java

@Action(value = "print-license-cert")
public void doPrintCertificate() {
    loadLicense();/*from  w w  w  . ja v a  2  s. c  o  m*/

    try {
        ByteArrayOutputStream ba = LicenseCertificate.generate(license, request);
        if (ba != null && ba.size() > 0) {
            // This is where the response is set
            String filename = "license_certificate.pdf";
            response.setContentLength(ba.size());
            response.setContentType("application/pdf");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");

            ServletOutputStream out = response.getOutputStream();
            ba.writeTo(out);
            out.flush();
        }
    } catch (Exception ex) {
        // Generate an error pdf
        ByteArrayOutputStream ba = null;
        try {
            ba = new ByteArrayOutputStream();
            Document document = new Document(PageSize.A4, 50, 50, 100, 100);
            @SuppressWarnings("unused")
            PdfWriter writer = PdfWriter.getInstance(document, ba);
            document.open();
            document.add(new Paragraph("An error occurred while generating the letter document.",
                    FontFactory.getFont("Times-Roman", 12, Font.NORMAL)));
            document.close();
            if (ba != null && ba.size() > 0) {
                // This is where the response is set
                // String filename = getTrackingRecordScreening().getPerson().getFirstAndLastName() + " - " +
                // screeningLetter.getLetterType() + ".pdf";
                response.setContentLength(ba.size());
                response.setContentType("application/pdf");
                response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                // response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");
                response.setHeader("Content-disposition", "attachment");

                ServletOutputStream out = response.getOutputStream();
                ba.writeTo(out);
                out.flush();
            }

        } catch (Exception e) {
            log.error("AN ERROR OCCURRED GENERATING ERROR PDF DOCUMENT: " + e);
        }
    }
}

From source file:org.apache.fop.fonts.type1.Type1SubsetFile.java

protected byte[] stitchFont(ByteArrayOutputStream boasHeader, ByteArrayOutputStream boasMain,
        ByteArrayOutputStream boasTrailer) throws IOException {
    int headerLength = boasHeader.size();
    int mainLength = boasMain.size();

    boasMain.write(128);/*  ww w.ja  v a  2s. co  m*/
    boasMain.write(1);
    updateSectionSize(boasTrailer.size()).writeTo(boasMain);
    boasTrailer.write(128);
    boasTrailer.write(3);

    boasTrailer.writeTo(boasMain);

    boasHeader.write(128);
    boasHeader.write(2);
    //You need to encode the main section first before getting it's size!!!
    updateSectionSize(mainLength).writeTo(boasHeader);
    boasMain.writeTo(boasHeader);

    ByteArrayOutputStream fullFont = new ByteArrayOutputStream();
    fullFont.write(128);
    fullFont.write(1);
    updateSectionSize(headerLength).writeTo(fullFont);
    boasHeader.writeTo(fullFont);

    return fullFont.toByteArray();
}