1
2
3
4
5
6
7 package nl.mineleni.cbsviewer.servlet;
8
9 import java.io.IOException;
10 import java.io.OutputStreamWriter;
11 import java.io.PrintWriter;
12
13 import javax.servlet.ServletOutputStream;
14 import javax.servlet.http.HttpServletResponse;
15 import javax.servlet.http.HttpServletResponseWrapper;
16
17 import org.apache.http.HttpHeaders;
18
19
20
21
22 public class GZIPHttpServletResponseWrapper extends HttpServletResponseWrapper {
23
24 private ServletResponseGZIPOutputStream gzipStream;
25
26 private ServletOutputStream outputStream;
27
28 private PrintWriter printWriter;
29
30
31
32
33
34
35
36
37
38 public GZIPHttpServletResponseWrapper(HttpServletResponse response)
39 throws IOException {
40 super(response);
41 response.addHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
42 }
43
44
45
46
47
48
49
50 public void finish() throws IOException {
51 if (printWriter != null) {
52 printWriter.close();
53 }
54 if (outputStream != null) {
55 outputStream.close();
56 }
57 if (gzipStream != null) {
58 gzipStream.close();
59 }
60 }
61
62
63
64
65
66
67 @Override
68 public void flushBuffer() throws IOException {
69 if (printWriter != null) {
70 printWriter.flush();
71 }
72 if (outputStream != null) {
73 outputStream.flush();
74 }
75 super.flushBuffer();
76 }
77
78
79
80
81
82
83 @Override
84 public ServletOutputStream getOutputStream() throws IOException {
85 if (printWriter != null) {
86 throw new IllegalStateException("printWriter already defined");
87 }
88 if (outputStream == null) {
89 initGzip();
90 outputStream = gzipStream;
91 }
92 return outputStream;
93 }
94
95
96
97
98
99
100 @Override
101 public PrintWriter getWriter() throws IOException {
102 if (outputStream != null) {
103 throw new IllegalStateException("printWriter already defined");
104 }
105 if (printWriter == null) {
106 initGzip();
107 printWriter = new PrintWriter(new OutputStreamWriter(gzipStream,
108 getResponse().getCharacterEncoding()));
109 }
110 return printWriter;
111 }
112
113
114
115
116
117
118 @Override
119 public void setContentLength(int len) {
120 }
121
122
123
124
125
126
127
128 private void initGzip() throws IOException {
129 gzipStream = new ServletResponseGZIPOutputStream(getResponse()
130 .getOutputStream());
131 }
132
133 }