KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > net > filter > GZIPFilter


1 /*
2  * Copyright 2003 Jayson Falkner (jayson@jspinsider.com)
3  * This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
4  * http://www.jspbook.com. You may freely use the code both commercially
5  * and non-commercially. If you like the code, please pick up a copy of
6  * the book and help support the authors, development of more free code,
7  * and the JSP/Servlet/J2EE community.
8  */

9 package org.snipsnap.net.filter;
10
11 import javax.servlet.Filter JavaDoc;
12 import javax.servlet.FilterChain JavaDoc;
13 import javax.servlet.FilterConfig JavaDoc;
14 import javax.servlet.ServletException JavaDoc;
15 import javax.servlet.ServletRequest JavaDoc;
16 import javax.servlet.ServletResponse JavaDoc;
17 import javax.servlet.http.HttpServletRequest JavaDoc;
18 import javax.servlet.http.HttpServletResponse JavaDoc;
19 import java.io.IOException JavaDoc;
20
21 public class GZIPFilter implements Filter JavaDoc {
22
23   public void doFilter(ServletRequest JavaDoc req, ServletResponse JavaDoc res,
24                        FilterChain JavaDoc chain) throws IOException JavaDoc, ServletException JavaDoc {
25     // only compress if this is a real http request and if it is HTTP/1.1+ and
26
// not included
27
if (req instanceof HttpServletRequest JavaDoc &&
28         !isHttp10(req) && !isIncludedRequest(req)) {
29       HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) req;
30       HttpServletResponse JavaDoc response = (HttpServletResponse JavaDoc) res;
31       String JavaDoc ae = request.getHeader("accept-encoding");
32       if (ae != null && ae.indexOf("gzip") != -1) {
33 // System.out.println("GZIP supported, compressing.");
34
GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response);
35         chain.doFilter(req, wrappedResponse);
36         wrappedResponse.finishResponse();
37         return;
38       }
39     }
40     chain.doFilter(req, res);
41   }
42
43   /**
44    * Check for old HTTP/1.0 protocol
45    *
46    * @param request the servlet request
47    * @return whether this is an old request
48    */

49   private boolean isHttp10(ServletRequest JavaDoc request) {
50     return "HTTP/1.0".equals(request.getProtocol());
51   }
52
53   /**
54    * Check for included requests by checking the corresponding request attribute
55    *
56    * @param request the servlet request
57    * @return true if the request was included
58    */

59   private boolean isIncludedRequest(ServletRequest JavaDoc request) {
60     return request.getAttribute("javax.servlet.include.request_uri") != null;
61   }
62
63
64   public void init(FilterConfig JavaDoc filterConfig) {
65     // noop
66
}
67
68   public void destroy() {
69     // noop
70
}
71 }
72
Popular Tags