Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c9976e47958eed78c7a5672df27d1c94b43f728f (plain) (blame)
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.servlets.gzip;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;

import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

/* ------------------------------------------------------------ */
/**
 * GZIP Handler This handler will gzip the content of a response if:
 * <ul>
 * <li>The handler is mapped to a matching path</li>
 * <li>The response status code is >=200 and <300
 * <li>The content length is unknown or more than the <code>minGzipSize</code> initParameter or the minGzipSize is 0(default)</li>
 * <li>The content-type matches one of the set of mimetypes to be compressed</li>
 * <li>The content-type does NOT match one of the set of mimetypes AND setExcludeMimeTypes is <code>true</code></li>
 * <li>No content-encoding is specified by the resource</li>
 * </ul>
 *
 * <p>
 * Compressing the content can greatly improve the network bandwidth usage, but at a cost of memory and CPU cycles. If this handler is used for static content,
 * then use of efficient direct NIO may be prevented, thus use of the gzip mechanism of the <code>org.eclipse.jetty.servlet.DefaultServlet</code> is advised instead.
 * </p>
 */
public class GzipHandler extends HandlerWrapper
{
    private static final Logger LOG = Log.getLogger(GzipHandler.class);

    final protected Set<String> _mimeTypes=new HashSet<>();
    protected boolean _excludeMimeTypes=false;
    protected Set<String> _excludedUA;
    protected int _bufferSize = 8192;
    protected int _minGzipSize = 256;
    protected String _vary = "Accept-Encoding, User-Agent";

    /* ------------------------------------------------------------ */
    /**
     * Instantiates a new gzip handler.
     */
    public GzipHandler()
    {
    }

    /* ------------------------------------------------------------ */
    /**
     * Get the mime types.
     *
     * @return mime types to set
     */
    public Set<String> getMimeTypes()
    {
        return _mimeTypes;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the mime types.
     *
     * @param mimeTypes
     *            the mime types to set
     */
    public void setMimeTypes(Set<String> mimeTypes)
    {
        _excludeMimeTypes=false;
        _mimeTypes.clear();
        _mimeTypes.addAll(mimeTypes);
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the mime types.
     *
     * @param mimeTypes
     *            the mime types to set
     */
    public void setMimeTypes(String mimeTypes)
    {
        if (mimeTypes != null)
        {
            _excludeMimeTypes=false;
            _mimeTypes.clear();
            StringTokenizer tok = new StringTokenizer(mimeTypes,",",false);
            while (tok.hasMoreTokens())
            {
                _mimeTypes.add(tok.nextToken());
            }
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the mime types.
     */
    public void setExcludeMimeTypes(boolean exclude)
    {
        _excludeMimeTypes=exclude;
    }

    /* ------------------------------------------------------------ */
    /**
     * Get the excluded user agents.
     *
     * @return excluded user agents
     */
    public Set<String> getExcluded()
    {
        return _excludedUA;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the excluded user agents.
     *
     * @param excluded
     *            excluded user agents to set
     */
    public void setExcluded(Set<String> excluded)
    {
        _excludedUA = excluded;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the excluded user agents.
     *
     * @param excluded
     *            excluded user agents to set
     */
    public void setExcluded(String excluded)
    {
        if (excluded != null)
        {
            _excludedUA = new HashSet<String>();
            StringTokenizer tok = new StringTokenizer(excluded,",",false);
            while (tok.hasMoreTokens())
                _excludedUA.add(tok.nextToken());
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * @return The value of the Vary header set if a response can be compressed.
     */
    public String getVary()
    {
        return _vary;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the value of the Vary header sent with responses that could be compressed.  
     * <p>
     * By default it is set to 'Accept-Encoding, User-Agent' since IE6 is excluded by 
     * default from the excludedAgents. If user-agents are not to be excluded, then 
     * this can be set to 'Accept-Encoding'.  Note also that shared caches may cache 
     * many copies of a resource that is varied by User-Agent - one per variation of the 
     * User-Agent, unless the cache does some normalization of the UA string.
     * @param vary The value of the Vary header set if a response can be compressed.
     */
    public void setVary(String vary)
    {
        _vary = vary;
    }

    /* ------------------------------------------------------------ */
    /**
     * Get the buffer size.
     *
     * @return the buffer size
     */
    public int getBufferSize()
    {
        return _bufferSize;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the buffer size.
     *
     * @param bufferSize
     *            buffer size to set
     */
    public void setBufferSize(int bufferSize)
    {
        _bufferSize = bufferSize;
    }

    /* ------------------------------------------------------------ */
    /**
     * Get the minimum reponse size.
     *
     * @return minimum reponse size
     */
    public int getMinGzipSize()
    {
        return _minGzipSize;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the minimum reponse size.
     *
     * @param minGzipSize
     *            minimum reponse size
     */
    public void setMinGzipSize(int minGzipSize)
    {
        _minGzipSize = minGzipSize;
    }
    
    /* ------------------------------------------------------------ */
    @Override
    protected void doStart() throws Exception
    {
        if (_mimeTypes.size()==0 && _excludeMimeTypes)
        {
            _excludeMimeTypes = true;
            for (String type:MimeTypes.getKnownMimeTypes())
            {
                if (type.equals("image/svg+xml")) //always compressable (unless .svgz file)
                    continue;
                if (type.startsWith("image/")||
                    type.startsWith("audio/")||
                    type.startsWith("video/"))
                    _mimeTypes.add(type);
            }
            _mimeTypes.add("application/compress");
            _mimeTypes.add("application/zip");
            _mimeTypes.add("application/gzip");
        }
        super.doStart();
    }

    /* ------------------------------------------------------------ */
    /**
     * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        if (_handler!=null && isStarted())
        {
            String ae = request.getHeader("accept-encoding");
            if (ae != null && ae.indexOf("gzip")>=0 && !response.containsHeader("Content-Encoding")
                    && !HttpMethod.HEAD.is(request.getMethod()))
            {
                if (_excludedUA!=null)
                {
                    String ua = request.getHeader("User-Agent");
                    if (_excludedUA.contains(ua))
                    {
                        _handler.handle(target,baseRequest, request, response);
                        return;
                    }
                }

                final CompressedResponseWrapper wrappedResponse = newGzipResponseWrapper(request,response);

                boolean exceptional=true;
                try
                {
                    _handler.handle(target, baseRequest, request, wrappedResponse);
                    exceptional=false;
                }
                finally
                {
                    if (request.isAsyncStarted())
                    {
                        request.getAsyncContext().addListener(new AsyncListener()
                        {
                            
                            @Override
                            public void onTimeout(AsyncEvent event) throws IOException
                            {
                            }
                            
                            @Override
                            public void onStartAsync(AsyncEvent event) throws IOException
                            {
                            }
                            
                            @Override
                            public void onError(AsyncEvent event) throws IOException
                            {
                            }
                            
                            @Override
                            public void onComplete(AsyncEvent event) throws IOException
                            {
                                try
                                {
                                    wrappedResponse.finish();
                                }
                                catch(IOException e)
                                {
                                    LOG.warn(e);
                                }
                            }
                        });
                    }
                    else if (exceptional && !response.isCommitted())
                    {
                        wrappedResponse.resetBuffer();
                        wrappedResponse.noCompression();
                    }
                    else
                        wrappedResponse.finish();
                }
            }
            else
            {
                _handler.handle(target,baseRequest, request, response);
            }
        }
    }

    /**
     * Allows derived implementations to replace ResponseWrapper implementation.
     *
     * @param request the request
     * @param response the response
     * @return the gzip response wrapper
     */
    protected CompressedResponseWrapper newGzipResponseWrapper(HttpServletRequest request, HttpServletResponse response)
    {
        return new CompressedResponseWrapper(request,response)
        {
            {
                super.setMimeTypes(GzipHandler.this._mimeTypes,GzipHandler.this._excludeMimeTypes);
                super.setBufferSize(GzipHandler.this._bufferSize);
                super.setMinCompressSize(GzipHandler.this._minGzipSize);
            }

            @Override
            protected AbstractCompressedStream newCompressedStream(HttpServletRequest request,HttpServletResponse response) throws IOException
            {
                return new AbstractCompressedStream("gzip",request,this,_vary)
                {
                    @Override
                    protected DeflaterOutputStream createStream() throws IOException
                    {
                        return new GZIPOutputStream(_response.getOutputStream(),_bufferSize);
                    }
                };
            }

            @Override
            protected PrintWriter newWriter(OutputStream out,String encoding) throws UnsupportedEncodingException
            {
                return GzipHandler.this.newWriter(out,encoding);
            }
        };
    }

    /**
     * Allows derived implementations to replace PrintWriter implementation.
     *
     * @param out the out
     * @param encoding the encoding
     * @return the prints the writer
     * @throws UnsupportedEncodingException
     */
    protected PrintWriter newWriter(OutputStream out,String encoding) throws UnsupportedEncodingException
    {
        return encoding==null?new PrintWriter(out):new PrintWriter(new OutputStreamWriter(out,encoding));
    }
}

Back to the top