001    package com.mockrunner.mock.web;
002    
003    import java.io.ByteArrayOutputStream;
004    import java.io.IOException;
005    
006    import javax.servlet.ServletOutputStream;
007    
008    import com.mockrunner.base.NestedApplicationException;
009    
010    /**
011     * Mock implementation of <code>ServletOutputStream</code>.
012     */
013    public class MockServletOutputStream extends ServletOutputStream
014    {
015        private ByteArrayOutputStream buffer;
016        private String encoding;
017        
018        public MockServletOutputStream()
019        {
020            this("ISO-8859-1");
021        }
022        
023        public MockServletOutputStream(String encoding)
024        {
025            buffer = new ByteArrayOutputStream();
026            this.encoding = encoding;
027        }
028        
029        public void setEncoding(String encoding)
030        {
031            this.encoding = encoding;
032        }
033        
034        public void write(int value) throws IOException
035        {
036            buffer.write(value);
037        }
038        
039        public String getContent()
040        {
041            try
042            {
043                buffer.flush();
044                return buffer.toString(encoding);
045            } 
046            catch(IOException exc)
047            {
048                throw new NestedApplicationException(exc);
049            }
050        }
051        
052        public byte[] getBinaryContent()
053        {
054            try
055            {
056                buffer.flush();
057                return buffer.toByteArray();
058            } 
059            catch(IOException exc)
060            {
061                throw new NestedApplicationException(exc);
062            }
063        }
064        
065        public void clearContent()
066        {
067            buffer = new ByteArrayOutputStream();
068        }
069    }