View Javadoc

1   package ch.qos.logback.access.servlet;
2   
3   import java.io.ByteArrayOutputStream;
4   import java.io.IOException;
5   
6   import javax.servlet.ServletOutputStream;
7   import javax.servlet.ServletResponse;
8   
9   public class TeeServletOutputStream extends ServletOutputStream {
10  
11    final ServletOutputStream underlyingStream;
12    final ByteArrayOutputStream baosCopy;
13  
14    TeeServletOutputStream(ServletResponse httpServletResponse)
15        throws IOException {
16      // System.out.println("TeeServletOutputStream.constructor() called");
17      this.underlyingStream = httpServletResponse.getOutputStream();
18      baosCopy = new ByteArrayOutputStream();
19    }
20  
21    byte[] getOutputStreamAsByteArray() {
22      return baosCopy.toByteArray();
23    }
24  
25    @Override
26    public void write(int val) throws IOException {
27      if (underlyingStream != null) {
28        underlyingStream.write(val);
29        baosCopy.write(val);
30      }
31    }
32  
33    @Override
34    public void write(byte[] byteArray) throws IOException {
35      if (underlyingStream == null) {
36        return;
37      }
38      // System.out.println("WRITE TeeServletOutputStream.write(byte[]) called");
39      write(byteArray, 0, byteArray.length);
40    }
41  
42    @Override
43    public void write(byte byteArray[], int offset, int length)
44        throws IOException {
45      if (underlyingStream == null) {
46        return;
47      }
48      // System.out.println("WRITE TeeServletOutputStream.write(byte[], int, int)
49      // called");
50      // System.out.println(new String(byteArray, offset, length));
51      underlyingStream.write(byteArray, offset, length);
52      baosCopy.write(byteArray, offset, length);
53    }
54  
55    @Override
56    public void close() throws IOException {
57      // System.out.println("CLOSE TeeServletOutputStream.close() called");
58  
59      // If the servlet accessing the stream is using a writer instead of
60      // an OutputStream, it will probably call os.close() before calling
61      // writer.close. Thus, the underlying output stream will be called
62      // before the data sent to the writer could be flushed.
63    }
64  
65  
66    @Override
67    public void flush() throws IOException {
68      if (underlyingStream == null) {
69        return;
70      }
71      // System.out.println("FLUSH TeeServletOutputStream.flush() called");
72      underlyingStream.flush();
73      baosCopy.flush();
74    }
75  }