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.appverse.web.framework.backend.frontfacade.gxt.controllers.FileUploadController.java

/**
 * /* w  ww.  j a  va  2s. c  om*/
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz
Content-Disposition: form-data; name="file"; filename="iphone100x100.png"
Content-Type: image/png
        
        
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz
Content-Disposition: form-data; name="hiddenFileName"
        
iphone100x100.png
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz
Content-Disposition: form-data; name="hiddenMediaCategory"
        
2
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz
Content-Disposition: form-data; name="maxFileSize"
        
14745600000
------WebKitFormBoundaryx2lXibtD2G3Y2Qkz--    */

@POST
@Path("{servicemethodname}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void handleFormUpload(@PathParam("servicemethodname") String servicemethodname,
        @FormDataParam("file") InputStream stream, @FormDataParam("hiddenFileName") String hiddenFileName,
        @FormDataParam("hiddenMediaCategory") String hiddenMediaCategory,
        @FormDataParam("maxFileSize") String maxSize, @Context HttpServletRequest request,
        @Context HttpServletResponse response) throws Exception {

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("hiddenFileName", hiddenFileName);
    parameters.put("hiddenMediaCategory", hiddenMediaCategory);
    parameters.put("maxFileSize", maxSize);

    SecurityHelper.checkXSRFToken(request);

    serviceName.set(servicemethodname.substring(0, servicemethodname.lastIndexOf(".")));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = stream.read(bytes)) != -1) {
        baos.write(bytes, 0, read);
    }
    baos.flush();
    baos.close();

    if (baos != null && baos.size() > 0) {
        processCall(response, baos.toByteArray(), parameters);
    } else {
        throw new Exception("The file is empty");
    }
}

From source file:cz.incad.kramerius.service.replication.ExternalReferencesFormat.java

private void changeDatastreamVersion(Document document, Element datastream, Element version, URL url)
        throws IOException {
    InputStream is = null;/*from   w  ww .jav a  2 s . c o  m*/
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        URLConnection urlConnection = url.openConnection();
        is = urlConnection.getInputStream();
        IOUtils.copyStreams(is, bos);
        version.setAttribute("SIZE", "" + bos.size());
        version.removeChild(XMLUtils.findElement(version, "contentLocation", version.getNamespaceURI()));
        Element binaryContent = document.createElementNS(version.getNamespaceURI(), "binaryContent");
        document.adoptNode(binaryContent);
        binaryContent.setTextContent(new String(Base64.encodeBase64(bos.toByteArray())));
        version.appendChild(binaryContent);

        datastream.setAttribute("CONTROL_GROUP", "M");

    } finally {
        IOUtils.tryClose(is);
    }
}

From source file:com.alliander.osgp.adapter.ws.endpointinterceptors.WebServiceMonitorInterceptor.java

/**
 * Try to find the XML_ELEMENT_CORRELATION_UID, XML_ELEMENT_DEVICE_ID and
 * the XML_ELEMENT_OSP_RESULT_TYPE from the soap message. Note that these
 * elements are not always present in the soap message. In that case, the
 * values will be null. Also, determine the data size of the response.
 *
 * @param soapMessage//from   w ww.  j av  a 2s .com
 *            The soap message.
 *
 * @return Map containing CORRELATION_UID, DEVICE_ID, RESPONSE_RESULT and
 *         RESPONSE_DATA_SIZE.
 */
private Map<String, Object> parseSoapMessage(final SoapMessage soapMessage) {
    try {
        // Determine the data size of the message (stream).
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        soapMessage.writeTo(outputStream);
        final int dataSize = outputStream.size();

        // final String message = new String(outputStream.toByteArray());
        // LOGGER.info("soap message: {}", message);

        // Try to find the desired XML elements in the document.
        final Document document = soapMessage.getDocument();
        final String correlationUid = this.evaluateXPathExpression(document, XML_ELEMENT_CORRELATION_UID);
        final String deviceId = this.evaluateXPathExpression(document, XML_ELEMENT_DEVICE_ID);
        final String result = this.evaluateXPathExpression(document, XML_ELEMENT_OSP_RESULT_TYPE);

        // Create the Map containing the output.
        final Map<String, Object> map = new HashMap<String, Object>(4);
        map.put(CORRELATION_UID, correlationUid);
        map.put(DEVICE_ID, deviceId);
        map.put(RESPONSE_RESULT, result);
        map.put(RESPONSE_DATA_SIZE, dataSize);

        return map;
    } catch (final Exception e) {
        LOGGER.error("failed to parse soap message or to execute xPath expression", e);
        return null;
    }
}

From source file:integration.report.ReportIT.java

protected void createEntity(IntellectualEntity ie) throws IOException {
    HttpPost post = new HttpPost(serverAddress + "/scape/entity");
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    try {// w ww . ja v a2 s.  c om
        this.scapeMarshaller.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:com.milaboratory.primitivio.PrimitivIOTest.java

@Test
public void testNonReferenceSerialization1() throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    PrimitivO po = new PrimitivO(bos);
    int cc = 10;/*from  ww  w .j  a  v  a2 s.  c  o  m*/
    for (int i = 0; i < cc; ++i) {
        po.writeObject(2);
    }

    Assert.assertEquals(cc * 4, bos.size());

    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    PrimitivI pi = new PrimitivI(bis);
    for (int i = 0; i < cc; ++i) {
        Assert.assertEquals((Integer) 2, pi.readObject(Integer.class));
    }
}

From source file:org.apache.nifi.distributed.cache.client.DistributedMapCacheClientService.java

private <T> void serialize(final T value, final Serializer<T> serializer, final DataOutputStream dos)
        throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    serializer.serialize(value, baos);/*from ww  w. j ava 2s .co  m*/
    dos.writeInt(baos.size());
    baos.writeTo(dos);
}

From source file:org.openstatic.http.HttpResponse.java

/** Set the entire response body to the contents of an InputStream which will be read until EOF into memory and then relayed */
public void setBufferedData(InputStream is, String contentType) {
    try {/*from   w  ww . j a  v a 2 s. c  om*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int inputByte;
        while ((inputByte = is.read()) > -1) {
            baos.write(inputByte);
        }
        is.close();
        this.data = new ByteArrayInputStream(baos.toByteArray());
        this.dataLength = baos.size();
        baos.reset();
        this.contentType = contentType;
    } catch (Exception e) {
        this.responseCode = "404 Not Found";
    }
}

From source file:com.datatorrent.lib.io.HttpJsonChunksInputOperator.java

@Override
public void processResponse(ClientResponse response) throws IOException {
    InputStream is = response.getEntity(java.io.InputStream.class);

    while (true) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[255];
        int bytesRead;
        while ((bytesRead = is.read(bytes)) != -1) {
            LOG.debug("read {} bytes", bytesRead);
            bos.write(bytes, 0, bytesRead);
            if (is.available() == 0 && bos.size() > 0) {
                // give chance to process what we have before blocking on read
                break;
            }/*from w  w  w . java 2 s  .co m*/
        }
        try {
            if (processBytes(bos.toByteArray())) {
                LOG.debug("End of chunked input stream.");
                response.close();
                break;
            }
        } catch (JSONException ex) {
            LOG.error("Caught JSON error:", ex);
        }
        if (bytesRead == -1) {
            LOG.error("Unexpected end of chunked input stream");
            response.close();
            break;
        }

        bos.reset();
    }
}

From source file:io.undertow.servlet.test.streams.ServletInputStreamTestCase.java

private void runTestViaJavaImpl(final String message, String url) throws IOException {
    HttpURLConnection urlcon = null;
    try {//w  w w  .j av  a 2 s .  c o m
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/" + url;
        urlcon = (HttpURLConnection) new URL(uri).openConnection();
        urlcon.setInstanceFollowRedirects(true);
        urlcon.setRequestProperty("Connection", "close");
        urlcon.setRequestMethod("POST");
        urlcon.setDoInput(true);
        urlcon.setDoOutput(true);
        OutputStream os = urlcon.getOutputStream();
        os.write(message.getBytes());
        os.close();
        Assert.assertEquals(StatusCodes.OK, urlcon.getResponseCode());
        InputStream is = urlcon.getInputStream();

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        int len;
        while ((len = is.read(buf)) > 0) {
            bytes.write(buf, 0, len);
        }
        is.close();
        final String response = new String(bytes.toByteArray(), 0, bytes.size());
        if (!message.equals(response)) {
            System.out.println(String.format("response=%s", Hex.encodeHexString(response.getBytes())));
        }
        Assert.assertEquals(message, response);
    } finally {
        if (urlcon != null) {
            urlcon.disconnect();
        }
    }
}

From source file:io.undertow.server.ssl.ComplexSSLTestCase.java

@Test
public void testSslLotsOfData() throws IOException, GeneralSecurityException, URISyntaxException {

    DefaultServer.setRootHandler(new HttpHandler() {
        @Override/*  ww w .  jav a 2s .  c  o  m*/
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (exchange.isInIoThread()) {
                exchange.dispatch(this);
                return;
            }
            exchange.startBlocking();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[100];
            int res = 0;
            while ((res = exchange.getInputStream().read(buf)) > 0) {
                out.write(buf, 0, res);
            }
            System.out.println("WRITE " + out.size());
            exchange.getOutputStream().write(out.toByteArray());
            System.out.println("DONE " + out.size());
        }
    });

    DefaultServer.startSSLServer();
    TestHttpClient client = new TestHttpClient();
    client.setSSLContext(DefaultServer.getClientSSLContext());
    try {
        generateMessage(1000000);
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerSSLAddress());
        post.setEntity(new StringEntity(message));
        HttpResponse resultList = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, resultList.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(resultList);
        Assert.assertEquals(message.length(), response.length());
        Assert.assertEquals(message, response);

        generateMessage(100000);
        post = new HttpPost(DefaultServer.getDefaultServerSSLAddress());
        post.setEntity(new StringEntity(message));
        resultList = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, resultList.getStatusLine().getStatusCode());
        response = HttpClientUtils.readResponse(resultList);
        Assert.assertEquals(message.length(), response.length());
        Assert.assertEquals(message, response);

    } finally {
        client.getConnectionManager().shutdown();
        DefaultServer.stopSSLServer();
    }
}