View Javadoc

1   package com.atlassian.gzipfilter;
2   
3   import com.atlassian.gzipfilter.util.IOUtils;
4   
5   import java.io.IOException;
6   import java.io.OutputStreamWriter;
7   import java.io.PrintWriter;
8   
9   import javax.servlet.ServletOutputStream;
10  import javax.servlet.http.HttpServletResponse;
11  import javax.servlet.http.HttpServletResponseWrapper;
12  
13  public class GzipResponseWrapper extends HttpServletResponseWrapper
14  {
15      protected HttpServletResponse origResponse = null;
16      protected ServletOutputStream stream = null;
17      protected PrintWriter writer = null;
18      private String encoding;
19  
20      public GzipResponseWrapper(HttpServletResponse response, String encoding)
21      {
22          super(response);
23          this.encoding = encoding;
24          origResponse = response;
25      }
26  
27      protected ServletOutputStream createOutputStream() throws IOException
28      {
29          return new GzipResponseStream(origResponse);
30      }
31  
32      public void finishResponse()
33      {
34          IOUtils.closeQuietly(writer);
35          IOUtils.closeQuietly(stream);
36      }
37  
38      public void flushBuffer() throws IOException
39      {
40          if (stream != null)
41              stream.flush();
42      }
43  
44      public ServletOutputStream getOutputStream() throws IOException
45      {
46          if (writer != null)
47              throw new IllegalStateException("getWriter() has already been called!");
48  
49          if (stream == null)
50              stream = createOutputStream();
51  
52          return stream;
53      }
54  
55      public PrintWriter getWriter() throws IOException
56      {
57          if (writer != null)
58              return writer;
59  
60          if (stream != null)
61              throw new IllegalStateException("getOutputStream() has already been called!");
62  
63          stream = createOutputStream();
64          writer = new PrintWriter(new OutputStreamWriter(stream, encoding));
65  
66          return writer;
67      }
68  
69      public void setEncoding(String encoding)
70      {
71          this.encoding = encoding;
72      }
73  }