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