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:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java

public final void testPurchaseOrderPrint() throws Exception {
    PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS
            .createPurchaseOrderDocument();
    po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN);
    po.refreshNonUpdateableReferences();
    po.prepareForSave();/*from ww  w  . j av  a2 s  .c o  m*/
    AccountingDocumentTestUtils.saveDocument(po, docService);
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        poService.performPrintPurchaseOrderPDFOnly(po.getDocumentNumber(), baosPDF);
        assertTrue(baosPDF.size() > 0);
    } catch (ValidationException e) {
        fail("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber()
                + "\n" + dumpMessageMapErrors());
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }
}

From source file:com.haulmont.cuba.core.sys.LogControlImpl.java

protected String readUtf8Line(RandomAccessFile logFile) throws IOException {
    int c = -1;//w  ww. j a va2s  .  com
    boolean eol = false;
    ByteArrayOutputStream input = new ByteArrayOutputStream();

    while (!eol) {
        switch (c = logFile.read()) {
        case -1:
        case '\n':
            eol = true;
            break;
        case '\r':
            eol = true;
            long cur = logFile.getFilePointer();
            if ((logFile.read()) != '\n') {
                logFile.seek(cur);
            }
            break;
        default:
            input.write((byte) c);
            break;
        }
    }
    if ((c == -1) && (input.size() == 0)) {
        return null;
    }

    return new String(input.toByteArray(), StandardCharsets.UTF_8);
}

From source file:org.apache.geode.cache.lucene.internal.filesystem.FileSystemJUnitTest.java

/**
 * A test that skip can jump to the correct position in the stream
 *//*  w w  w  . j a  v  a 2  s .  com*/
@Test
public void testSeek() throws Exception {
    File file = system.createFile("testFile1");

    ByteArrayOutputStream expected = new ByteArrayOutputStream();
    byte[] data = new byte[SMALL_CHUNK];

    // Write multiple times to the file with a lot of small chunks
    while (expected.size() < FileSystem.CHUNK_SIZE + 1) {
        rand.nextBytes(data);

        expected.write(data);
        writeBytes(file, data);
    }

    byte[] expectedBytes = expected.toByteArray();
    assertContents(expectedBytes, file);

    // Assert that there are only 2 chunks in the system, since we wrote just
    // past the end of the first chunk.
    assertEquals(2, chunkRegion.size());

    SeekableInputStream in = file.getInputStream();

    // Seek to several positions in the first chunk
    checkByte(5, in, expectedBytes);
    checkByte(50, in, expectedBytes);
    checkByte(103, in, expectedBytes);
    checkByte(1, in, expectedBytes);

    // Seek back and forth between chunks
    checkByte(FileSystem.CHUNK_SIZE + 2, in, expectedBytes);
    checkByte(23, in, expectedBytes);
    checkByte(FileSystem.CHUNK_SIZE + 10, in, expectedBytes);
    checkByte(1023, in, expectedBytes);

    // Read the remaining data after a seek

    in.seek(10);
    byte[] results = new byte[expectedBytes.length];

    // Fill in the initial 10 bytes with the expected value
    System.arraycopy(expectedBytes, 0, results, 0, 10);

    assertEquals(results.length - 10, in.read(results, 10, results.length - 10));
    assertEquals(-1, in.read());

    assertArrayEquals(expectedBytes, results);
}

From source file:org.kie.guvnor.dtablexls.backend.server.FileServlet.java

protected void processAttachmentDownload(String path, HttpServletResponse response) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try {//from   w  ww  . j  a  va 2s  .co m
        org.kie.commons.java.nio.file.Path targetPathNio = ioService.get(new URI(path));
        org.uberfire.backend.vfs.Path targetPath = paths.convert(targetPathNio, false);
        IOUtils.copy(decisionTableXLSService.load(targetPath), output);
        // String fileName = m2RepoService.getJarName(path);
        String fileName = targetPath.getFileName();

        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
        response.setContentLength(output.size());
        response.getOutputStream().write(output.toByteArray());
        response.getOutputStream().flush();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.marklogic.contentpump.CompressedDocumentReader.java

protected void setValue(long length) throws IOException {
    ByteArrayOutputStream baos;
    if (length > 0) {
        baos = new ByteArrayOutputStream((int) length);
    } else {/*from   w ww  .ja  v a2 s  .  c  o  m*/
        baos = new ByteArrayOutputStream();
    }

    int size;
    while ((size = zipIn.read(buf, 0, buf.length)) != -1) {
        baos.write(buf, 0, size);
    }
    if (value instanceof Text) {
        ((Text) value).set(baos.toString(encoding));
    } else {
        if (batchSize > 1) {
            // Copy data since XCC won't do it when Content is created.
            value = (VALUEIN) new BytesWritable();
        }
        ((BytesWritable) value).set(baos.toByteArray(), 0, baos.size());
    }
    baos.close();
}

From source file:com.gemstone.gemfire.cache.lucene.internal.filesystem.FileSystemJUnitTest.java

/**
 * A test that skip can jump to the correct position in the stream
 *//*w w w .j  av  a 2 s . c o  m*/
@Test
public void testSeek() throws Exception {
    File file = system.createFile("testFile1");

    ByteArrayOutputStream expected = new ByteArrayOutputStream();
    byte[] data = new byte[SMALL_CHUNK];

    //Write multiple times to the file with a lot of small chunks
    while (expected.size() < FileSystem.CHUNK_SIZE + 1) {
        rand.nextBytes(data);

        expected.write(data);
        writeBytes(file, data);
    }

    byte[] expectedBytes = expected.toByteArray();
    assertContents(expectedBytes, file);

    //Assert that there are only 2 chunks in the system, since we wrote just
    //past the end of the first chunk.
    assertEquals(2, chunkRegion.size());

    SeekableInputStream in = file.getInputStream();

    //Seek to several positions in the first chunk
    checkByte(5, in, expectedBytes);
    checkByte(50, in, expectedBytes);
    checkByte(103, in, expectedBytes);
    checkByte(1, in, expectedBytes);

    //Seek back and forth between chunks
    checkByte(FileSystem.CHUNK_SIZE + 2, in, expectedBytes);
    checkByte(23, in, expectedBytes);
    checkByte(FileSystem.CHUNK_SIZE + 10, in, expectedBytes);
    checkByte(1023, in, expectedBytes);

    //Read the remaining data after a seek

    in.seek(10);
    byte[] results = new byte[expectedBytes.length];

    //Fill in the initial 10 bytes with the expected value
    System.arraycopy(expectedBytes, 0, results, 0, 10);

    assertEquals(results.length - 10, in.read(results, 10, results.length - 10));
    assertEquals(-1, in.read());

    assertArrayEquals(expectedBytes, results);
}

From source file:fi.jumi.test.JumiBootstrapTest.java

@Test
public void will_not_close_stderr_when_debug_output_is_enabled() throws Exception {
    PrintStream originalErr = System.err;
    try {/*from   w w w.  j a v a 2  s.co  m*/
        ByteArrayOutputStream printed = new ByteArrayOutputStream();
        PrintStream spiedErr = spy(new PrintStream(printed));
        System.setErr(spiedErr);

        JumiBootstrap bootstrap = new JumiBootstrap();
        bootstrap.suite.setTestClasses(OnePassingTest.class);
        bootstrap.daemon.setIdleTimeout(0); // we want the daemon process to exit quickly
        bootstrap.setTextUiOutput(new NullWriter());
        bootstrap.enableDebugMode(); // <-- the thing we are testing
        bootstrap.runSuite();

        Thread.sleep(50); // wait for the daemon process to exit, and our printer thread to notice it
        assertThat("this test has a problem; daemon printed nothing", printed.size(), is(not(0)));
        verify(spiedErr, never()).close(); // <-- the thing we are testing

    } finally {
        System.setErr(originalErr);
    }
}

From source file:com.centurylink.mdw.util.HttpHelper.java

/**
 * Populates the response member.  Closes the connection.
 *///www.jav  a 2 s .c om
private void readInput(HttpURLConnection connection) throws IOException {
    InputStream is = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[2048];
        try {
            is = connection.getInputStream();
            while (maxBytes == -1 || baos.size() < maxBytes) {
                int bytesRead = is.read(buffer);
                if (bytesRead == -1)
                    break;
                baos.write(buffer, 0, bytesRead);
            }
            response = baos.toByteArray();
            if (followHtmlHeadMetaRefresh && getResponse().indexOf("http-equiv") > 0) {
                try {
                    redirect = parseResponseForHtmlMetaEquiv(getResponse());
                    if (redirect != null)
                        response = new HttpHelper(this, redirect).getBytes();
                } catch (Exception ex) {
                    throw new IllegalArgumentException("Unparseable response: " + ex.getMessage(), ex);
                }

            }
        } catch (IOException ex) {
            InputStream eis = null;
            try {
                eis = connection.getErrorStream();
                while (maxBytes == -1 || baos.size() < maxBytes) {
                    int bytesRead = eis.read(buffer);
                    if (bytesRead == -1)
                        break;
                    baos.write(buffer, 0, bytesRead);
                }
                response = baos.toByteArray();
            } catch (Exception ex2) {
                // throw original exception
            } finally {
                if (eis != null) {
                    eis.close();
                }
            }
            throw ex;
        }
    } finally {
        if (is != null)
            is.close();
        connection.disconnect();
        responseCode = connection.getResponseCode();
        responseMessage = connection.getResponseMessage();
        headers = new HashMap<String, String>();
        for (String headerKey : connection.getHeaderFields().keySet()) {
            if (headerKey == null)
                headers.put("HTTP", connection.getHeaderField(headerKey));
            else
                headers.put(headerKey, connection.getHeaderField(headerKey));
        }
    }
}

From source file:com.celements.photo.plugin.CelementsPhotoPlugin.java

/**
 * Get a specified image file in a zip archive, extract it, change it to the 
 * desired size and save it as an attachment to the given page.
 * //w ww  .j  a v a2s.c o m
 * @param zipFile File containing the image to extract.
 * @param unzipFileName Filename of the image to extract.
 * @param attachToDoc Document to attach the extracted and resized image.
 * @param width Width (max - aspect ratio is maintained) to resize the image to.
 * @param height Height (max - aspect ratio is maintained) to resize the image to.
 * @param context XWikiContezt
 * @throws XWikiException
 */
public void unzipFileToAttachment(XWikiAttachment zipFile, String unzipFileName, XWikiDocument attachToDoc,
        int width, int height, XWikiContext context) throws XWikiException {
    LOGGER.info("START: zip='" + zipFile.getFilename() + "' file='" + unzipFileName + "' gallery='"
            + attachToDoc + "' " + "width='" + width + "' height='" + height + "'");
    try {
        ByteArrayInputStream imgFullSize = null;
        if (isZipFile(zipFile, context)) {
            imgFullSize = new ByteArrayInputStream(
                    (new Unzip()).getFile(zipFile.getContent(context), unzipFileName).toByteArray());
        } else if (isImgFile(zipFile, context)) {
            imgFullSize = new ByteArrayInputStream(zipFile.getContent(context));
        }
        //TODO is there a better way to find the mime type of the file in the in stream?
        //      -> look at http://tika.apache.org/ or maybe in image magic?
        String mimeType = "png";
        if ((unzipFileName.lastIndexOf('.') > -1) && (!unzipFileName.endsWith("."))) {
            mimeType = unzipFileName.substring(unzipFileName.lastIndexOf('.') + 1);
        }
        LOGGER.debug("unzip mimetype is " + mimeType);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageDimensions id = (new GenerateThumbnail()).createThumbnail(imgFullSize, out, width, height, null,
                null, mimeType, null);
        LOGGER.info("width='" + id.width + "' height='" + id.height + "'");
        LOGGER.info("output stream size: " + out.size());
        unzipFileName = unzipFileName.replace(System.getProperty("file.separator"), ".");
        unzipFileName = context.getWiki().clearName(unzipFileName, false, true, context);
        XWikiAttachment att = (new AddAttachmentToDoc()).addAtachment(attachToDoc, out.toByteArray(),
                unzipFileName, context);
        LOGGER.info("attachment='" + att.getFilename() + "', gallery='" + att.getDoc().getFullName()
                + "' size='" + att.getFilesize() + "'");
    } catch (IOException e) {
        LOGGER.error(e);
    }
    LOGGER.info("END file='" + unzipFileName + "'");
}

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

@Test
public void testIngestAsyncAndRetrieveLifeCycle() throws Exception {
    IntellectualEntity ie = TestUtil.createTestEntityWithMultipleRepresentations("entity-10");
    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);
    assertEquals(200, resp.getStatusLine().getStatusCode());
    String id = EntityUtils.toString(resp.getEntity());
    assertTrue(id.length() > 0);/*  ww  w.j  a va 2s  .  c  om*/

    /* check the lifecycle state and wait for the entity to be ingested */
    LifecycleState state;
    long start = System.currentTimeMillis();
    do {
        HttpGet get = new HttpGet(SCAPE_URL + "/lifecycle/" + id);
        resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        state = (LifecycleState) this.marshaller.deserialize(resp.getEntity().getContent());
        get.releaseConnection();
    } while (!state.getState().equals(State.INGESTED) && (System.currentTimeMillis() - start) < 60000);
    assertEquals(State.INGESTED, state.getState());
}