KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > myvietnam > mvncore > servlet > filter > CompressionFilter


1 /*
2  * CompressionFilter.java
3  * $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/servlet/filter/CompressionFilter.java,v 1.6 2004/12/12 18:05:35 minhnn Exp $
4  * $Revision: 1.6 $
5  * $Date: 2004/12/12 18:05:35 $
6  *
7  * ====================================================================
8  *
9  * The Apache Software License, Version 1.1
10  *
11  * Copyright (c) 1999 The Apache Software Foundation. All rights
12  * reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  *
18  * 1. Redistributions of source code must retain the above copyright
19  * notice, this list of conditions and the following disclaimer.
20  *
21  * 2. Redistributions in binary form must reproduce the above copyright
22  * notice, this list of conditions and the following disclaimer in
23  * the documentation and/or other materials provided with the
24  * distribution.
25  *
26  * 3. The end-user documentation included with the redistribution, if
27  * any, must include the following acknowlegement:
28  * "This product includes software developed by the
29  * Apache Software Foundation (http://www.apache.org/)."
30  * Alternately, this acknowlegement may appear in the software itself,
31  * if and wherever such third-party acknowlegements normally appear.
32  *
33  * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
34  * Foundation" must not be used to endorse or promote products derived
35  * from this software without prior written permission. For written
36  * permission, please contact apache@apache.org.
37  *
38  * 5. Products derived from this software may not be called "Apache"
39  * nor may "Apache" appear in their names without prior written
40  * permission of the Apache Group.
41  *
42  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
43  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
44  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
45  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
46  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
47  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
48  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
49  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
50  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
51  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
52  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  * ====================================================================
55  *
56  * This software consists of voluntary contributions made by many
57  * individuals on behalf of the Apache Software Foundation. For more
58  * information on the Apache Software Foundation, please see
59  * <http://www.apache.org/>.
60  *
61  * [Additional notices, if required by prior licensing conditions]
62  *
63  */

64
65 package net.myvietnam.mvncore.servlet.filter;
66
67 import java.io.IOException JavaDoc;
68 import java.util.Enumeration JavaDoc;
69
70 import javax.servlet.*;
71 import javax.servlet.http.HttpServletRequest JavaDoc;
72 import javax.servlet.http.HttpServletResponse JavaDoc;
73
74 import org.apache.commons.logging.Log;
75 import org.apache.commons.logging.LogFactory;
76
77
78 /**
79  * Implementation of <code>javax.servlet.Filter</code> used to compress
80  * the ServletResponse if it is bigger than a threshold.
81  *
82  * @author Amy Roh
83  * @author Dmitri Valdin
84  * @version $Revision: 1.6 $, $Date: 2004/12/12 18:05:35 $
85  */

86
87 public class CompressionFilter implements Filter{
88
89     private static Log log = LogFactory.getLog(CompressionFilter.class);
90
91     /**
92      * The filter configuration object we are associated with. If this value
93      * is null, this filter instance is not currently configured.
94      */

95     private FilterConfig config = null;
96
97     /**
98      * Minimal reasonable threshold
99      */

100     private int minThreshold = 128;
101
102
103     /**
104      * The threshold number to compress
105      */

106     protected int compressionThreshold;
107
108     /**
109      * Debug level for this filter
110      */

111 // private int debug = 0;
112

113     /**
114      * Place this filter into service.
115      *
116      * @param filterConfig The filter configuration object
117      */

118
119     public void init(FilterConfig filterConfig) {
120
121         config = filterConfig;
122         if (filterConfig != null) {
123             /*
124             String value = filterConfig.getInitParameter("debug");
125             if (value!=null) {
126                 debug = Integer.parseInt(value);
127             } else {
128                 debug = 0;
129             }*/

130             String JavaDoc str = filterConfig.getInitParameter("compressionThreshold");
131             if (str!=null) {
132                 compressionThreshold = Integer.parseInt(str);
133                 if (compressionThreshold != 0 && compressionThreshold < minThreshold) {
134                     log.info("compressionThreshold should be either 0 - no compression or >= " + minThreshold);
135                     log.info("compressionThreshold set to " + minThreshold);
136                     compressionThreshold = minThreshold;
137                 }
138             } else {
139                 compressionThreshold = 0;
140             }
141
142         } else {
143             compressionThreshold = 0;
144         }
145
146     }
147
148     /**
149     * Take this filter out of service.
150     */

151     public void destroy() {
152
153         this.config = null;
154
155     }
156
157     /**
158      * The <code>doFilter</code> method of the Filter is called by the container
159      * each time a request/response pair is passed through the chain due
160      * to a client request for a resource at the end of the chain.
161      * The FilterChain passed into this method allows the Filter to pass on the
162      * request and response to the next entity in the chain.<p>
163      * This method first examines the request to check whether the client support
164      * compression. <br>
165      * It simply just pass the request and response if there is no support for
166      * compression.<br>
167      * If the compression support is available, it creates a
168      * CompressionServletResponseWrapper object which compresses the content and
169      * modifies the header if the content length is big enough.
170      * It then invokes the next entity in the chain using the FilterChain object
171      * (<code>chain.doFilter()</code>), <br>
172      **/

173
174     public void doFilter ( ServletRequest JavaDoc request, ServletResponse JavaDoc response, FilterChain chain )
175         throws IOException JavaDoc, ServletException {
176         /*
177         Currently, many browsers do not send character encoding information in the
178         Content-Type header of an HTTP request. If an encoding has not been specified
179         by the client request, the container uses a default encoding to parse request
180         parameters. If the client hasn't set character encoding and the request parameters
181         are encoded with a different encoding than the default, the parameters will be
182         parsed incorrectly. You can use the method setCharacterEncoding in ServletRequest
183         interface to set the encoding. Since this method must be called
184         prior to parsing any post data or reading any input from the request, this function
185         is a prime application for filters(http://java.sun.com/products/servlet/Filters.pdf.)
186         In this case, it may be caused by parsing parameter "gzip". And charset should be UTF-8.
187         You can use another filter for the encoding.(see Tomcat's examples)
188
189         */

190         request.setCharacterEncoding("utf-8");
191         if (compressionThreshold == 0) {
192             //log.trace("doFilter gets called, but compressionTreshold is set to 0 - no compression");
193
chain.doFilter(request, response);
194             return;
195         }
196         boolean supportCompression = false;
197         if (request instanceof HttpServletRequest JavaDoc) {
198             //log.trace("requestURI = " + ((HttpServletRequest)request).getRequestURI());
199

200             // Are we allowed to compress ?
201
String JavaDoc s = request.getParameter("gzip");
202             if ("false".equals(s)) {
203                 //log.trace("got parameter gzip=false --> don't compress, just chain filter");
204
chain.doFilter(request, response);
205                 return;
206             }
207
208             Enumeration JavaDoc e =
209                 ((HttpServletRequest JavaDoc)request).getHeaders("Accept-Encoding");
210             while (e.hasMoreElements()) {
211                 String JavaDoc name = (String JavaDoc)e.nextElement();
212                 if (name.indexOf("gzip") != -1) {
213                     //log.trace("supports compression");
214
supportCompression = true;
215                 } else {
216                     //log.trace("no support for compresion");
217
}
218             }
219         }
220
221         if (!supportCompression) {
222             //log.trace("doFilter gets called wo compression");
223
chain.doFilter(request, response);
224             return;
225         } else {
226             if (response instanceof HttpServletResponse JavaDoc) {
227                 CompressionServletResponseWrapper wrappedResponse =
228                     new CompressionServletResponseWrapper((HttpServletResponse JavaDoc)response);
229                 //minhnn
230
//wrappedResponse.setDebugLevel(debug);
231
wrappedResponse.setCompressionThreshold(compressionThreshold);
232                 //log.trace("doFilter gets called with compression");
233
try {
234                     chain.doFilter(request, wrappedResponse);
235                 } finally {
236                     wrappedResponse.finishResponse();
237                 }
238                 return;
239             }
240         }
241     }
242
243     /**
244      * Set filter config
245      * This function is equivalent to init. Required by Weblogic 6.1
246      *
247      * @param filterConfig The filter configuration object
248      */

249     public void setFilterConfig(FilterConfig filterConfig) {
250         init(filterConfig);
251     }
252
253     /**
254      * Return filter config
255      * Required by Weblogic 6.1
256      */

257     public FilterConfig getFilterConfig() {
258         return config;
259     }
260
261 }
262
263
Popular Tags