View Javadoc
1   /*
2    * Copyright (c) 2014, Dienst Landelijk Gebied - Ministerie van Economische Zaken
3    * 
4    * Gepubliceerd onder de BSD 2-clause licentie, 
5    * zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie.
6    */
7   package nl.mineleni.cbsviewer.servlet;
8   
9   import java.io.IOException;
10  
11  import javax.servlet.Filter;
12  import javax.servlet.FilterChain;
13  import javax.servlet.FilterConfig;
14  import javax.servlet.ServletException;
15  import javax.servlet.ServletRequest;
16  import javax.servlet.ServletResponse;
17  import javax.servlet.http.HttpServletRequest;
18  import javax.servlet.http.HttpServletResponse;
19  
20  import org.apache.http.HttpHeaders;
21  
22  /**
23   * Eenvoudige GZip compressie filter ter optimalisatie van bandbreedte.
24   * 
25   * @author prinsmc
26   *
27   */
28  public class GZipFilter implements Filter {
29  
30  	/**
31  	 * Comprimeert de response met GZip mits de clinet aangeeft dat die gzip
32  	 * accepteert.
33  	 * 
34  	 * {@inheritDoc}
35  	 * 
36  	 * @param request
37  	 *            het request
38  	 * @param response
39  	 *            de response
40  	 * @param chain
41  	 *            de filter chain
42  	 * @throws IOException
43  	 *             Signals that an I/O exception has occurred.
44  	 * @throws ServletException
45  	 *             the servlet exception
46  	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
47  	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
48  	 * 
49  	 * 
50  	 */
51  	@Override
52  	public void doFilter(final ServletRequest request,
53  			final ServletResponse response, final FilterChain chain)
54  			throws IOException, ServletException {
55  		HttpServletRequest httpRequest = (HttpServletRequest) request;
56  		HttpServletResponse httpResponse = (HttpServletResponse) response;
57  		String acceptEncoding = httpRequest
58  				.getHeader(HttpHeaders.ACCEPT_ENCODING);
59  		if (acceptEncoding != null) {
60  			if (acceptEncoding.indexOf("gzip") >= 0) {
61  				GZIPHttpServletResponseWrapper gzipResponse = new GZIPHttpServletResponseWrapper(
62  						httpResponse);
63  				chain.doFilter(request, gzipResponse);
64  				gzipResponse.finish();
65  				return;
66  			}
67  		}
68  		chain.doFilter(request, response);
69  	}
70  
71  	/*
72  	 * (non-Javadoc)
73  	 * 
74  	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
75  	 */
76  	@Override
77  	public void init(final FilterConfig filterConfig) throws ServletException {
78  		// do nothing
79  	}
80  
81  	/*
82  	 * (non-Javadoc)
83  	 * 
84  	 * @see javax.servlet.Filter#destroy()
85  	 */
86  	@Override
87  	public void destroy() {
88  		// do nothing
89  	}
90  }