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:PngEncoder.java

/**
 * Writes the IDAT (Image data) chunks to the output stream.
 *
 * @param out the OutputStream to write the chunk to
 * @param csum the Checksum that is updated as data is written
 *             to the passed-in OutputStream
 * @throws IOException if a problem is encountered writing the output
 *//*from w  w  w .  jav  a 2s .  c  o  m*/
private void writeIdatChunks(OutputStream out, Checksum csum) throws IOException {
    int rowWidth = width * outputBpp; // size of image data in a row in bytes.

    int row = 0;

    Deflater deflater = new Deflater(compressionLevel);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DeflaterOutputStream defOut = new DeflaterOutputStream(byteOut, deflater);

    byte[] filteredPixelQueue = new byte[rowWidth];

    // Output Pixel Queues
    byte[][] outputPixelQueue = new byte[2][rowWidth];
    Arrays.fill(outputPixelQueue[1], (byte) 0);
    int outputPixelQueueRow = 0;
    int outputPixelQueuePrevRow = 1;

    while (row < height) {
        if (filter == null) {
            defOut.write(0);
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            defOut.write(outputPixelQueue[outputPixelQueueRow], 0, rowWidth);
        } else {
            defOut.write(filter.getType());
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            filter.filter(filteredPixelQueue, outputPixelQueue[outputPixelQueueRow],
                    outputPixelQueue[outputPixelQueuePrevRow], outputBpp);
            defOut.write(filteredPixelQueue, 0, rowWidth);
        }

        ++row;
        outputPixelQueueRow = row & 1;
        outputPixelQueuePrevRow = outputPixelQueueRow ^ 1;
    }
    defOut.finish();
    byteOut.close();

    writeInt(out, byteOut.size());
    csum.reset();
    out.write(IDAT);
    byteOut.writeTo(out);
    writeInt(out, (int) csum.getValue());
}

From source file:org.apache.fineract.infrastructure.scheduledemail.service.EmailCampaignWritePlatformCommandHandlerImpl.java

/**
 * This generates the the report and converts it to a file by passing the parameters below
 * @param emailCampaign/* ww w  .  j  av  a  2  s.  c  o  m*/
 * @param emailAttachmentFileFormat
 * @param reportParams
 * @param reportName
 * @param errorLog
 * @return
 */
private File generateAttachments(final EmailCampaign emailCampaign,
        final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat,
        final Map<String, String> reportParams, final String reportName, final StringBuilder errorLog) {

    try {
        final ByteArrayOutputStream byteArrayOutputStream = this.readReportingService
                .generatePentahoReportAsOutputStream(reportName, emailAttachmentFileFormat.getValue(),
                        reportParams, null, emailCampaign.getApprovedBy(), errorLog);

        final String fileLocation = FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator + "";
        final String fileNameWithoutExtension = fileLocation + File.separator + reportName;

        // check if file directory exists, if not create directory
        if (!new File(fileLocation).isDirectory()) {
            new File(fileLocation).mkdirs();
        }

        if (byteArrayOutputStream.size() == 0) {
            errorLog.append("Pentaho report processing failed, empty output stream created");
        } else if (errorLog.length() == 0 && (byteArrayOutputStream.size() > 0)) {
            final String fileName = fileNameWithoutExtension + "." + emailAttachmentFileFormat.getValue();

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

            return file;
        }

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

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = RequestMethod.POST)
public void exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response,
        HttpServletRequest request) throws ServletException, IOException, InterruptedException,
        SVGConverterException, NoSuchElementException, PoolException, TimeoutException {

    long start1 = System.currentTimeMillis();

    MimeType mime = getMime(type);
    filename = getFilename(filename);/*  w  w  w. j  a  v  a  2  s  . c  o  m*/
    Float parsedWidth = widthToFloat(width);
    Float parsedScale = scaleToFloat(scale);
    options = sanitize(options);
    String inputs;

    boolean convertSvg = false;

    // Create return JSON object
    JSONObject jobj = new JSONObject();

    if (options != null) {
        // create a svg file out of the options
        inputs = options;
        callback = sanitize(callback);
    } else {
        jobj.put("status", -1);
        jobj.put("msg", "The svg POST is not supported.");
        response.reset();
        response.setContentType("application/json");
        response.getWriter().print(jobj);
        response.flushBuffer();
        return;
    }

    String[] inputList = inputs.split("!#!");
    String input;

    ByteArrayOutputStream stream = null;
    //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale);

    String fileList = "";
    String chartFilename = "";
    for (int i = 0; i < inputList.length; i++) {
        input = inputList[i];
        stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale);

        if (stream == null) {
            //throw new ServletException("Error while converting");
            jobj.put("status", -1);
            jobj.put("msg", "Error while converting.");
            response.reset();
            response.setContentType("application/json");
            response.getWriter().print(jobj);
            response.flushBuffer();
            return;
        }

        logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1));

        // Now Save the it to file. And return the path.
        String uuid = UUID.randomUUID().toString();
        String extension = ".png";
        if (mime.compareTo(MimeType.JPEG) == 0) {
            extension = ".jpg";
        } else if (mime.compareTo(MimeType.PDF) == 0) {
            extension = ".pdf";
        } else if (mime.compareTo(MimeType.PNG) == 0) {
            extension = ".png";
        } else if (mime.compareTo(MimeType.SVG) == 0) {
            extension = ".svg";
        }

        chartFilename = uuid + extension;
        //OutputStream chartFile = new FileOutputStream ("C:\\inetpub\\wwwroot\\tmp\\"+chartFilename);
        OutputStream chartFile = new FileOutputStream(
                "C:\\Users\\mc142\\Source\\Repos\\JourneyCompass\\website\\tmp\\" + chartFilename);
        stream.writeTo(chartFile);
        chartFile.close();

        if (i == inputList.length - 1) {
            fileList += chartFilename;
        } else {
            fileList += chartFilename + "!#!";
        }
        stream = null;
    }

    jobj.put("filenames", fileList);
    jobj.put("status", 0);
    jobj.put("msg", "success");
    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/json");
    response.setStatus(HttpStatus.OK.value());
    response.addHeader("Access-Control-Allow-Origin", "*");
    //response.setHeader("Access-Control-Allow-Headers", "X-MYRESPONSEHEADER");
    response.getWriter().print(jobj);
    response.flushBuffer();
    /**** This is the original code that let browser saves the file.
    response.reset();      
    response.setCharacterEncoding("utf-8");
    response.setContentLength(stream.size());
    response.setStatus(HttpStatus.OK.value());
    response.setHeader("Content-disposition", "attachment; filename=\""
    + filename + "." + mime.name().toLowerCase() + "\"");
            
    IOUtils.write(stream.toByteArray(), response.getOutputStream());
    response.flushBuffer();
    ****/
}

From source file:microsoft.exchange.webservices.data.AutodiscoverService.java

/**
 * Calls the Autodiscover service to get configuration settings at the
 * specified URL./*from w  w  w . j  av a  2s . c om*/
 *
 * @param <TSettings>  the generic type
 * @param cls          the cls
 * @param emailAddress the email address
 * @param url          the url
 * @return The requested configuration settings. (TSettings The type of the
 * settings to retrieve)
 * @throws Exception the exception
 */
private <TSettings extends ConfigurationSettingsBase> TSettings getLegacyUserSettingsAtUrl(Class<TSettings> cls,
        String emailAddress, URI url) throws Exception {
    this.traceMessage(TraceFlags.AutodiscoverConfiguration,
            String.format("Trying to call Autodiscover for %s on %s.", emailAddress, url));

    TSettings settings = cls.newInstance();

    HttpWebRequest request = null;
    try {
        request = this.prepareHttpWebRequestForUrl(url);

        this.traceHttpRequestHeaders(TraceFlags.AutodiscoverRequestHttpHeaders, request);
        // OutputStreamWriter out = new
        // OutputStreamWriter(request.getOutputStream());
        OutputStream urlOutStream = request.getOutputStream();

        // If tracing is enabled, we generate the request in-memory so that we
        // can pass it along to the ITraceListener. Then we copy the stream to
        // the request stream.
        if (this.isTraceEnabledFor(TraceFlags.AutodiscoverRequest)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

            PrintWriter writer = new PrintWriter(memoryStream);
            this.writeLegacyAutodiscoverRequest(emailAddress, settings, writer);
            writer.flush();

            this.traceXml(TraceFlags.AutodiscoverRequest, memoryStream);
            // out.write(memoryStream.toString());
            // out.close();
            memoryStream.writeTo(urlOutStream);
            urlOutStream.flush();
            urlOutStream.close();
            memoryStream.close();
        } else {
            PrintWriter writer = new PrintWriter(urlOutStream);
            this.writeLegacyAutodiscoverRequest(emailAddress, settings, writer);

            /*  Flush Start */
            writer.flush();
            urlOutStream.flush();
            urlOutStream.close();
            /* Flush End */
        }
        request.executeRequest();
        request.getResponseCode();
        URI redirectUrl;
        OutParam<URI> outParam = new OutParam<URI>();
        if (this.tryGetRedirectionResponse(request, outParam)) {
            redirectUrl = outParam.getParam();
            settings.makeRedirectionResponse(redirectUrl);
            return settings;
        }
        InputStream serviceResponseStream = request.getInputStream();
        // If tracing is enabled, we read the entire response into a
        // MemoryStream so that we
        // can pass it along to the ITraceListener. Then we parse the response
        // from the
        // MemoryStream.
        if (this.isTraceEnabledFor(TraceFlags.AutodiscoverResponse)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

            while (true) {
                int data = serviceResponseStream.read();
                if (-1 == data) {
                    break;
                } else {
                    memoryStream.write(data);
                }
            }
            memoryStream.flush();

            this.traceResponse(request, memoryStream);
            ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
            EwsXmlReader reader = new EwsXmlReader(memoryStreamIn);
            reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT));
            settings.loadFromXml(reader);

        } else {
            EwsXmlReader reader = new EwsXmlReader(serviceResponseStream);
            reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT));
            settings.loadFromXml(reader);
        }

        serviceResponseStream.close();
    } finally {
        if (request != null) {
            try {
                request.close();
            } catch (Exception e2) {
                // Ignore exceptions while closing the request.
            }
        }
    }

    return settings;
}

From source file:microsoft.exchange.webservices.data.autodiscover.AutodiscoverService.java

/**
 * Calls the Autodiscover service to get configuration settings at the
 * specified URL.//  ww w . j a  v  a  2  s.  c  om
 *
 * @param <TSettings>  the generic type
 * @param cls          the cls
 * @param emailAddress the email address
 * @param url          the url
 * @return The requested configuration settings. (TSettings The type of the
 * settings to retrieve)
 * @throws Exception the exception
 */
private <TSettings extends ConfigurationSettingsBase> TSettings getLegacyUserSettingsAtUrl(Class<TSettings> cls,
        String emailAddress, URI url) throws Exception {
    this.traceMessage(TraceFlags.AutodiscoverConfiguration,
            String.format("Trying to call Autodiscover for %s on %s.", emailAddress, url));

    TSettings settings = cls.newInstance();

    HttpWebRequest request = null;
    try {
        request = this.prepareHttpWebRequestForUrl(url);

        this.traceHttpRequestHeaders(TraceFlags.AutodiscoverRequestHttpHeaders, request);
        // OutputStreamWriter out = new
        // OutputStreamWriter(request.getOutputStream());
        OutputStream urlOutStream = request.getOutputStream();

        // If tracing is enabled, we generate the request in-memory so that we
        // can pass it along to the ITraceListener. Then we copy the stream to
        // the request stream.
        if (this.isTraceEnabledFor(TraceFlags.AutodiscoverRequest)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

            PrintWriter writer = new PrintWriter(memoryStream);
            this.writeLegacyAutodiscoverRequest(emailAddress, settings, writer);
            writer.flush();

            this.traceXml(TraceFlags.AutodiscoverRequest, memoryStream);
            // out.write(memoryStream.toString());
            // out.close();
            memoryStream.writeTo(urlOutStream);
            urlOutStream.flush();
            urlOutStream.close();
            memoryStream.close();
        } else {
            PrintWriter writer = new PrintWriter(urlOutStream);
            this.writeLegacyAutodiscoverRequest(emailAddress, settings, writer);

            /*  Flush Start */
            writer.flush();
            urlOutStream.flush();
            urlOutStream.close();
            /* Flush End */
        }
        request.executeRequest();
        request.getResponseCode();
        URI redirectUrl;
        OutParam<URI> outParam = new OutParam<URI>();
        if (this.tryGetRedirectionResponse(request, outParam)) {
            redirectUrl = outParam.getParam();
            settings.makeRedirectionResponse(redirectUrl);
            return settings;
        }
        InputStream serviceResponseStream = request.getInputStream();
        // If tracing is enabled, we read the entire response into a
        // MemoryStream so that we
        // can pass it along to the ITraceListener. Then we parse the response
        // from the
        // MemoryStream.
        if (this.isTraceEnabledFor(TraceFlags.AutodiscoverResponse)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

            while (true) {
                int data = serviceResponseStream.read();
                if (-1 == data) {
                    break;
                } else {
                    memoryStream.write(data);
                }
            }
            memoryStream.flush();

            this.traceResponse(request, memoryStream);
            ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
            EwsXmlReader reader = new EwsXmlReader(memoryStreamIn);
            reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT));
            settings.loadFromXml(reader);

        } else {
            EwsXmlReader reader = new EwsXmlReader(serviceResponseStream);
            reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT));
            settings.loadFromXml(reader);
        }

        serviceResponseStream.close();
    } finally {
        if (request != null) {
            try {
                request.close();
            } catch (Exception e2) {
                // Ignore exception while closing the request.
            }
        }
    }

    return settings;
}

From source file:org.docx4j.template.jsp.engine.JspTemplateImpl.java

private void doInterpret(String requestURL, Map<String, Object> variables, OutputStream output)
        throws IOException, ServletException {
    /**//from  ww  w  . j  a v a 2 s.co  m
      * ServletContext?RequestDispatcher
      */
    ServletContext sc = request.getSession().getServletContext();
    /**
     * ???reqeustDispatcher
     */
    RequestDispatcher rd = sc.getRequestDispatcher(requestURL);
    /**
     * ByteArrayOutputStream?,??
     */
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    /**
     * ServletOutputStreamwrite
     */
    final ServletOutputStream outputStream = new ServletOutputStream() {

        public void write(int b) throws IOException {
            /**
             * ?
             */
            baos.write(b);
        }

        @SuppressWarnings("unused")
        public boolean isReady() {
            return false;
        }

    };
    /**
     *  OutputStream  PrintWriter
     * OutputStreamWriter ????? charset ????
     */
    final PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, config.getOutputEncoding()), true);
    /**
     * ?HttpServletResponse??response
     */
    HttpServletResponse resp = new HttpServletResponseWrapper(response) {
        /**
         * getOutputStream(ServletResponse)ServletOutputStream
         * ?response
         * ?byteArrayOutputStream
         */
        public ServletOutputStream getOutputStream() {
            return outputStream;
        }

        /**
         * ?getWriter(ServletResponse)PrintWriter
         * ???
         */
        public PrintWriter getWriter() {
            return pw;
        }
    };
    /**
     * ?jsp RequestDispatcher.include(ServletRequest request,
     * ServletResponse response) RequestDispatcher??response
     */
    rd.include(request, resp);
    pw.flush();
    /**
     * ByteArrayOutputStreamwriteTo?????ByteArray
     */
    baos.writeTo(output);
}

From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java

/**
 * Builds changes XML document from Bugzilla XML Document
 * //from  w  ww .j av  a  2  s  .  co  m
 * @param bugsDocument
 * @throws MojoExecutionException
 */
private void builChangesXML(final Document bugsDocument) throws MojoExecutionException {
    FileOutputStream fos = null;
    Transform t;
    try {
        t = new Transform(this.getClass().getClassLoader().getResourceAsStream("bugzilla.xsl"));
    } catch (final TransformerConfigurationException e) {
        this.getLog().error("Internal XSL error.", e);
        throw new MojoExecutionException("Error with internal XSL transformation file.", e);
    }
    ByteArrayOutputStream baos = null;
    try {
        // creamos los directorios
        this.createFilePath();
        // formamos el documento de cambios
        final byte[] changesXml = t.transformar(bugsDocument);

        // comprobamos si ya existe el fichero y estamos con currentVersionOnly=true.
        // por lo que hay que mantener los cambios de versiones anteriores
        if (this.currentVersionOnly && this.xmlPath.exists()) {
            final Document changesDocument = this.getChangesDocument();
            // buscamos la release que se corresponde con la versin actual
            final NodeList nodelist = changesDocument.getElementsByTagName(ELEMENT_RELEASE);
            boolean replaced = false;
            for (int i = 0; i < nodelist.getLength(); i++) {
                final Element elementRelease = (Element) nodelist.item(i);
                if (this.versionName.equals(elementRelease.getAttribute(ATTRIBUTE_VERSION))) {
                    // sustituimos el nodo de la release por el que hemos obtenido ahora
                    this.replaceReleaseNode(elementRelease, changesXml);
                    replaced = true;
                    break;
                }
            }
            if (!replaced) {
                this.addNewRelease(changesDocument, changesXml);
            }
            this.saveChangesDocument(changesDocument);

        } else {
            // escribimos el documento XML de cambios
            fos = new FileOutputStream(this.xmlPath);
            baos = new ByteArrayOutputStream();
            baos.write(changesXml);
            baos.writeTo(fos);
            baos.flush();
            fos.flush();
        }

    } catch (final IOException e) {
        this.getLog().error("Error creating file " + this.xmlPath, e);
        throw new MojoExecutionException("Error creating file " + this.xmlPath, e);
    } catch (final TransformerException e) {
        this.getLog().error("Error creating file " + this.xmlPath, e);
        throw new MojoExecutionException("Error creating file " + this.xmlPath, e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (final IOException e) {
                // ignore
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (final IOException e) {
                // ignore
            }
        }
    }

}

From source file:portal.api.repo.PortalRepositoryAPIImpl.java

private String saveFile(ByteArrayOutputStream att, String filePath) throws IOException {

    File f = new File(filePath);
    FileOutputStream fos;/*from w  w  w. ja v  a2s  . c  o m*/
    try {
        fos = new FileOutputStream(f);
        att.writeTo(fos);
        fos.close();
        return f.getAbsolutePath();
    } catch (IOException ioe) {
        // Handle exception here
        ioe.printStackTrace();
    } finally {
    }

    return null;

}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

/**
 * Execute the split of a pdf document when split type is S_SIZE
 * /*from  w  w  w .ja v  a 2s. c om*/
 * @param inputCommand
 * @throws Exception
 */
private void executeSizeSplit(SplitParsedCommand inputCommand) throws Exception {
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    pdfReader.removeUnusedObjects();
    pdfReader.consolidateNamedDestinations();
    int n = pdfReader.getNumberOfPages();
    BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n);
    int fileNum = 0;
    LOG.info("Found " + n + " pages in input pdf document.");
    int currentPage;
    Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
    PdfImportedPage importedPage;
    File tmpFile = null;
    File outFile = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int startPage = 0;
    int relativeCurrentPage = 0;
    for (currentPage = 1; currentPage <= n; currentPage++) {
        relativeCurrentPage++;
        // time to open a new document?
        if (relativeCurrentPage == 1) {
            LOG.debug("Creating a new document.");
            startPage = currentPage;
            fileNum++;
            tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
            FileNameRequest request = new FileNameRequest(currentPage, fileNum, null);
            outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));
            baos = new ByteArrayOutputStream();
            pdfWriter = new PdfSmartCopy(currentDocument, baos);
            // set creator
            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);

            setCompressionSettingOnWriter(inputCommand, pdfWriter);
            setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

            currentDocument.open();
        }

        importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
        pdfWriter.addPage(importedPage);
        // if it's time to close the document
        if ((currentPage == n) || ((relativeCurrentPage > 1) && ((baos.size() / relativeCurrentPage)
                * (1 + relativeCurrentPage) > inputCommand.getSplitSize().longValue()))) {
            LOG.debug("Current stream size: " + baos.size() + " bytes.");
            // manage bookmarks
            List bookmarks = bookmarkProcessor.processBookmarks(startPage, currentPage);
            if (bookmarks != null) {
                pdfWriter.setOutlines(bookmarks);
            }
            relativeCurrentPage = 0;
            currentDocument.close();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            baos.writeTo(fos);
            fos.close();
            baos.close();
            LOG.info("Temporary document " + tmpFile.getName() + " done.");
            FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
            LOG.debug("File " + outFile.getCanonicalPath() + " created.");
        }
        setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
    }
    pdfReader.close();
    LOG.info("Split " + inputCommand.getSplitType() + " done.");
}

From source file:com.wabacus.WabacusFacade.java

private static void exportReportDataOnPDF(String pageid, ReportRequest rrequest, WabacusResponse wresponse) {
    boolean success = true;
    try {/*from   ww w. j a  v a 2  s  . c o m*/
        rrequest.setWResponse(wresponse);
        wresponse.setRRequest(rrequest);
        rrequest.init(pageid);
        if (rrequest.getLstAllReportBeans() == null || rrequest.getLstAllReportBeans().size() == 0) {
            throw new WabacusRuntimeException("?" + pageid
                    + "?plainexcel???");
        }
        Document document = new Document();
        ByteArrayOutputStream baosResult = new ByteArrayOutputStream();
        PdfCopy pdfCopy = new PdfCopy(document, baosResult);
        document.open();
        boolean ispdfprint = rrequest.isPdfPrintAction();
        for (IComponentConfigBean ccbeanTmp : rrequest.getLstComponentBeans()) {//??PDF?
            PDFExportBean pdfbeanTmp = null;
            if (ispdfprint) {
                pdfbeanTmp = ccbeanTmp.getPdfPrintBean();
            } else if (ccbeanTmp.getDataExportsBean() != null) {
                pdfbeanTmp = (PDFExportBean) ccbeanTmp.getDataExportsBean()
                        .getDataExportBean(Consts.DATAEXPORT_PDF);
            }
            if (pdfbeanTmp != null && pdfbeanTmp.getPdftemplate() != null
                    && !pdfbeanTmp.getPdftemplate().trim().equals("")) {
                PdfAssistant.getInstance().addPdfPageToDocument(pdfCopy,
                        PdfAssistant.getInstance().showReportDataOnPdfWithTpl(rrequest, ccbeanTmp));
            }
        }
        AbsReportType reportTypeObjTmp;
        for (ReportBean rbTmp : rrequest.getLstAllReportBeans()) {
            reportTypeObjTmp = (AbsReportType) rrequest.getComponentTypeObj(rbTmp, null, false);
            if (rrequest.isReportInPdfTemplate(rbTmp.getId()))
                continue;//??PDF???
            PdfAssistant.getInstance().addPdfPageToDocument(pdfCopy, reportTypeObjTmp.displayOnPdf());
        }
        document.close();
        BufferedOutputStream bos = null;
        if (rrequest.isExportToLocalFile()) {
            bos = new BufferedOutputStream(new FileOutputStream(new File(rrequest.getDataExportFilepath())));
        } else {
            if (!ispdfprint) {
                String title = WabacusAssistant.getInstance().encodeAttachFilename(rrequest.getRequest(),
                        rrequest.getDataExportFilename());
                wresponse.getResponse().setHeader("Content-disposition",
                        "attachment;filename=" + title + ".pdf");
            }
            wresponse.getResponse().setContentLength(baosResult.size());
            bos = new BufferedOutputStream(wresponse.getResponse().getOutputStream());
        }
        baosResult.writeTo(bos);
        bos.close();
        baosResult.close();
        if (rrequest.isExportToLocalFile() && rrequest.isDataexport_localstroagezip()) {
            tarDataFile(rrequest);
        }
    } catch (WabacusRuntimeTerminateException wrwe) {
        if (wresponse.getStatecode() == Consts.STATECODE_FAILED) {
            success = false;
        }
    } catch (Exception wre) {
        wresponse.setStatecode(Consts.STATECODE_FAILED);
        log.error("?" + rrequest.getPagebean().getId() + "", wre);
        success = false;
    } finally {
        rrequest.destroy(success);
    }
    doPostDataExport(rrequest, wresponse);
}