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:eu.scape_project.fcrepo.integration.ReferencedContentIntellectualEntitiesIT.java

@Test
public void testIngestIntellectualEntitiesAsync() throws Exception {
    List<String> entityIds = new ArrayList(
            Arrays.asList("ref-async-1", "ref-async-2", "ref-async-3", "ref-async-4", "ref-async-5"));
    List<String> queueId = new ArrayList<>();
    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);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        post.releaseConnection();/*from  w w w. ja va  2s . co  m*/
    }

    Iterator<String> ids = entityIds.iterator();
    while (ids.hasNext()) {
        String id = ids.next();
        HttpGet get = new HttpGet(SCAPE_URL + "/lifecycle/" + id);
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        get.releaseConnection();
        LifecycleState state = (LifecycleState) this.marshaller.deserialize(resp.getEntity().getContent());
        if (state.getState().equals(LifecycleState.State.INGESTED)) {
            //                System.out.println(id + " was ingested");
            ids.remove();
        } else if (state.getState().equals(LifecycleState.State.INGESTING)) {
            //                System.out.println(id + " is currently ingesting");
        } else {
            throw new Exception("this should not happen!");
        }
        if (!ids.hasNext()) {
            ids = entityIds.iterator();
        }
    }
}

From source file:org.apache.olingo.fit.KeyAsSegment.java

private Response replaceServiceName(final Response response) {
    try {/*  w  w w.j av  a  2 s. c  o m*/
        final String content = IOUtils.toString((InputStream) response.getEntity(), Constants.ENCODING)
                .replaceAll("Static\\.svc", "KeyAsSegment.svc");

        final Response.ResponseBuilder builder = Response.status(response.getStatus());
        for (String headerName : response.getHeaders().keySet()) {
            for (Object headerValue : response.getHeaders().get(headerName)) {
                builder.header(headerName, headerValue);
            }
        }

        final InputStream toBeStreamedBack = IOUtils.toInputStream(content, Constants.ENCODING);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(toBeStreamedBack, baos);
        IOUtils.closeQuietly(toBeStreamedBack);

        builder.header("Content-Length", baos.size());
        builder.entity(new ByteArrayInputStream(baos.toByteArray()));

        return builder.build();
    } catch (Exception e) {
        return response;
    }
}

From source file:com.google.dataconnector.client.fetchrequest.HttpFetchStrategy.java

/**
 * Implements the strategy method of processing the request and filling in the
 * reply with results of processing./*  w ww.j ava  2 s.co  m*/
 * 
 * @param request The request.
 * @param replyBuilder The reply to fill in.
 */
@Override
public void process(FetchRequest request, FetchReply.Builder replyBuilder) throws StrategyException {
    HttpResponse response = getHttpResponse(request);

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    replyBuilder.setStatus(statusCode);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            entity.writeTo(buff);
            buff.flush();
            buff.close();
            if (buff.size() > 0) {
                replyBuilder.setContents(ByteString.copyFrom(buff.toByteArray()));
            }
        } catch (IOException e) {
            throw new StrategyException(request.getId() + " while copying content:", e);
        }
    }
    // Copy the headers
    for (Header h : response.getAllHeaders()) {
        replyBuilder.addHeaders(MessageHeader.newBuilder().setKey(h.getName()).setValue(h.getValue()).build());
    }
    LOG.info(request.getId() + ": Got response from resource:" + statusLine);
}

From source file:cc.arduino.plugins.wifi101.flashers.java.NinaFlasher.java

@Override
public void uploadCertificates(String port, List<String> websites) throws Exception {
    FlasherSerialClient client = null;//from   w w w. j a v a2s.  c o  m
    try {
        file = openFirmwareFile();
        progress(10, "Connecting to programmer...");
        client = new FlasherSerialClient();
        client.open(port, this.baudrate);
        client.hello();
        int maxPayload = client.getMaximumPayload();
        int count = websites.size();
        String pem = "";

        for (String website : websites) {
            URL url;
            try {
                url = new URL(website);
            } catch (MalformedURLException e1) {
                url = new URL("https://" + website);
            }

            progress(30 + 20 * count / websites.size(), "Downloading certificate from " + website + "...");
            Certificate[] certificates = SSLCertDownloader.retrieveFromURL(url);

            // Pick the latest certificate (that should be the root cert)
            X509Certificate x509 = (X509Certificate) certificates[certificates.length - 1];
            pem = convertToPem(x509) + "\n" + pem;
        }

        byte[] pemArray = pem.getBytes();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        output.write(pemArray);
        while (output.size() % maxPayload != 0) {
            output.write(0);
        }
        byte[] fwData = output.toByteArray();

        int size = fwData.length;
        int address = 0x10000;
        int written = 0;

        if (size > 0x20000) {
            throw new Exception("Too many certificates!");
        }

        progress(20, "Erasing target...");

        client.eraseFlash(address, size);

        while (written < size) {
            progress(20 + written * 40 / size, "Programming " + size + " bytes ...");
            int len = maxPayload;
            if (written + len > size) {
                len = size - written;
            }
            client.writeFlash(address, Arrays.copyOfRange(fwData, written, written + len));
            written += len;
            address += len;
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:gov.nih.nci.cacis.transform.XMLToRdfTransformerTest.java

@Test
public void transformStream() throws XMLStreamException, TransformerException, URISyntaxException, IOException {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();

    final Map<String, String> params = new HashMap<String, String>();
    params.put("BaseURI", "http://yadda.com/someUUID");

    transform.transform(params, sampleMessageIS, os);
    assertNotNull(os);/*from  www.j a va 2s.com*/
    assertTrue(os.size() > 0);

    os.reset();
    transform.transform(params, sampleTrimIS, os);
    assertNotNull(os);
    assertTrue(os.size() > 0);
}

From source file:net.acesinc.convergentui.BaseFilter.java

protected void writeResponse(BufferedImage image, MediaType type) throws Exception {
    RequestContext context = RequestContext.getCurrentContext();
    // there is no body to send
    if (image == null) {
        return;/*from www .j a  v a  2s. c  o  m*/
    }
    HttpServletResponse servletResponse = context.getResponse();
    //        servletResponse.setCharacterEncoding("UTF-8");
    servletResponse.setContentType(type.toString());

    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ImageIO.write(image, type.getSubtype(), tmp);
    tmp.close();
    Integer contentLength = tmp.size();

    servletResponse.setContentLength(contentLength);

    OutputStream outStream = servletResponse.getOutputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    ImageIO.write(image, type.getSubtype(), os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());

    try {
        writeResponse(is, outStream);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            outStream.flush();
            outStream.close();
        } catch (IOException ex) {
        }
    }
}

From source file:hudson.remoting.PipeTest.java

/**
 * Writer end closes even before the remote computation kicks in.
 */// w w  w .j  ava  2 s  .  c  o m
public void testQuickBurstWrite() throws Exception {
    final Pipe p = Pipe.createLocalToRemote();
    Future<Integer> f = channel.callAsync(new Callable<Integer, IOException>() {
        public Integer call() throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(p.getIn(), baos);
            return baos.size();
        }
    });
    OutputStream os = p.getOut();
    os.write(1);
    os.close();

    // at this point the async executable kicks in.
    // TODO: introduce a lock to ensure the ordering.

    assertEquals(1, (int) f.get());
}

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

protected void postEntity(IntellectualEntity ie) throws IOException {
    HttpPost post = new HttpPost(SCAPE_URL + "/entity");
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    try {/*from w w  w.  j  av  a 2 s  .  c om*/
        this.marshaller.serialize(ie, sink);
    } catch (JAXBException e) {
        throw new IOException(e);
    }
    post.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(),
            ContentType.TEXT_XML));
    HttpResponse resp = this.client.execute(post);
    assertEquals(201, resp.getStatusLine().getStatusCode());
    String id = EntityUtils.toString(resp.getEntity());
    assertTrue(id.length() > 0);
    post.releaseConnection();
}

From source file:org.apache.olingo.fit.Demo.java

private Response replaceServiceName(final Response response) {
    try {// w  w  w  . ja v  a 2  s .  c  o m
        final String content = IOUtils.toString((InputStream) response.getEntity(), Constants.ENCODING)
                .replaceAll("Static\\.svc", "Demo.svc");

        final Response.ResponseBuilder builder = Response.status(response.getStatus());
        for (String headerName : response.getHeaders().keySet()) {
            for (Object headerValue : response.getHeaders().get(headerName)) {
                builder.header(headerName, headerValue);
            }
        }

        final InputStream toBeStreamedBack = IOUtils.toInputStream(content, Constants.ENCODING);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(toBeStreamedBack, baos);
        IOUtils.closeQuietly(toBeStreamedBack);

        builder.header("Content-Length", baos.size());
        builder.entity(new ByteArrayInputStream(baos.toByteArray()));

        return builder.build();
    } catch (Exception e) {
        return response;
    }
}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBaseTest.java

@Test
public void testCopyFilePath() throws Exception {

    String rootPath = System.getProperty("java.io.tmpdir", "/tmp");
    DeployOperatorable operator = new DeployOperatorBaseImpl.Builder().setPath(rootPath).build();
    DeployOperatorBaseImpl operatorImpl = (DeployOperatorBaseImpl) operator;

    String source = DeployOperatorBaseTest.class.getResource("write.jpg").getPath();
    operatorImpl.copy(source, "/docuemnt/1/write.jpg");
    FileObject fileObject = operatorImpl.getFileObject();

    ByteArrayOutputStream content = (ByteArrayOutputStream) fileObject.getContent().getOutputStream();
    Assert.assertEquals(335961, content.size());
}