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
29 import java.io.ByteArrayOutputStream;
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
44 public class GZipStream extends ServletOutputStream {
45
46 public GZipStream(HttpServletResponse response) throws IOException {
47 super();
48
49 _response = response;
50 _output = response.getOutputStream();
51 _bufferedOutput = new ByteArrayOutputStream();
52 _closed = false;
53 }
54
55 public void close() throws IOException {
56 if (_closed) {
57 throw new IOException();
58 }
59
60 if (_bufferedOutput instanceof ByteArrayOutputStream) {
61 ByteArrayOutputStream baos = (ByteArrayOutputStream)_bufferedOutput;
62
63 if (baos.size() > 20) {
64 ByteArrayOutputStream compressedContent =
65 new ByteArrayOutputStream();
66
67 GZIPOutputStream gzipOutput = new GZIPOutputStream(
68 compressedContent);
69
70 gzipOutput.write(baos.toByteArray());
71 gzipOutput.finish();
72
73 byte[] compressedBytes = compressedContent.toByteArray();
74
75 _response.setContentLength(compressedBytes.length);
76 _response.addHeader(HttpHeaders.CONTENT_ENCODING, _GZIP);
77
78 _output.write(compressedBytes);
79 }
80 else {
81 _response.setContentLength(baos.size());
82
83 _output.write(baos.toByteArray());
84 }
85
86 _output.flush();
87 _output.close();
88
89 _closed = true;
90 }
91 else if (_bufferedOutput instanceof GZIPOutputStream) {
92 GZIPOutputStream gzipOutput = (GZIPOutputStream)_bufferedOutput;
93
94 gzipOutput.finish();
95
96 _output.flush();
97 _output.close();
98
99 _closed = true;
100 }
101 }
102
103 public void flush() throws IOException {
104 if (_closed) {
105 throw new IOException();
106 }
107
108 _bufferedOutput.flush();
109 }
110
111 public void write(int b) throws IOException {
112 if (_closed) {
113 throw new IOException();
114 }
115
116
118
120 _bufferedOutput.write((byte)b);
121 }
122
123 public void write(byte b[]) throws IOException {
124 write(b, 0, b.length);
125 }
126
127 public void write(byte b[], int off, int len) throws IOException {
128 if (_closed) {
129 throw new IOException();
130 }
131
132
134
136 try {
137 _bufferedOutput.write(b, off, len);
138 }
139 catch (IOException ioe) {
140 _log.warn(ioe.getMessage());
141 }
142 }
143
144 public boolean closed() {
145 return _closed;
146 }
147
148 public void reset() {
149 }
150
151 private static final String _GZIP = "gzip";
152
153 private static Log _log = LogFactoryUtil.getLog(GZipStream.class);
154
155 private HttpServletResponse _response = null;
156 private ServletOutputStream _output = null;
157 private OutputStream _bufferedOutput = null;
158 private boolean _closed = false;
159
160 }