Example usage for org.apache.commons.io.output CountingOutputStream getByteCount

List of usage examples for org.apache.commons.io.output CountingOutputStream getByteCount

Introduction

In this page you can find the example usage for org.apache.commons.io.output CountingOutputStream getByteCount.

Prototype

public synchronized long getByteCount() 

Source Link

Document

The number of bytes that have passed through this stream.

Usage

From source file:com.loadtesting.showcase.springmvc.filter.LoadTestFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 *///www  .j a v  a  2s.  co m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ExampleKpiCapturers caps = new ExampleKpiCapturers(request, LoadTestLayer.list());
    WebProfilingFormat webFormat;
    try {
        caps.startDefaultCapturer();

        CountingOutputStream cos = new CountingOutputStream(response.getOutputStream());
        chain.doFilter(request, response);
        webFormat = new WebProfilingFormat(request.getContentLength(), cos.getByteCount());
    } finally {
        caps.endDefaultCapturer();
    }

    sendReports(webFormat, caps);
}

From source file:com.loadtesting.showcase.springmvc.filter.PatternFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 *///from w  ww. jav a  2s .c  o m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ExampleKpiCapturers caps = new ExampleKpiCapturers(request, PatternLayer.list());
    WebProfilingFormat webFormat;
    try {
        caps.startDefaultCapturer();

        CountingOutputStream cos = new CountingOutputStream(response.getOutputStream());
        chain.doFilter(request, response);
        webFormat = new WebProfilingFormat(request.getContentLength(), cos.getByteCount());
    } finally {
        caps.endDefaultCapturer();
    }

    sendReports(webFormat, caps);
}

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

/**
 * Copies the entity content to the specified output stream and validates
 * that the number of bytes copied is the same as specified when in the
 * original content-length.// w w w .j a v  a2 s  .c  om
 *
 * @param out stream to copy to
 * @throws IOException throw when there is a problem writing to the streams
 */
private void copyContentToOutputStream(final OutputStream out) throws IOException {
    final long bytesCopied;

    /* Only the EmbeddedHttpContent class requires us to actually call
     * write out on the wrapped object. In its particular case it is doing
     * a wrapping operation between an InputStream and an OutputStream in
     * order to provide an OutputStream interface to MantaClient. */
    if (this.wrapped.getClass().equals(EmbeddedHttpContent.class)) {
        CountingOutputStream cout = new CountingOutputStream(out);
        this.wrapped.writeTo(cout);
        cout.flush();
        bytesCopied = cout.getByteCount();
    } else {
        /* We choose a small buffer because large buffer don't result in
         * better performance when writing to a CipherOutputStream. You
         * can try this yourself by fiddling with this value and running
         * EncryptingEntityBenchmark. */
        final int bufferSize = 128;

        InputStream contentStream = getContent();
        bytesCopied = IOUtils.copy(contentStream, out, bufferSize);
        out.flush();
        try {
            contentStream.close();
        } catch (IOException e) {
            LOGGER.error("Failed to close content stream in EncryptingEntity.", e);
        }
    }

    /* If we don't know the length of the underlying content stream, we
     * count the number of bytes written, so that it is available. */
    if (originalLength == UNKNOWN_LENGTH) {
        originalLength = bytesCopied;
    } else if (originalLength != bytesCopied) {
        MantaIOException e = new MantaIOException(
                "Bytes copied doesn't equal the " + "specified content length");
        e.setContextValue("specifiedContentLength", originalLength);
        e.setContextValue("actualContentLength", bytesCopied);
        throw e;
    }
}

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);/*from   w  w w  .  j  av a  2s .  co  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:ee.ria.xroad.proxy.protocol.ProxyMessageEncoder.java

@Override
public void attachment(String contentType, InputStream content, Map<String, String> additionalHeaders)
        throws Exception {
    log.trace("writeAttachment({})", contentType);

    if (!inAttachmentPart) {
        mpEncoder.startNested(attachmentBoundary);
        inAttachmentPart = true;//from  ww w.j av  a  2 s.c om
    }

    DigestCalculator calc = createDigestCalculator(hashAlgoId);
    CountingOutputStream cos = new CountingOutputStream(calc.getOutputStream());
    TeeInputStream proxyIs = new TeeInputStream(content, cos, true);

    mpEncoder.startPart(contentType, toHeaders(additionalHeaders));
    mpEncoder.write(proxyIs);

    attachmentsByteCount += cos.getByteCount();

    signer.addPart(MessageFileNames.attachment(++attachmentNo), hashAlgoId, calc.getDigest());
}

From source file:com.digitalpebble.stormcrawler.warc.GzipHdfsBolt.java

protected void writeRecord(byte[] bytes) throws IOException {
    CountingOutputStream countingStream = new CountingOutputStream(out);
    @SuppressWarnings("resource")
    CompressedOutputStream compressedStream = new CompressedOutputStream(countingStream);
    synchronized (this.writeLock) {
        compressedStream.write(bytes);//from  w  w  w . j a  v a  2s.  c  om
        compressedStream.finish();
        compressedStream.flush();
    }
    compressedStream.end();
    if (rotateOnCompressedOffset) {
        offset += countingStream.getByteCount();
    } else {
        offset += bytes.length;
    }
}

From source file:caarray.client.test.java.JavaApiFacade.java

public Long copyMageTabZipToOutputStream(String api, CaArrayEntityReference experimentReference,
        boolean compressed) throws Exception {
    CountingOutputStream outStream = new CountingOutputStream(new NullOutputStream());
    dataApiUtils.copyMageTabZipToOutputStream(experimentReference, outStream);
    return outStream.getByteCount();
}

From source file:com.izforge.izpack.installer.unpacker.Pack200FileUnpackerTest.java

@Override
protected InputStream createPackStream(File source) throws IOException {
    File tmpfile = null;//from   ww  w  .  j a v a 2 s .com
    JarFile jar = null;

    try {
        tmpfile = File.createTempFile("izpack-compress", ".pack200", FileUtils.getTempDirectory());
        CountingOutputStream proxyOutputStream = new CountingOutputStream(FileUtils.openOutputStream(tmpfile));
        OutputStream bufferedStream = IOUtils.buffer(proxyOutputStream);

        Pack200.Packer packer = createPack200Packer(this.packFile);
        jar = new JarFile(this.packFile.getFile());
        packer.pack(jar, bufferedStream);

        bufferedStream.flush();
        this.packFile.setSize(proxyOutputStream.getByteCount());

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(FileUtils.openInputStream(tmpfile), out);
        out.close();
        return new ByteArrayInputStream(out.toByteArray());
    } finally {
        if (jar != null) {
            jar.close();
        }
        FileUtils.deleteQuietly(tmpfile);
    }
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportSender.java

private void populateResponseFile(FileObject responseFile, MessageContext msgContext, boolean append,
        boolean lockingEnabled) throws AxisFault {

    MessageFormatter messageFormatter = getMessageFormatter(msgContext);
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);

    try {//from  ww w .ja v a  2  s  .com
        CountingOutputStream os = new CountingOutputStream(responseFile.getContent().getOutputStream(append));
        try {
            messageFormatter.writeTo(msgContext, format, os, true);
        } finally {
            os.close();
        }

        // update metrics
        metrics.incrementMessagesSent(msgContext);
        metrics.incrementBytesSent(msgContext, os.getByteCount());

    } catch (FileSystemException e) {
        if (lockingEnabled) {
            VFSUtils.releaseLock(fsManager, responseFile);
        }
        metrics.incrementFaultsSending();
        handleException("IO Error while creating response file : " + responseFile.getName(), e);
    } catch (IOException e) {
        if (lockingEnabled) {
            VFSUtils.releaseLock(fsManager, responseFile);
        }
        metrics.incrementFaultsSending();
        handleException("IO Error while creating response file : " + responseFile.getName(), e);
    }
}

From source file:ee.ria.xroad.proxy.protocol.ProxyMessageDecoder.java

private void parseAttachments(String attachmentContentType, InputStream is) throws MimeException, IOException {
    MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(attachmentContentType).build();

    final MimeStreamParser attachmentParser = new MimeStreamParser(config);
    attachmentParser.setContentHandler(new AbstractContentHandler() {
        private Map<String, String> headers;
        private String partContentType;

        @Override/*  w  w  w  . j a v a2  s . c o m*/
        public void startHeader() throws MimeException {
            headers = new HashMap<>();
            partContentType = null;
        }

        @Override
        public void field(Field field) throws MimeException {
            if (field.getName().toLowerCase().equals(HEADER_CONTENT_TYPE)) {
                partContentType = field.getBody();
            } else {
                headers.put(field.getName(), field.getBody());
            }
        }

        @Override
        public void startMultipart(BodyDescriptor bd) {
            attachmentParser.setFlat();
        }

        @Override
        public void body(BodyDescriptor bd, InputStream is) throws IOException {
            LOG.trace("attachment body: {}", bd.getMimeType());
            try {
                DigestCalculator dc = CryptoUtils.createDigestCalculator(getHashAlgoId());
                CountingOutputStream cos = new CountingOutputStream(dc.getOutputStream());
                TeeInputStream proxyIs = new TeeInputStream(is, cos, true);

                callback.attachment(partContentType, proxyIs, headers);

                attachmentsByteCount += cos.getByteCount();

                verifier.addPart(MessageFileNames.attachment(++attachmentNo), getHashAlgoId(), dc.getDigest());
            } catch (Exception ex) {
                throw translateException(ex);
            }
        }
    });

    attachmentParser.parse(is);
}