1
22
23 package com.liferay.portal.servlet.filters.compression;
24
25 import com.liferay.portal.kernel.log.Log;
26 import com.liferay.portal.kernel.log.LogFactoryUtil;
27 import com.liferay.portal.kernel.util.ByteArrayMaker;
28
29 import java.io.IOException;
30 import java.io.OutputStream;
31
32 import java.util.zip.GZIPOutputStream;
33
34 import javax.servlet.ServletOutputStream;
35 import javax.servlet.http.HttpServletResponse;
36
37
44 public class CompressionStream extends ServletOutputStream {
45
46 public CompressionStream(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 =
66 new GZIPOutputStream(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(_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 _CONTENT_ENCODING = "Content-Encoding";
143
144 private static final String _GZIP = "gzip";
145
146 private static Log _log = LogFactoryUtil.getLog(CompressionStream.class);
147
148 private HttpServletResponse _response = null;
149 private ServletOutputStream _output = null;
150 private OutputStream _bufferedOutput = null;
151 private boolean _closed = false;
152
153 }