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