1
14
15 package com.liferay.portal.servlet.filters.gzip;
16
17 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
18 import com.liferay.portal.kernel.log.Log;
19 import com.liferay.portal.kernel.log.LogFactoryUtil;
20 import com.liferay.portal.kernel.servlet.HttpHeaders;
21
22 import java.io.IOException;
23
24 import java.util.zip.GZIPOutputStream;
25
26 import javax.servlet.ServletOutputStream;
27 import javax.servlet.http.HttpServletResponse;
28
29
36 public class GZipStream extends ServletOutputStream {
37
38 public GZipStream(HttpServletResponse response) throws IOException {
39 super();
40
41 _response = response;
42 _outputStream = response.getOutputStream();
43 _unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();
44 _gzipOutputStream = new GZIPOutputStream(_unsyncByteArrayOutputStream);
45 }
46
47 public void close() throws IOException {
48 if (_closed) {
49 throw new IOException();
50 }
51
52 _gzipOutputStream.finish();
53
54 int contentLength = _unsyncByteArrayOutputStream.size();
55
56 _response.setContentLength(contentLength);
57 _response.addHeader(HttpHeaders.CONTENT_ENCODING, _GZIP);
58
59 _outputStream.write(
60 _unsyncByteArrayOutputStream.unsafeGetByteArray(), 0,
61 contentLength);
62
63 _outputStream.flush();
64 _outputStream.close();
65
66 _closed = true;
67 }
68
69 public boolean closed() {
70 return _closed;
71 }
72
73 public void flush() throws IOException {
74 if (_closed) {
75 throw new IOException();
76 }
77
78 _gzipOutputStream.flush();
79 }
80
81 public void reset() {
82 }
83
84 public void write(byte b[]) throws IOException {
85 write(b, 0, b.length);
86 }
87
88 public void write(byte b[], int off, int len) throws IOException {
89 if (_closed) {
90 throw new IOException();
91 }
92
93
95
97 try {
98 _gzipOutputStream.write(b, off, len);
99 }
100 catch (IOException ioe) {
101 _log.warn(ioe.getMessage());
102 }
103 }
104
105 public void write(int b) throws IOException {
106 if (_closed) {
107 throw new IOException();
108 }
109
110
112
114 _gzipOutputStream.write((byte)b);
115 }
116
117 private static final String _GZIP = "gzip";
118
119 private static Log _log = LogFactoryUtil.getLog(GZipStream.class);
120
121 private boolean _closed;
122 private GZIPOutputStream _gzipOutputStream;
123 private ServletOutputStream _outputStream;
124 private HttpServletResponse _response;
125 private UnsyncByteArrayOutputStream _unsyncByteArrayOutputStream;
126
127 }