mitm.common.util.ReadableOutputStreamBuffer.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.util.ReadableOutputStreamBuffer.java

Source

/*
 * Copyright (c) 2010-2011, Martijn Brinkers, Djigzo.
 *
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License
 * version 3, 19 November 2007 as published by the Free Software
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 *
 * If you modify this Program, or any covered work, by linking or
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar,
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar,
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar,
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar,
 * wsdl4j-1.6.1.jar (or modified versions of these libraries),
 * containing parts covered by the terms of Eclipse Public License,
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant
 * you additional permission to convey the resulting work.
 */
package mitm.common.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.DeferredFileOutputStream;

/**
 * An OutputStream implementation that allows the data written to the read back. The bytes are written in memory
 * until a threshold is reached. After the threshold is reached the bytes are written to disk.
 *
 * @author Martijn Brinkers
 *
 */
public class ReadableOutputStreamBuffer extends OutputStream {
    /*
     * The output to delegate all calls to.
     */
    private final DeferredFileOutputStream buffer;

    /*
     * True if this stream is closed.
     */
    private boolean closed;

    /*
     * True if the buffer is closed.
     */
    private boolean bufferClosed;

    /**
     * Creates a ReadableOutputStream. If the number of bytes written exceeds threshold, the data will
     * be stored in a temporary file. The caller should always call close to make sure the temp file
     * is deleted.
     */
    public ReadableOutputStreamBuffer(int threshold) {
        buffer = new DeferredFileOutputStream(threshold, FileConstants.TEMP_FILE_PREFIX, null, null);
    }

    private void checkBufferClosed() throws IOException {
        if (bufferClosed) {
            throw new IOException("This underlying buffer is already closed.");
        }
    }

    @Override
    public void write(int b) throws IOException {
        checkBufferClosed();

        buffer.write(b);
    }

    @Override
    public void write(byte b[]) throws IOException {
        checkBufferClosed();

        buffer.write(b);
    }

    @Override
    public void write(byte b[], int off, int len) throws IOException {
        checkBufferClosed();

        buffer.write(b, off, len);
    }

    @Override
    public void flush() throws IOException {
        buffer.flush();
    }

    private void closeBuffer() {
        IOUtils.closeQuietly(buffer);

        bufferClosed = true;
    }

    @Override
    public void close() throws IOException {
        if (closed) {
            return;
        }

        closed = true;

        closeBuffer();

        FileUtils.deleteQuietly(buffer.getFile());
    }

    /**
     * The threshols
     */
    public int getThreshold() {
        return buffer.getThreshold();
    }

    /**
     * The number of bytes currently written
     */
    public long getByteCount() {
        return buffer.getByteCount();
    }

    /**
     * Returns an InputStream on the data written. This closes the underlying output buffer and new data can
     * no longer be written to this output stream. The returned InputStream is no longer valid after
     * {@link #close()} is called.
     *
     * Note 1: The caller should close the returned input stream after use!
     *
     * Note 2: calling {@link #getInputStream()} closes the underlying buffer but does not close this OutputStream!
     * {@link #close()} should always be called to make sure that no temp files are leaked.
     */
    @SuppressWarnings("resource")
    public InputStream getInputStream() throws IOException {
        if (closed) {
            throw new IOException("This ReadableOutputStreamBuffer is already closed.");
        }

        closeBuffer();

        return buffer.isInMemory() ? new ByteArrayInputStream(buffer.getData())
                : new BufferedInputStream(new FileInputStream(buffer.getFile()));
    }
}