import java.io.*;
import javax.servlet.*;

/**
 * An implementation of ServletOutputStream that captures
 * output to a ByteArrayOutputStream.  This allows interception
 * and retrieval of response output.  This is intended to be
 * used in conjunction with a ServletResponseWrapper and a Filter.
 *
 * @author Daniel J. Troesser
 */

public class ByteArrayServletOutputStream 
        extends ServletOutputStream {
                
    private ByteArrayOutputStream baos;

    public ByteArrayServletOutputStream() {
        baos = new ByteArrayOutputStream();
    }

    /**
     * Converts and returns the buffer's contents as a string
     *
     * @return the buffer's contents as a string
     */
    public ByteArrayOutputStream getByteArrayOutputStream() {
        return baos;
    }

    /**
     * Returns the underlying byte array as a String
     *
     * @return the underlying byte array as a String
     */
    public String toString() {
        return baos.toString();
    }

    /**
     * Writes the specified byte to the byte array output stream
     *
     * @param b the byte to be written.
     */
    public void write(int b) {
        baos.write(b);
    }
    
    public void reset() {
        baos.reset();
    }

    public int getSize() {
        return baos.size();
    }

    public void setSize(int size) throws IOException {
        // Actually have to create a new one with the specified size
        ByteArrayOutputStream oldOs = baos;
        baos = new ByteArrayOutputStream(size);
        baos.write(oldOs.toByteArray());
    }
}
