1
22
23 package com.liferay.portal.servlet.filters.gzip;
24
25 import com.liferay.portal.kernel.log.Log;
26 import com.liferay.portal.kernel.log.LogFactoryUtil;
27 import com.liferay.portal.kernel.servlet.HttpHeaders;
28 import com.liferay.portal.kernel.util.ByteArrayMaker;
29
30 import java.io.IOException;
31 import java.io.OutputStream;
32
33 import java.util.zip.GZIPOutputStream;
34
35 import javax.servlet.ServletOutputStream;
36 import javax.servlet.http.HttpServletResponse;
37
38
45 public class GZipStream extends ServletOutputStream {
46
47 public GZipStream(HttpServletResponse response) throws IOException {
48 super();
49
50 _response = response;
51 _output = response.getOutputStream();
52 _bufferedOutput = new ByteArrayMaker();
53 _closed = false;
54 }
55
56 public void close() throws IOException {
57 if (_closed) {
58 throw new IOException();
59 }
60
61 if (_bufferedOutput instanceof ByteArrayMaker) {
62 ByteArrayMaker baos = (ByteArrayMaker)_bufferedOutput;
63
64 ByteArrayMaker compressedContent = new ByteArrayMaker();
65
66 GZIPOutputStream gzipOutput = new GZIPOutputStream(
67 compressedContent);
68
69 gzipOutput.write(baos.toByteArray());
70 gzipOutput.finish();
71
72 byte[] compressedBytes = compressedContent.toByteArray();
73
74 _response.setContentLength(compressedBytes.length);
75 _response.addHeader(HttpHeaders.CONTENT_ENCODING, _GZIP);
76
77 _output.write(compressedBytes);
78 _output.flush();
79 _output.close();
80
81 _closed = true;
82 }
83 else if (_bufferedOutput instanceof GZIPOutputStream) {
84 GZIPOutputStream gzipOutput = (GZIPOutputStream)_bufferedOutput;
85
86 gzipOutput.finish();
87
88 _output.flush();
89 _output.close();
90
91 _closed = true;
92 }
93 }
94
95 public void flush() throws IOException {
96 if (_closed) {
97 throw new IOException();
98 }
99
100 _bufferedOutput.flush();
101 }
102
103 public void write(int b) throws IOException {
104 if (_closed) {
105 throw new IOException();
106 }
107
108
110
112 _bufferedOutput.write((byte)b);
113 }
114
115 public void write(byte b[]) throws IOException {
116 write(b, 0, b.length);
117 }
118
119 public void write(byte b[], int off, int len) throws IOException {
120 if (_closed) {
121 throw new IOException();
122 }
123
124
126
128 try {
129 _bufferedOutput.write(b, off, len);
130 }
131 catch (IOException ioe) {
132 _log.warn(ioe.getMessage());
133 }
134 }
135
136 public boolean closed() {
137 return _closed;
138 }
139
140 public void reset() {
141 }
142
143 private static final String _GZIP = "gzip";
144
145 private static Log _log = LogFactoryUtil.getLog(GZipStream.class);
146
147 private HttpServletResponse _response = null;
148 private ServletOutputStream _output = null;
149 private OutputStream _bufferedOutput = null;
150 private boolean _closed = false;
151
152 }