Code: ByteStreamResponseWrapper

Maxi was asking for the source code of ByteStreamResponseWrapper. This is related to this post (How to: write a servlet filter).

package subin.rnd.enterprise.servlet.wrapper;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import subin.rnd.enterprise.servlet.io.ServletOutputStreamImpl;

public class ByteStreamResponseWrapper
extends HttpServletResponseWrapper
{
    private ByteArrayOutputStream byteStream;

    public ByteStreamResponseWrapper(HttpServletResponse response)
    {
        super(response);
    }

    @Override
    public ServletOutputStream getOutputStream()
    {
        ServletOutputStreamImpl outputStream = null;

        this.byteStream =  (null == this.byteStream)
            ? new ByteArrayOutputStream() : this.byteStream;
        outputStream = new ServletOutputStreamImpl(this.byteStream);

        return (outputStream);
    }

    @Override
    public PrintWriter getWriter()
    {
        PrintWriter printWriter = null;

        this.byteStream =  (null == this.byteStream)
            ? new ByteArrayOutputStream() : this.byteStream;
        printWriter = new PrintWriter(this.byteStream);

        return (printWriter);
    }

    @Override
    public String toString()
    {
        return ((null == this.byteStream)
                ? null : new String(this.byteStream.toByteArray()));
    }

    public byte[] toBytes()
    {
        return ((null == this.byteStream)
                ? null : this.byteStream.toByteArray());
    }
}

Then there is ServletUtility & ServletOutputStreamImpl.

Code: ServletUtility

package subin.rnd.enterprise.servlet.util;

import java.io.OutputStream;
import javax.servlet.ServletResponse;

public class ServletUtility
{
    /**
     * Writes the bytes to the {@link OutputStream}
     *
     * @param response
     * @param bytes
     */
    public static void write(ServletResponse response, byte[] bytes)
    {
        int contentLength = -1;
        OutputStream outputStream = null;

        if ((null != response) &&
            (null != bytes) &&
            (bytes.length > 0))
        {
            contentLength = bytes.length;

            try
            {
                response.setContentLength(contentLength);
                outputStream = response.getOutputStream();
                outputStream.write(bytes);
            }
            catch (Exception exception)
            {
                outputStream = null;
            }
            finally
            {
                try
                {
                    if (null != outputStream) outputStream.close();
                }
                catch (Exception e){}
            }
        }
    }
}

ServletOutputStreamImpl is an implementation of ServletOutputStream. I think I don’t need to put the source code of it.

Advertisements