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.ge.predix.sample.blobstore.repository.BlobstoreService.java

/**
 * Adds a new Blob to the binded bucket in the Object Store
 *
 * @param obj S3Object to be added/*from  www.j av a 2 s.c  om*/
 * @throws Exception
 */
public void put(S3Object obj) throws Exception {
    if (obj == null) {
        log.error("put(): Empty file provided");
        throw new Exception("File is null");
    }
    InputStream is = obj.getObjectContent();

    List<PartETag> partETags = new ArrayList<>();

    InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucket, obj.getKey());
    InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);
    try {

        int i = 1;
        int currentPartSize = 0;
        ByteArrayOutputStream tempBuffer = new ByteArrayOutputStream();
        int byteValue;
        while ((byteValue = is.read()) != -1) {
            tempBuffer.write(byteValue);
            currentPartSize = tempBuffer.size();
            if (currentPartSize == (50 * 1024 * 1024)) //make this a const
            {
                byte[] b = tempBuffer.toByteArray();
                ByteArrayInputStream byteStream = new ByteArrayInputStream(b);

                UploadPartRequest uploadPartRequest = new UploadPartRequest().withBucketName(bucket)
                        .withKey(obj.getKey()).withUploadId(initResponse.getUploadId()).withPartNumber(i++)
                        .withInputStream(byteStream).withPartSize(currentPartSize);
                partETags.add(s3Client.uploadPart(uploadPartRequest).getPartETag());

                tempBuffer.reset();
            }
        }
        log.info("currentPartSize: " + currentPartSize);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(currentPartSize);
        obj.setObjectMetadata(objectMetadata);

        if (i == 1 && currentPartSize < (5 * 1024 * 1024)) // make this a const
        {
            s3Client.abortMultipartUpload(
                    new AbortMultipartUploadRequest(bucket, obj.getKey(), initResponse.getUploadId()));

            byte[] b = tempBuffer.toByteArray();
            ByteArrayInputStream byteStream = new ByteArrayInputStream(b);

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, obj.getKey(), byteStream,
                    obj.getObjectMetadata());
            s3Client.putObject(putObjectRequest);
            return;
        }

        if (currentPartSize > 0 && currentPartSize <= (50 * 1024 * 1024)) // make this a const
        {
            byte[] b = tempBuffer.toByteArray();
            ByteArrayInputStream byteStream = new ByteArrayInputStream(b);

            log.info("currentPartSize: " + currentPartSize);
            log.info("byteArray: " + b);

            UploadPartRequest uploadPartRequest = new UploadPartRequest().withBucketName(bucket)
                    .withKey(obj.getKey()).withUploadId(initResponse.getUploadId()).withPartNumber(i)
                    .withInputStream(byteStream).withPartSize(currentPartSize);
            partETags.add(s3Client.uploadPart(uploadPartRequest).getPartETag());
        }
    } catch (Exception e) {
        log.error("put(): Exception occurred in put(): " + e.getMessage());
        s3Client.abortMultipartUpload(
                new AbortMultipartUploadRequest(bucket, obj.getKey(), initResponse.getUploadId()));
        throw e;
    }
    CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest()
            .withBucketName(bucket).withPartETags(partETags).withUploadId(initResponse.getUploadId())
            .withKey(obj.getKey());

    s3Client.completeMultipartUpload(completeMultipartUploadRequest);
}

From source file:org.obm.caldav.client.AbstractPushTest.java

private void appendHeader(HttpMethod hm, ByteArrayOutputStream out) {
    hm.setRequestHeader("Host", "lemurien.tlse.lng:8008");
    hm.setRequestHeader("User-Agent", userAgent);
    hm.setRequestHeader("Accept", "text/xml");
    hm.setRequestHeader("Accept-Charset", "utf-8,*;q=0.1");
    hm.setRequestHeader("Content-Length", "" + out.size());
    hm.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    hm.setRequestHeader("Depth", "0");
    if (authenticate != null && !"".equals(authenticate)) {
        hm.setRequestHeader("Authorization", authenticate);
    }//from w  ww  .  jav  a  2 s. c  o  m
}

From source file:net.sf.jasperreports.engine.design.JRJdk13Compiler.java

@Override
public String compileClasses(File[] sourceFiles, String classpath) throws JRException {
    String[] source = new String[sourceFiles.length + 2];
    for (int i = 0; i < sourceFiles.length; i++) {
        source[i] = sourceFiles[i].getPath();
    }/*from w  w  w . j a  v  a  2s.co m*/
    source[sourceFiles.length] = "-classpath";
    source[sourceFiles.length + 1] = classpath;

    String errors = null;

    try {
        Class<?> clazz = JRClassLoader.loadClassForRealName("com.sun.tools.javac.Main");
        Object compiler = clazz.getDeclaredConstructor().newInstance();

        try {
            Method compileMethod = clazz.getMethod("compile",
                    new Class[] { String[].class, PrintWriter.class });
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int result = (Integer) compileMethod.invoke(compiler,
                    new Object[] { source, new PrintWriter(baos) });

            if (result != MODERN_COMPILER_SUCCESS) {
                errors = baos.toString();
            } else {
                if (log.isInfoEnabled() && baos.size() > 0) {
                    log.info(baos.toString());
                }
            }
        } catch (NoSuchMethodException ex) {
            Method compileMethod = clazz.getMethod("compile", new Class[] { String[].class });

            int result = (Integer) compileMethod.invoke(compiler, new Object[] { source });
            if (result != MODERN_COMPILER_SUCCESS) {
                errors = "See error messages above.";
            }
        }
    } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException
            | InstantiationException e) {
        StringBuilder files = new StringBuilder();
        for (int i = 0; i < sourceFiles.length; ++i) {
            files.append(sourceFiles[i].getPath());
            files.append(' ');
        }
        throw new JRException(EXCEPTION_MESSAGE_KEY_JAVA_SOURCE_COMPILE_ERROR, new Object[] { files }, e);
    }

    return errors;
}

From source file:org.apache.hadoop.hbase.rest.provider.consumer.ProtobufMessageBodyConsumer.java

@Override
public ProtobufMessageHandler readFrom(Class<ProtobufMessageHandler> type, Type genericType,
        Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
        InputStream inputStream) throws IOException, WebApplicationException {
    ProtobufMessageHandler obj = null;/*from   ww w. j  av a2s . c o  m*/
    try {
        obj = type.newInstance();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int read;
        do {
            read = inputStream.read(buffer, 0, buffer.length);
            if (read > 0) {
                baos.write(buffer, 0, read);
            }
        } while (read > 0);
        if (LOG.isDebugEnabled()) {
            LOG.debug(getClass() + ": read " + baos.size() + " bytes from " + inputStream);
        }
        obj = obj.getObjectFromMessage(baos.toByteArray());
    } catch (InstantiationException e) {
        throw new WebApplicationException(e);
    } catch (IllegalAccessException e) {
        throw new WebApplicationException(e);
    }
    return obj;
}

From source file:org.esxx.Response.java

public long getContentLength() throws IOException {
    if (!buffered) {
        throw new IllegalStateException("getContentLength() only works on buffered responses");
    }/*from   w  w w  . j av  a  2s. c o  m*/

    if (contentLength == -1) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        writeResult(bos);
        setResult(bos.toByteArray());
        contentLength = bos.size();
    }

    return contentLength;
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.DataWrapper.java

public void write(ByteArrayOutputStream baos) throws IOException {

    if (response.isCommitted()) {
        String contentType = response.getContentType();
        log.error(String.format("Response already committed, can't send %d bytes of content type %s",
                baos.size(), contentType));
        if (log.isDebugEnabled() && (contentType == null || !contentType.startsWith("image/"))) {
            log.error("Full content: " + baos.toString());
        }/*ww  w. j a  v a  2 s .c om*/
        return;
    }
    //Logging the dataspeed...
    Operation o = new Operation();
    o.setType(Operation.CLIENT_TRANSFER);
    if (requestReporting != null) {
        o.setDataSize(new Long(baos.size()));
        o.setMsSinceRequestStart(new Long(requestReporting.getMSSinceStart()));
    }
    long startTime = System.currentTimeMillis();
    // Log initialized, now start the operation...
    this.setContentLength(baos.size());
    try {
        sos.write(baos.toByteArray());
        sos.flush();
    } finally {
        if (sos != null) {
            sos.close();
        }
    }
    // Operation done.. now write the log...
    if (requestReporting != null) {
        o.setDuration(new Long(System.currentTimeMillis() - startTime));
        try {
            requestReporting.addRequestOperation(o);
        } catch (Throwable t) {
            log.warn("", t);
        }
    }

}

From source file:com.joyent.manta.client.multipart.EncryptedMultipartManager.java

@Override
public void complete(final EncryptedMultipartUpload<WRAPPED_UPLOAD> upload,
        final Stream<? extends MantaMultipartUploadTuple> partsStream) throws IOException {
    final EncryptionState encryptionState = upload.getEncryptionState();

    encryptionState.getLock().lock();//from  w w  w .ja v  a 2s . co m
    try {
        Stream<? extends MantaMultipartUploadTuple> finalPartsStream = partsStream;
        // we need to take a snapshot _before_ calling remainderAndLastPartAuth
        final EncryptionStateSnapshot snapshot = EncryptionStateRecorder.record(encryptionState,
                upload.getId());
        if (!encryptionState.isLastPartAuthWritten()) {
            ByteArrayOutputStream remainderStream = encryptionState.remainderAndLastPartAuth();
            if (remainderStream.size() > 0) {
                final MantaMultipartUploadPart finalPart = uploadPartWithSnapshot(upload,
                        encryptionState.getLastPartNumber() + 1, buildRequestContext(null), encryptionState,
                        new ByteArrayEntity(remainderStream.toByteArray()), snapshot);
                finalPartsStream = Stream.concat(partsStream, Stream.of(finalPart));
            }
        }

        wrapped.complete(upload.getWrapped(), finalPartsStream);
    } finally {
        encryptionState.getLock().unlock();
    }
}

From source file:com.rabbitstewdio.build.maven.tomcat.AbstractContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String filename = request.getPathInfo();

    InputStream in = findResource(filename);
    if (in == null) {
        log.warn("Unable to find [" + filename + "] on " + getServletName());
        response.setStatus(404);//from   w  w  w  .j  av a2 s . c om
        return;
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(in, bout);

    response.setCharacterEncoding("UTF-8");

    String mimeType = getServletContext().getMimeType(filename);
    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    response.addDateHeader("Expires", 0L);
    response.setDateHeader(LAST_MODIFIED, new Date().getTime());
    response.setContentLength(bout.size());
    response.getOutputStream().write(bout.toByteArray());
    response.flushBuffer();
}

From source file:org.taverna.server.master.worker.RunDatabase.java

private void logLength(String message, Object obj) {
    if (!log.isDebugEnabled())
        return;//from  w  w w  .ja v a  2 s.c  o  m
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(obj);
        }
        log.debug(message + ": " + baos.size());
    } catch (Exception e) {
        log.warn("oops", e);
    }
}

From source file:com.ning.metrics.action.hdfs.data.RowSmile.java

/**
 * Serialize the row into the DataOutput
 *
 * @param out DataOutput to write//from   ww w.j av  a 2s  .c om
 * @throws java.io.IOException generic serialization error
 */
@Override
public void write(DataOutput out) throws IOException {
    schema.write(out);
    WritableUtils.writeVInt(out, data.size());

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    JsonGenerator gen = objectMapper.getJsonFactory().createJsonGenerator(outStream, JsonEncoding.UTF8);
    for (JsonNodeComparable dataItem : data) {
        objectMapper.writeValue(gen, dataItem);
    }
    gen.close();

    // Size of Smile payload. Needed for deserialization, see below
    WritableUtils.writeVInt(out, outStream.size());

    out.write(outStream.toByteArray());
}