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