/
GzipHttpServletResponse.java
284 lines (230 loc) · 8.6 KB
/
GzipHttpServletResponse.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*
* Copyright 2016 OmniFaces
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.omnifaces.servlet;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
* This HTTP servlet response wrapper will GZIP the response when the given threshold has exceeded and the response
* content type matches one of the given mimetypes.
*
* @author Bauke Scholtz
* @since 1.1
*/
public class GzipHttpServletResponse extends HttpServletResponseOutputWrapper {
// Constants ------------------------------------------------------------------------------------------------------
private static final Pattern NO_TRANSFORM =
Pattern.compile("((.*)[\\s,])?no-transform([\\s,](.*))?", Pattern.CASE_INSENSITIVE);
// Properties -----------------------------------------------------------------------------------------------------
private int threshold;
private Set<String> mimetypes;
private long contentLength;
private String vary;
private boolean noGzip;
private boolean closing;
private GzipThresholdOutputStream output;
// Constructors ---------------------------------------------------------------------------------------------------
/**
* Construct a new GZIP HTTP servlet response based on the given wrapped response, threshold and mimetypes.
* @param wrapped The wrapped response.
* @param threshold The GZIP buffer threshold.
* @param mimetypes The mimetypes which needs to be compressed with GZIP.
*/
public GzipHttpServletResponse(HttpServletResponse wrapped, int threshold, Set<String> mimetypes) {
super(wrapped);
this.threshold = threshold;
this.mimetypes = mimetypes;
}
// Actions --------------------------------------------------------------------------------------------------------
@Override
public void setContentLength(int contentLength) {
// Get hold of content length locally to avoid it from being set on responses which will actually be gzipped.
this.contentLength = contentLength;
}
// @Override Servlet 3.1.
public void setContentLengthLong(long contentLength) {
// Get hold of content length locally to avoid it from being set on responses which will actually be gzipped.
this.contentLength = contentLength;
}
@Override
public void setHeader(String name, String value) {
super.setHeader(name, value);
if (name != null) {
String lowerCasedName = name.toLowerCase();
if ("vary".equals(lowerCasedName)) {
vary = value;
}
else if ("content-range".equals(lowerCasedName)) {
noGzip = (value != null);
}
else if ("cache-control".equals(lowerCasedName)) {
noGzip = (value != null && NO_TRANSFORM.matcher(value).matches());
}
}
}
@Override
public void addHeader(String name, String value) {
super.addHeader(name, value);
if (name != null && value != null) {
String lowerCasedName = name.toLowerCase();
if ("vary".equals(lowerCasedName)) {
vary = ((vary != null) ? (vary + ",") : "") + value;
}
else if ("content-range".equals(lowerCasedName)) {
noGzip = true;
}
else if ("cache-control".equals(lowerCasedName)) {
noGzip = (noGzip || NO_TRANSFORM.matcher(value).matches());
}
}
}
@Override
public void flushBuffer() throws IOException {
if (isCommitted()) {
super.flushBuffer();
}
}
@Override
public void reset() {
super.reset();
if (!isCommitted()) {
contentLength = 0;
vary = null;
noGzip = false;
if (output != null) {
output.reset();
}
}
}
@Override
public void close() throws IOException {
closing = true;
super.close();
closing = false;
}
@Override
protected OutputStream createOutputStream() {
output = new GzipThresholdOutputStream(threshold);
return output;
}
// Inner classes --------------------------------------------------------------------------------------------------
/**
* This output stream will switch to GZIP compression when the given threshold is exceeded.
* <p>
* This is an inner class because it needs to be able to manipulate the response headers once the decision whether
* to GZIP or not has been made.
*
* @author Bauke Scholtz
*/
private class GzipThresholdOutputStream extends OutputStream {
// Constants --------------------------------------------------------------------------------------------------
private static final String ERROR_CLOSED = "Stream is already closed.";
// Properties -------------------------------------------------------------------------------------------------
private byte[] thresholdBuffer;
private int thresholdLength;
private OutputStream output;
private boolean closed;
// Constructors -----------------------------------------------------------------------------------------------
public GzipThresholdOutputStream(int threshold) {
thresholdBuffer = new byte[threshold];
}
// Actions ----------------------------------------------------------------------------------------------------
@Override
public void write(int b) throws IOException {
write(new byte[] { (byte) b }, 0, 1);
}
@Override
public void write(byte[] bytes) throws IOException {
write(bytes, 0, bytes.length);
}
@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
checkClosed();
if (length == 0) {
return;
}
if (output == null) {
if ((length - offset) <= (thresholdBuffer.length - thresholdLength)) {
System.arraycopy(bytes, offset, thresholdBuffer, thresholdLength, length);
thresholdLength += length;
return;
}
else {
// Threshold buffer has exceeded. Now use GZIP if possible.
output = createGzipOutputStreamIfNecessary(true);
output.write(thresholdBuffer, 0, thresholdLength);
}
}
output.write(bytes, offset, length);
}
@Override
public void flush() throws IOException {
checkClosed();
if (output != null) {
output.flush();
}
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
if (output == null) {
// Threshold buffer hasn't exceeded. Use normal output stream.
setContentLength(thresholdLength);
output = createGzipOutputStreamIfNecessary(false);
output.write(thresholdBuffer, 0, thresholdLength);
}
output.close();
closed = true;
}
public void reset() {
thresholdLength = 0;
output = null;
}
// Helpers ----------------------------------------------------------------------------------------------------
/**
* Create GZIP output stream if necessary. That is, when the given <code>gzip</code> argument is
* <code>true</code>, the current response does not have the <code>Cache-Control: no-transform</code> or
* <code>Content-Range</code> headers, the current response is not committed, the content type is not
* <code>null</code> and the content type matches one of the mimetypes.
*/
private OutputStream createGzipOutputStreamIfNecessary(boolean gzip) throws IOException {
HttpServletResponse originalResponse = (HttpServletResponse) getResponse();
if (gzip && !noGzip && (closing || !isCommitted())) {
String contentType = getContentType();
if (contentType != null && mimetypes.contains(contentType.split(";", 2)[0])) {
addHeader("Content-Encoding", "gzip");
setHeader("Vary", ((vary != null && !vary.equals("*")) ? (vary + ",") : "") + "Accept-Encoding");
return new GZIPOutputStream(originalResponse.getOutputStream());
}
}
if (contentLength > 0) {
originalResponse.setHeader("Content-Length", String.valueOf(contentLength));
}
return originalResponse.getOutputStream();
}
/**
* Check if the current stream is closed and if so, then throw IO exception.
* @throws IOException When the current stream is closed.
*/
private void checkClosed() throws IOException {
if (closed) {
throw new IOException(ERROR_CLOSED);
}
}
}
}