Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

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

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

From source file:com.wabacus.WabacusFacade.java

private static void exportReportDataOnPDF(String pageid, ReportRequest rrequest, WabacusResponse wresponse) {
    boolean success = true;
    try {/*from w  w  w .  ja  va2  s . com*/
        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);
}

From source file:br.gov.jfrj.siga.vraptor.ExDocumentoController.java

private void lerForm(final ExDocumentoDTO exDocumentoDTO, final String[] vars) throws IOException {

    if (exDocumentoDTO.getAnexar()) {
        exDocumentoDTO.getDoc().setConteudoTpDoc(exDocumentoDTO.getConteudoTpDoc());
        exDocumentoDTO.getDoc().setNmArqDoc(exDocumentoDTO.getNmArqDoc());
    }//  w w w. j a  v  a 2s.c  o  m

    exDocumentoDTO.getDoc().setDescrDocumento(exDocumentoDTO.getDescrDocumento());
    exDocumentoDTO.getDoc().setNmSubscritorExt(exDocumentoDTO.getNmSubscritorExt());
    exDocumentoDTO.getDoc().setNmFuncaoSubscritor(exDocumentoDTO.getNmFuncaoSubscritor());
    exDocumentoDTO.getDoc().setNumExtDoc(exDocumentoDTO.getNumExtDoc());
    exDocumentoDTO.getDoc().setNumAntigoDoc(exDocumentoDTO.getNumAntigoDoc());
    exDocumentoDTO.getDoc().setObsOrgao(exDocumentoDTO.getObsOrgao());
    exDocumentoDTO.getDoc().setEletronico(exDocumentoDTO.getEletronico() == 1 ? true : false);
    exDocumentoDTO.getDoc().setNmOrgaoExterno(exDocumentoDTO.getNmOrgaoExterno());
    exDocumentoDTO.getDoc().setDescrClassifNovo(exDocumentoDTO.getDescrClassifNovo());
    exDocumentoDTO.getDoc()
            .setExNivelAcesso(dao().consultar(exDocumentoDTO.getNivelAcesso(), ExNivelAcesso.class, false));
    exDocumentoDTO.getDoc()
            .setExTipoDocumento(dao().consultar(exDocumentoDTO.getIdTpDoc(), ExTipoDocumento.class, false));

    if (!exDocumentoDTO.getDoc().isFinalizado()) {
        exDocumentoDTO.getDoc().setExFormaDocumento(
                dao().consultar(exDocumentoDTO.getIdFormaDoc(), ExFormaDocumento.class, false));
    }
    exDocumentoDTO.getDoc().setNmDestinatario(exDocumentoDTO.getNmDestinatario());

    exDocumentoDTO.getDoc().setExModelo(null);
    if (exDocumentoDTO.getIdMod() != 0) {
        ExModelo modelo = dao().consultar(exDocumentoDTO.getIdMod(), ExModelo.class, false);
        if (modelo != null) {
            exDocumentoDTO.getDoc().setExModelo(modelo.getModeloAtual());
        }
    }

    if (exDocumentoDTO.getClassificacaoSel().getId() != null
            && exDocumentoDTO.getClassificacaoSel().getId() != 0) {

        final ExClassificacao classificacao = dao().consultar(exDocumentoDTO.getClassificacaoSel().getId(),
                ExClassificacao.class, false);

        if (classificacao != null && !classificacao.isFechada()) {
            exDocumentoDTO.getDoc().setExClassificacao(classificacao);
        } else {
            exDocumentoDTO.getDoc().setExClassificacao(null);
            exDocumentoDTO.getClassificacaoSel().apagar();
        }

    } else {
        exDocumentoDTO.getDoc().setExClassificacao(null);
    }
    if (exDocumentoDTO.getCpOrgaoSel().getId() != null) {
        exDocumentoDTO.getDoc()
                .setOrgaoExterno(dao().consultar(exDocumentoDTO.getCpOrgaoSel().getId(), CpOrgao.class, false));
    } else {
        exDocumentoDTO.getDoc().setOrgaoExterno(null);
    }

    // Orlando: Alterei o IF abaixo incluindo a instruo
    // "doc.setLotaCadastrante(getLotaTitular());".
    // Esta linha estava "solta",aps o IF, e era executada sempre.
    // Fiz esta modificao porque esta linha alterava a lotao do
    // cadastrante, no permitindo que este,
    // ao preencher o campo subscritor com a matrcula de outro usurio,
    // tivesse acesso ao documento.

    if (exDocumentoDTO.getDoc().getCadastrante() == null) {
        exDocumentoDTO.getDoc().setCadastrante(getCadastrante());
        exDocumentoDTO.getDoc().setLotaCadastrante(getLotaTitular());
    }

    if (exDocumentoDTO.getDoc().getLotaCadastrante() == null) {
        exDocumentoDTO.getDoc().setLotaCadastrante(exDocumentoDTO.getDoc().getCadastrante().getLotacao());
    }
    if (exDocumentoDTO.getSubscritorSel().getId() != null) {
        exDocumentoDTO.getDoc().setSubscritor(daoPes(exDocumentoDTO.getSubscritorSel().getId()));
        exDocumentoDTO.getDoc().setLotaSubscritor(exDocumentoDTO.getDoc().getSubscritor().getLotacao());
    } else {
        exDocumentoDTO.getDoc().setSubscritor(null);
    }

    if (exDocumentoDTO.isSubstituicao()) {
        if (exDocumentoDTO.getTitularSel().getId() != null) {
            exDocumentoDTO.getDoc().setTitular(daoPes(exDocumentoDTO.getTitularSel().getId()));
            exDocumentoDTO.getDoc().setLotaTitular(exDocumentoDTO.getDoc().getTitular().getLotacao());
        } else {
            exDocumentoDTO.getDoc().setTitular(exDocumentoDTO.getDoc().getSubscritor());
            exDocumentoDTO.getDoc().setLotaTitular(exDocumentoDTO.getDoc().getLotaSubscritor());
        }
    } else {
        exDocumentoDTO.getDoc().setTitular(exDocumentoDTO.getDoc().getSubscritor());
        exDocumentoDTO.getDoc().setLotaTitular(exDocumentoDTO.getDoc().getLotaSubscritor());
    }

    if (exDocumentoDTO.getDestinatarioSel().getId() != null) {
        exDocumentoDTO.getDoc().setDestinatario(daoPes(exDocumentoDTO.getDestinatarioSel().getId()));
        exDocumentoDTO.getDoc()
                .setLotaDestinatario(daoPes(exDocumentoDTO.getDestinatarioSel().getId()).getLotacao());
        exDocumentoDTO.getDoc().setOrgaoExternoDestinatario(null);
    } else {
        exDocumentoDTO.getDoc().setDestinatario(null);
        if (exDocumentoDTO.getLotacaoDestinatarioSel().getId() != null) {
            exDocumentoDTO.getDoc()
                    .setLotaDestinatario(daoLot(exDocumentoDTO.getLotacaoDestinatarioSel().getId()));
            exDocumentoDTO.getDoc().setOrgaoExternoDestinatario(null);
        } else {
            exDocumentoDTO.getDoc().setLotaDestinatario(null);

            if (exDocumentoDTO.getOrgaoExternoDestinatarioSel().getId() != null) {
                exDocumentoDTO.getDoc().setOrgaoExternoDestinatario(dao().consultar(
                        exDocumentoDTO.getOrgaoExternoDestinatarioSel().getId(), CpOrgao.class, false));

            } else {
                exDocumentoDTO.getDoc().setOrgaoExternoDestinatario(null);
            }
        }
    }

    final SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    try {
        exDocumentoDTO.getDoc().setDtDoc(df.parse(exDocumentoDTO.getDtDocString()));
    } catch (final ParseException e) {
        exDocumentoDTO.getDoc().setDtDoc(null);
    } catch (final NullPointerException e) {
        exDocumentoDTO.getDoc().setDtDoc(null);
    }
    if (exDocumentoDTO.getDoc().getDtRegDoc() == null)
        exDocumentoDTO.getDoc().setDtRegDoc(dao().dt());

    try {
        exDocumentoDTO.getDoc().setDtDocOriginal(df.parse(exDocumentoDTO.getDtDocOriginalString()));
    } catch (final ParseException e) {
        exDocumentoDTO.getDoc().setDtDocOriginal(null);
    } catch (final NullPointerException e) {
        exDocumentoDTO.getDoc().setDtDocOriginal(null);
    }

    if (exDocumentoDTO.getNumExpediente() != null) {
        exDocumentoDTO.getDoc().setNumExpediente(new Long(exDocumentoDTO.getNumExpediente()));
        exDocumentoDTO.getDoc().setAnoEmissao(new Long(exDocumentoDTO.getAnoEmissaoString()));
    }

    if (exDocumentoDTO.getMobilPaiSel().getId() != null) {
        exDocumentoDTO.getDoc()
                .setExMobilPai(dao().consultar(exDocumentoDTO.getMobilPaiSel().getId(), ExMobil.class, false));
    } else {
        exDocumentoDTO.getDoc().setExMobilPai(null);
    }

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final String marcacoes[] = { "<!-- INICIO NUMERO -->", "<!-- FIM NUMERO -->", "<!-- INICIO NUMERO",
            "FIM NUMERO -->", "<!-- INICIO TITULO", "FIM TITULO -->", "<!-- INICIO MIOLO -->",
            "<!-- FIM MIOLO -->", "<!-- INICIO CORPO -->", "<!-- FIM CORPO -->", "<!-- INICIO CORPO",
            "FIM CORPO -->", "<!-- INICIO ASSINATURA -->", "<!-- FIM ASSINATURA -->",
            "<!-- INICIO ABERTURA -->", "<!-- FIM ABERTURA -->", "<!-- INICIO ABERTURA", "FIM ABERTURA -->",
            "<!-- INICIO FECHO -->", "<!-- FIM FECHO -->" };

    final String as[] = vars;
    if (as != null) {
        for (final String s : as) {
            if (baos.size() > 0)
                baos.write('&');
            baos.write(s.getBytes());
            baos.write('=');
            if (param(s) != null) {
                String parametro = param(s);
                for (final String m : marcacoes) {
                    if (parametro.contains(m))
                        parametro = parametro.replaceAll(m, "");
                }
                if (!FuncoesEL.contemTagHTML(parametro)) {
                    if (parametro.contains("\"")) {
                        parametro = parametro.replace("\"", "&quot;");
                        setParam(s, parametro);
                    }
                }

                baos.write(URLEncoder.encode(parametro, "iso-8859-1").getBytes());
            }
        }
        exDocumentoDTO.getDoc().setConteudoTpDoc("application/zip");
        exDocumentoDTO.getDoc().setConteudoBlobForm(baos.toByteArray());
    }
}

From source file:org.apache.poi.hpsf.Section.java

/**
 * Writes this section into an output stream.<p>
 *
 * Internally this is done by writing into three byte array output
 * streams: one for the properties, one for the property list and one for
 * the section as such. The two former are appended to the latter when they
 * have received all their data.//w  w w.j  a va  2s . co m
 *
 * @param out The stream to write into.
 *
 * @return The number of bytes written, i.e. the section's size.
 * @exception IOException if an I/O error occurs
 * @exception WritingNotSupportedException if HPSF does not yet support
 * writing a property's variant type.
 */
public int write(final OutputStream out) throws WritingNotSupportedException, IOException {
    /* Check whether we have already generated the bytes making out the
     * section. */
    if (sectionBytes.size() > 0) {
        sectionBytes.writeTo(out);
        return sectionBytes.size();
    }

    /* Writing the section's dictionary it tricky. If there is a dictionary
     * (property 0) the codepage property (property 1) must be set, too. */
    int codepage = getCodepage();
    if (codepage == -1) {
        String msg = "The codepage property is not set although a dictionary is present. "
                + "Defaulting to ISO-8859-1.";
        LOG.log(POILogger.WARN, msg);
        codepage = Property.DEFAULT_CODEPAGE;
    }

    /* The properties are written to this stream. */
    final ByteArrayOutputStream propertyStream = new ByteArrayOutputStream();

    /* The property list is established here. After each property that has
     * been written to "propertyStream", a property list entry is written to
     * "propertyListStream". */
    final ByteArrayOutputStream propertyListStream = new ByteArrayOutputStream();

    /* Maintain the current position in the list. */
    int position = 0;

    /* Increase the position variable by the size of the property list so
     * that it points behind the property list and to the beginning of the
     * properties themselves. */
    position += 2 * LittleEndianConsts.INT_SIZE + getPropertyCount() * 2 * LittleEndianConsts.INT_SIZE;

    /* Write the properties and the property list into their respective
     * streams: */
    for (Property p : properties.values()) {
        final long id = p.getID();

        /* Write the property list entry. */
        LittleEndian.putUInt(id, propertyListStream);
        LittleEndian.putUInt(position, propertyListStream);

        /* If the property ID is not equal 0 we write the property and all
         * is fine. However, if it equals 0 we have to write the section's
         * dictionary which has an implicit type only and an explicit
         * value. */
        if (id != 0) {
            /* Write the property and update the position to the next
             * property. */
            position += p.write(propertyStream, codepage);
        } else {
            if (codepage == -1) {
                throw new IllegalPropertySetDataException("Codepage (property 1) is undefined.");
            }
            position += writeDictionary(propertyStream, codepage);
        }
    }

    /* Write the section: */
    int streamLength = LittleEndianConsts.INT_SIZE * 2 + propertyListStream.size() + propertyStream.size();

    /* Write the section's length: */
    LittleEndian.putInt(streamLength, out);

    /* Write the section's number of properties: */
    LittleEndian.putInt(getPropertyCount(), out);

    /* Write the property list: */
    propertyListStream.writeTo(out);

    /* Write the properties: */
    propertyStream.writeTo(out);

    return streamLength;
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

private PseudonymWithMetadata getPseudonym(int pin, URI pseudonymUID, int nextPseuBlobUriId,
        ByteArrayOutputStream accumulatedPseuBytes, PseudonymSerializer serializer) {
    System.out.println("Accumulated this many bytes: " + accumulatedPseuBytes.size());
    URI nextPseuBlobUri = URI.create(pseudonymUID.toASCIIString() + "_" + nextPseuBlobUriId);
    System.out.println("getting this uri: " + nextPseuBlobUri.toASCIIString());
    SmartcardBlob scBlob = this.getBlob(pin, nextPseuBlobUri);
    if (scBlob == null) {
        return serializer.unserializePseudonym(accumulatedPseuBytes.toByteArray(), pseudonymUID);
    }/*from   ww w.  j a va 2 s .co m*/
    byte[] blob = scBlob.blob;
    accumulatedPseuBytes.write(blob, 0, blob.length);
    if (blob.length < MAX_BLOB_BYTES) {
        return serializer.unserializePseudonym(accumulatedPseuBytes.toByteArray(), pseudonymUID);
    } else {
        //next round
        return getPseudonym(pin, pseudonymUID, nextPseuBlobUriId + 1, accumulatedPseuBytes, serializer);
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

private Credential getCredential(int pin, URI credentialId, int nextCredBlobUriId,
        ByteArrayOutputStream accumulatedCredBytes, CredentialSerializer serializer) {
    System.out.println("Accumulated this many bytes: " + accumulatedCredBytes.size());
    URI nextCredBlobUri = URI.create(credentialId.toASCIIString() + "_" + nextCredBlobUriId);
    System.out.println("getting this uri: " + nextCredBlobUri.toASCIIString());
    SmartcardBlob scBlob = this.getBlob(pin, nextCredBlobUri);
    if (scBlob == null) {
        return serializer.unserializeCredential(accumulatedCredBytes.toByteArray(), credentialId,
                this.getDeviceURI(pin));
    }// w  ww. j  a  v a 2  s  . c  o  m
    byte[] blob = scBlob.blob;
    accumulatedCredBytes.write(blob, 0, blob.length);
    if (blob.length < MAX_BLOB_BYTES) {
        //return new CredentialSerializerGzipXml().unserializeCredential(accumulatedCredBytes.toByteArray());
        return serializer.unserializeCredential(accumulatedCredBytes.toByteArray(), credentialId,
                this.getDeviceURI(pin));
    } else {
        //next round
        return getCredential(pin, credentialId, nextCredBlobUriId + 1, accumulatedCredBytes, serializer);
    }
}

From source file:org.apache.jackrabbit.oak.spi.blob.AbstractBlobStore.java

private void convertBlobToId(InputStream in, ByteArrayOutputStream idStream, int level, long totalLength)
        throws IOException {
    int count = 0;
    // try to re-use the block (but not concurrently)
    byte[] block = blockBuffer.getAndSet(null);
    if (block == null || block.length != blockSize) {
        // not yet initialized yet, already in use, or wrong size:
        // create a new one
        block = new byte[blockSize];
    }/*from   ww  w  .  j  a v  a2 s . c om*/
    while (true) {
        int blockLen = IOUtils.readFully(in, block, 0, block.length);
        count++;
        if (blockLen == 0) {
            break;
        } else if (blockLen < blockSizeMin) {
            idStream.write(TYPE_DATA);
            IOUtils.writeVarInt(idStream, blockLen);
            idStream.write(block, 0, blockLen);
            totalLength += blockLen;
        } else {
            MessageDigest messageDigest;
            try {
                messageDigest = MessageDigest.getInstance(HASH_ALGORITHM);
            } catch (NoSuchAlgorithmException e) {
                throw new IOException(e);
            }
            messageDigest.update(block, 0, blockLen);
            byte[] digest = messageDigest.digest();
            idStream.write(TYPE_HASH);
            IOUtils.writeVarInt(idStream, level);
            if (level > 0) {
                // level > 0: total size (size of all sub-blocks)
                // (see class level javadoc for details)                    
                IOUtils.writeVarLong(idStream, totalLength);
            }
            // level = 0: size (size of this block)
            // level > 0: size of the indirection block
            // (see class level javadoc for details)                
            IOUtils.writeVarLong(idStream, blockLen);
            totalLength += blockLen;
            IOUtils.writeVarInt(idStream, digest.length);
            idStream.write(digest);

            long start = System.nanoTime();
            storeBlock(digest, level, Arrays.copyOf(block, blockLen));
            statsCollector.uploaded(System.nanoTime() - start, TimeUnit.NANOSECONDS, blockLen);
        }
        if (idStream.size() > blockSize / 2) {
            // convert large ids to a block, but ensure it can be stored as
            // one block (otherwise the indirection no longer works)
            byte[] idBlock = idStream.toByteArray();
            idStream.reset();
            convertBlobToId(new ByteArrayInputStream(idBlock), idStream, level + 1, totalLength);
            count = 1;
        }
    }
    // re-use the block
    blockBuffer.set(block);
    if (count > 0 && idStream.size() > blockSizeMin) {
        // at the very end, convert large ids to a block,
        // because large block ids are not handy
        // (specially if they are used to read data in small chunks)
        byte[] idBlock = idStream.toByteArray();
        idStream.reset();
        convertBlobToId(new ByteArrayInputStream(idBlock), idStream, level + 1, totalLength);
    }
    in.close();
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java

private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[],
        Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException {

    try {//from w  w  w  .j  a  v  a2 s  .  c o m
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();

        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {

            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - "
                    + JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph = new Paragraph(serverName,
                    FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(),
                    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));

            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);

            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());

    }
}

From source file:PNGDecoder.java

/** main encoding method (stays blocked till encoding is finished).
 * @param image BufferedImage to encode/*from w w w. ja v a  2  s  .c  o  m*/
 * @throws IOException IOException
 */
public void encode(BufferedImage image) throws IOException {
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    final byte id[] = { -119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13 };
    write(id);
    crc.reset();
    write("IHDR".getBytes());
    write(width);
    write(height);
    byte head[] = null;
    switch (mode) {
    case BW_MODE:
        head = new byte[] { 1, 0, 0, 0, 0 };
        break;
    case GREYSCALE_MODE:
        head = new byte[] { 8, 0, 0, 0, 0 };
        break;
    case COLOR_MODE:
        head = new byte[] { 8, 2, 0, 0, 0 };
        break;
    }
    write(head);
    write((int) crc.getValue());
    ByteArrayOutputStream compressed = new ByteArrayOutputStream(65536);
    BufferedOutputStream bos = new BufferedOutputStream(new DeflaterOutputStream(compressed, new Deflater(9)));
    int pixel;
    int color;
    int colorset;
    switch (mode) {
    case BW_MODE:
        int rest = width % 8;
        int bytes = width / 8;
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < bytes; x++) {
                colorset = 0;
                for (int sh = 0; sh < 8; sh++) {
                    pixel = image.getRGB(x * 8 + sh, y);
                    color = ((pixel >> 16) & 0xff);
                    color += ((pixel >> 8) & 0xff);
                    color += (pixel & 0xff);
                    colorset <<= 1;
                    if (color >= 3 * 128)
                        colorset |= 1;
                }
                bos.write((byte) colorset);
            }
            if (rest > 0) {
                colorset = 0;
                for (int sh = 0; sh < width % 8; sh++) {
                    pixel = image.getRGB(bytes * 8 + sh, y);
                    color = ((pixel >> 16) & 0xff);
                    color += ((pixel >> 8) & 0xff);
                    color += (pixel & 0xff);
                    colorset <<= 1;
                    if (color >= 3 * 128)
                        colorset |= 1;
                }
                colorset <<= 8 - rest;
                bos.write((byte) colorset);
            }
        }
        break;
    case GREYSCALE_MODE:
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < width; x++) {
                pixel = image.getRGB(x, y);
                color = ((pixel >> 16) & 0xff);
                color += ((pixel >> 8) & 0xff);
                color += (pixel & 0xff);
                bos.write((byte) (color / 3));
            }
        }
        break;
    case COLOR_MODE:
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < width; x++) {
                pixel = image.getRGB(x, y);
                bos.write((byte) ((pixel >> 16) & 0xff));
                bos.write((byte) ((pixel >> 8) & 0xff));
                bos.write((byte) (pixel & 0xff));
            }
        }
        break;
    }
    bos.close();
    write(compressed.size());
    crc.reset();
    write("IDAT".getBytes());
    write(compressed.toByteArray());
    write((int) crc.getValue());
    write(0);
    crc.reset();
    write("IEND".getBytes());
    write((int) crc.getValue());
    out.close();
}

From source file:org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
 * Retransmit Document page to be retransmitted, then display the PDF to the browser.
 *
 * @param mapping  An ActionMapping/*from  w  w  w  .j  a  va2  s .  c o  m*/
 * @param form     An ActionForm
 * @param request  The HttpServletRequest
 * @param response The HttpServletResponse
 * @return An ActionForward
 * @throws Exception
 */
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String selectedItemIndexes = request.getParameter("selectedItemIndexes");
    String documentNumber = request.getParameter("poDocumentNumberForRetransmit");
    PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class)
            .getPurchaseOrderByDocumentNumber(documentNumber);
    String retransmitHeader = request.getParameter("retransmitHeader");

    // setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
    // the po from the form

    setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
    po.setRetransmitHeader(retransmitHeader);
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // below method will throw ValidationException if errors are found
        SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        sbContentDispValue.append("inline");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
        return mapping.findForward(OLEConstants.MAPPING_ERROR);
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:com.eviware.soapui.impl.support.AbstractMockResponse.java

public String writeResponse(MockResult result, String responseContent) throws Exception {
    MimeMultipart mp = null;/* w  w  w. j ava  2s.co  m*/

    Operation operation = getMockOperation().getOperation();

    // variables needed for both multipart sections....
    boolean isXOP = isMtomEnabled() && isForceMtom();
    StringToStringMap contentIds = new StringToStringMap();

    // only support multipart for wsdl currently.....
    if (operation instanceof WsdlOperation) {
        if (operation == null) {
            throw new IllegalStateException("Missing WsdlOperation for mock response");
        }

        // preprocess only if neccessary
        if (isMtomEnabled() || isInlineFilesEnabled() || getAttachmentCount() > 0) {
            try {
                mp = new MimeMultipart();

                WsdlOperation wsdlOperation = ((WsdlOperation) operation);
                MessageXmlObject requestXmlObject = createMessageXmlObject(responseContent, wsdlOperation);
                MessageXmlPart[] requestParts = requestXmlObject.getMessageParts();
                for (MessageXmlPart requestPart : requestParts) {
                    if (prepareMessagePart(mp, contentIds, requestPart)) {
                        isXOP = true;
                    }
                }
                responseContent = requestXmlObject.getMessageContent();
            } catch (Exception e) {
                SoapUI.logError(e);
            }
        }

        responseContent = removeEmptyContent(responseContent);
    }

    if (isStripWhitespaces()) {
        responseContent = XmlUtils.stripWhitespaces(responseContent);
    }

    MockRequest request = result.getMockRequest();
    request.getHttpResponse().setStatus(this.getResponseHttpStatus());

    ByteArrayOutputStream outData = new ByteArrayOutputStream();

    // non-multipart request?
    String responseCompression = getResponseCompression();
    if (!isXOP && (mp == null || mp.getCount() == 0) && getAttachmentCount() == 0) {
        String encoding = getEncoding();
        if (responseContent == null) {
            responseContent = "";
        }

        byte[] content = encoding == null ? responseContent.getBytes() : responseContent.getBytes(encoding);

        if (!result.getResponseHeaders().containsKeyIgnoreCase("Content-Type")) {
            result.setContentType(getContentType());
        }

        String acceptEncoding = result.getMockRequest().getRequestHeaders().get("Accept-Encoding", "");
        if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("GZIP")) {
            if (!headerExists("Content-Encoding", "gzip", result)) {
                result.addHeader("Content-Encoding", "gzip");
            }
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_GZIP, content));
        } else if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("DEFLATE")) {
            result.addHeader("Content-Encoding", "deflate");
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_DEFLATE, content));
        } else {
            outData.write(content);
        }
    } else // won't get here if rest at the moment...
    {
        // make sure..
        if (mp == null) {
            mp = new MimeMultipart();
        }

        // init root part
        initRootPart(responseContent, mp, isXOP);

        // init mimeparts
        AttachmentUtils.addMimeParts(this, Arrays.asList(getAttachments()), mp, contentIds);

        // create request message
        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(mp);
        message.saveChanges();
        MimeMessageMockResponseEntity mimeMessageRequestEntity = new MimeMessageMockResponseEntity(message,
                isXOP, this);

        result.addHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        result.addHeader("MIME-Version", "1.0");
        mimeMessageRequestEntity.writeTo(outData);
    }

    if (outData.size() > 0) {
        byte[] data = outData.toByteArray();

        if (responseCompression.equals(CompressionSupport.ALG_DEFLATE)
                || responseCompression.equals(CompressionSupport.ALG_GZIP)) {
            result.addHeader("Content-Encoding", responseCompression);
            data = CompressionSupport.compress(responseCompression, data);
        }
        if (result.getResponseHeaders().get("Transfer-Encoding") == null) {
            result.addHeader("Content-Length", "" + data.length);
        }
        result.writeRawResponseData(data);
    }

    return responseContent;
}