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:gov.utah.dts.det.ccl.actions.facility.information.license.LicensesPrintAction.java

@Action(value = "print-license-cert")
public void doPrintCertificate() {
    loadLicense();/* ww  w.  ja va  2  s  .co 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.myriad.state.utils.ByteBufferSupportTest.java

@Test
public void testNullAddByteBuffer() throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    ByteBufferSupport.addByteBuffer(null, stream);
    assertEquals(0, stream.size());
}

From source file:org.apache.myriad.state.utils.ByteBufferSupportTest.java

@Test
public void testNonEmptyAddByteBuffer() throws Exception {
    ByteBuffer bb = getByteBuffer(BYTE_ARRAY);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    ByteBufferSupport.addByteBuffer(bb, stream);
    assertEquals(20, stream.size());
    ByteBufferSupport.addByteBuffer(bb, stream);
    assertEquals(40, stream.size());//from ww  w. j av  a 2  s.  c om
}

From source file:io.github.qwefgh90.akka.pdf.PDFUtilWrapper.java

public static InputStream merge(final List<InputStream> sources, String _title, String _creator,
        String _subject) throws IOException {
    String title = _title == null ? "" : _title;
    String creator = _creator == null ? "" : _creator;
    String subject = _subject == null ? "" : _subject;

    ByteArrayOutputStream mergedPDFOutputStream = null;
    COSStream cosStream = null;/*from ww w .j a v  a 2s.c  om*/
    try {
        // If you're merging in a servlet, you can modify this example to use the outputStream only
        // as the response as shown here: http://stackoverflow.com/a/36894346/535646
        mergedPDFOutputStream = new ByteArrayOutputStream();
        cosStream = new COSStream();

        PDFMergerUtility pdfMerger = createPDFMergerUtility(sources, mergedPDFOutputStream);

        // PDF and XMP properties must be identical, otherwise document is not PDF/A compliant
        PDDocumentInformation pdfDocumentInfo = createPDFDocumentInfo(title, creator, subject);
        PDMetadata xmpMetadata = createXMPMetadata(cosStream, title, creator, subject);
        pdfMerger.setDestinationDocumentInformation(pdfDocumentInfo);
        pdfMerger.setDestinationMetadata(xmpMetadata);

        LOG.info("Merging " + sources.size() + " source documents into one PDF");
        pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        LOG.info("PDF merge successful, size = {" + mergedPDFOutputStream.size() + "} bytes");

        return new ByteArrayInputStream(mergedPDFOutputStream.toByteArray());
    } catch (BadFieldValueException e) {
        throw new IOException("PDF merge problem", e);
    } catch (TransformerException e) {
        throw new IOException("PDF merge problem", e);
    } finally {
        for (InputStream source : sources) {
            IOUtils.closeQuietly(source);
        }
        IOUtils.closeQuietly(cosStream);
        IOUtils.closeQuietly(mergedPDFOutputStream);
    }
}

From source file:com.jayway.restassured.itest.java.FileDownloadITest.java

@Test
public void canDownloadLargeFiles() throws Exception {
    int expectedSize = IOUtils
            .toByteArray(getClass().getResourceAsStream("/powermock-easymock-junit-1.4.12.zip")).length;
    final InputStream inputStream = expect().log().headers().when()
            .get("http://powermock.googlecode.com/files/powermock-easymock-junit-1.4.12.zip").asInputStream();

    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, byteArrayOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);
    IOUtils.closeQuietly(inputStream);//w w w  . j  av  a 2 s  .com

    assertThat(byteArrayOutputStream.size(), equalTo(expectedSize));
}

From source file:com.jayway.restassured.itest.java.FileDownloadITest.java

@Test
public void canDownloadLargeFilesWhenLoggingIfValidationFailsIsEnabled() throws Exception {
    int expectedSize = IOUtils
            .toByteArray(getClass().getResourceAsStream("/powermock-easymock-junit-1.4.12.zip")).length;
    final InputStream inputStream = when()
            .get("http://powermock.googlecode.com/files/powermock-easymock-junit-1.4.12.zip").then().log()
            .ifValidationFails().extract().asInputStream();

    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, byteArrayOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);
    IOUtils.closeQuietly(inputStream);//w  w  w  .j a va 2  s  . c o  m

    assertThat(byteArrayOutputStream.size(), equalTo(expectedSize));
}

From source file:com.rogiel.httpchannel.service.impl.MegaUploadServiceTest.java

@Test
public void testFreeDownloader() throws IOException {
    final DownloadChannel channel = service.getDownloader(URI.create("http://www.megaupload.com/?d=CVQKJ1KM"))
            .openChannel(new DownloadListener() {
                @Override/*ww  w .j  a  v  a  2  s.  c  om*/
                public boolean timer(long time) {
                    System.out.println("Waiting " + time);
                    // if (reason == TimerWaitReason.DOWNLOAD_TIMER)
                    // return true;
                    return true;
                }
            }, 0);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(Channels.newInputStream(channel), bout);
    System.out.println(bout.size());
}

From source file:com.rogiel.httpchannel.service.impl.MegaUploadServiceTest.java

@Test
public void testPremiumDownloader() throws IOException {
    service.getAuthenticator(new Credential(VALID_USERNAME, VALID_PASSWORD)).login();

    final DownloadChannel channel = service.getDownloader(URI.create("http://www.megaupload.com/?d=CVQKJ1KM"))
            .openChannel(new DownloadListener() {
                @Override// ww w.j a va  2s  .  c om
                public boolean timer(long time) {
                    System.out.println("Waiting " + time);
                    return true;
                }
            }, 0);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(Channels.newInputStream(channel), bout);
    System.out.println(bout.size());
}

From source file:eu.scape_project.fcrepo.integration.ReferencedContentIntellectualEntitiesIT.java

@Test
public void testIngestIntellectualEntitiesAsyncWithSameIDs() throws Exception {
    List<String> entityIds = new ArrayList(Arrays.asList("ref-async-6", "ref-async-6"));
    List<String> queueId = new ArrayList<>();
    int count = 0;
    for (String id : entityIds) {
        IntellectualEntity ie = TestUtil.createTestEntityWithMultipleRepresentations(id);
        HttpPost post = new HttpPost(SCAPE_URL + "/entity-async");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(ie, sink);
        post.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size()));
        HttpResponse resp = this.client.execute(post);
        if (count++ == 0) {
            assertEquals(200, resp.getStatusLine().getStatusCode());
        } else {/*w w w  . j  a  v a 2 s  .  co  m*/
            assertEquals(500, resp.getStatusLine().getStatusCode());
        }
        post.releaseConnection();
    }

}

From source file:grails.plugin.eas.SendMailEntity.java

/**
 * We always return -1 because we don't know the actual length of the POST data (this
 * causes HttpClient to send the data in "chunked" mode)
 *///from  www  .j  a v a  2s  .  co  m
@Override
public long getContentLength() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        // Calculate the overhead for the WBXML data
        writeTo(baos, false);
        // Return the actual size that will be sent
        return baos.size() + mimeLength;
    } catch (IOException e) {
        // Just return -1 (unknown)
    } finally {
        try {
            baos.close();
        } catch (IOException e) {
            // Ignore
        }
    }
    return -1;
}