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.thoughtworks.go.server.websocket.ConsoleLogSender.java

private void flushBuffer(ByteArrayOutputStream buffer, SocketEndpoint webSocket) throws IOException {
    if (buffer.size() == 0)
        return;/*from  w  ww .  ja  va  2 s  .c om*/
    webSocket.send(ByteBuffer.wrap(maybeGzipIfLargeEnough(buffer.toByteArray())));
    buffer.reset();
}

From source file:com.joyent.manta.client.crypto.EncryptingPartEntity.java

@Override
public void writeTo(final OutputStream httpOut) throws IOException {
    Validate.notNull(httpOut, "HttpOut stream must not be null");
    Validate.notNull(multipartStream, "MultipartStream must not be null");

    multipartStream.setNext(httpOut);/*w  w  w.j  a v  a2  s. c  o  m*/

    final InputStream contentStream = getContent();
    Validate.notNull(contentStream, "Content input stream must not be null");
    Validate.notNull(cipherStream, "Cipher output stream must not be null");
    final CountingOutputStream cout = new CountingOutputStream(cipherStream);

    try {
        IOUtils.copy(contentStream, cout, BUFFER_SIZE);
        cipherStream.flush();
        if (lastPartCallback != null) {
            ByteArrayOutputStream remainderStream = lastPartCallback.call(cout.getByteCount());
            if (remainderStream.size() > 0) {
                IOUtils.copy(new ByteArrayInputStream(remainderStream.toByteArray()), httpOut, BUFFER_SIZE);
            }
        }
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
}

From source file:org.bimserver.test.framework.actions.CheckoutAction.java

@Override
public void execute(VirtualUser virtualUser) throws Exception {
    SProject project = virtualUser.getRandomProject();
    if (project.getLastRevisionId() != -1) {
        List<SSerializerPluginConfiguration> allSerializers = virtualUser.getBimServerClient()
                .getPluginInterface().getAllSerializers(true);
        SSerializerPluginConfiguration serializer = allSerializers.get(nextInt(allSerializers.size()));
        boolean sync = nextBoolean();
        virtualUser.getActionResults()/*from w  w  w .  ja  va2 s  .  co  m*/
                .setText("Checking out revision " + project.getLastRevisionId() + " of project "
                        + project.getName() + " with serializer " + serializer.getName() + " sync: " + sync);
        long topicId = virtualUser.getBimServerClient().getBimsie1ServiceInterface()
                .checkout(project.getLastRevisionId(), serializer.getOid(), sync);
        SLongActionState downloadState = virtualUser.getBimServerClient().getRegistry().getProgress(topicId);
        while (downloadState.getState() != SActionState.FINISHED) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            downloadState = virtualUser.getBimServerClient().getRegistry().getProgress(topicId);
        }
        virtualUser.getLogger().info("Done preparing checkout, downloading");
        SDownloadResult downloadData = virtualUser.getBimServerClient().getBimsie1ServiceInterface()
                .getDownloadData(topicId);
        if (downloadData != null) {
            try {
                ByteArrayOutputStream data = new ByteArrayOutputStream();
                IOUtils.copy(downloadData.getFile().getInputStream(), data);
                virtualUser.getLogger().info(data.size() + " bytes downloaded");
            } catch (IOException e) {
                virtualUser.getLogger().error("", e);
            }
        } else {
            virtualUser.getLogger().warn("No download results...");
        }
    }
}

From source file:org.dataconservancy.dcs.lineage.http.view.BaseStreamingView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (entities == null) {
        throw new IllegalStateException("Entities must be set first: call setEntities(List<DcsEntity>)");
    }/*from   w w  w.  j  a  v  a  2  s . co m*/

    // Serialize the entities to a temporary byte array
    List<DcsEntity> entities = (List<DcsEntity>) model.get(ENTITIES.name());
    ByteArrayOutputStream tempOut = new ByteArrayOutputStream(1024 * 4);
    serializeEntities(entities, tempOut);

    setResponseHeaders(model, response, tempOut.size());

    if (request.getMethod().equalsIgnoreCase("HEAD")) {
        streamResponse(response, new byte[] {});
    } else if (request.getMethod().equalsIgnoreCase("GET")) {
        streamResponse(response, tempOut.toByteArray());
    } else {
        // catch-all, should never be invoked because this should be dealt with in the Controller.
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                request.getMethod() + " requests not allowed.");
    }
}

From source file:org.piraso.server.spring.remoting.HttpInvokerRequestExecutorWrapper.java

public RemoteInvocationResult executeRequest(HttpInvokerClientConfiguration config, RemoteInvocation invocation)
        throws Exception {
    if (helper != null && pirasoContext.isMonitored()) {
        try {/*  w w  w  .  jav a2s  . c o m*/
            ByteArrayOutputStream baos = helper.getByteArrayOutputStream(invocation);

            HttpURLConnection con = helper.openConnection(config);
            helper.prepareConnection(con, baos.size());
            con.setRequestProperty(REMOTE_ADDRESS_HEADER, pirasoContext.getEntryPoint().getRemoteAddr());
            con.setRequestProperty(REQUEST_ID_HEADER, String.valueOf(pirasoContext.getRequestId()));

            String groupId = getGroupId();
            if (groupId != null) {
                con.setRequestProperty(GROUP_ID_HEADER, groupId);
            }

            helper.writeRequestBody(config, con, baos);
            helper.validateResponse(config, con);
            InputStream responseBody = helper.readResponseBody(config, con);

            return helper.readRemoteInvocationResult(responseBody, config.getCodebaseUrl());
        } catch (HttpInvokerReflectionException e) {
            LOG.warn("Error on propagating piraso context. Will revert to direct delegation.", e);
        }
    }

    return delegate.executeRequest(config, invocation);
}

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

@Test
public void testDownloader() throws IOException {
    final URI downloadUrl = URI
            .create("http://hotfile.com/dl/129251605/9b4faf2/simulado_2010_1_res_all.zip.htm");

    final DownloadService<?> service = Services.matchURI(downloadUrl);

    final DownloadChannel channel = service.getDownloader(downloadUrl).openChannel(null, 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.HotFileServiceTest.java

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

    final DownloadChannel channel = service
            .getDownloader(//from   www .j  a  v a 2s .c o  m
                    URI.create("http://hotfile.com/dl/129251605/9b4faf2/simulado_2010_1_res_all.zip.html"))
            .openChannel(null, 0);

    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(Channels.newInputStream(channel), bout);
    System.out.println(bout.size());
}

From source file:com.webcohesion.ofx4j.client.net.OFXV1Connection.java

/**
 * Log a request buffer.// w w  w .  j  a va  2s . c o m
 *
 * @param outBuffer The buffer to log.
 */
protected void logRequest(ByteArrayOutputStream outBuffer) throws UnsupportedEncodingException {
    if (LOG.isInfoEnabled()) {
        LOG.info("Marshalling " + outBuffer.size() + " bytes of the OFX request.");
        if (LOG.isDebugEnabled()) {
            LOG.debug(outBuffer.toString("utf-8"));
        }
    }
}

From source file:org.jcodec.containers.mp4.boxes.Box.java

public long calcSize() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*from  w w w .  j  a v  a  2 s  .c om*/
        write(new DataOutputStream(baos));
    } catch (IOException e) {
    }
    return baos.size();
}

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

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

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

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

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

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