    001    // Copyright 2009 The Apache Software Foundation
    002    //
    003    // Licensed under the Apache License, Version 2.0 (the "License");
    004    // you may not use this file except in compliance with the License.
    005    // You may obtain a copy of the License at
    006    //
    007    //     http://www.apache.org/licenses/LICENSE-2.0
    008    //
    009    // Unless required by applicable law or agreed to in writing, software
    010    // distributed under the License is distributed on an "AS IS" BASIS,
    011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    012    // See the License for the specific language governing permissions and
    013    // limitations under the License.
    014
    015    package org.apache.tapestry5.internal.gzip;
    016
    017    import org.apache.tapestry5.SymbolConstants;
    018    import org.apache.tapestry5.ioc.annotations.Symbol;
    019    import org.apache.tapestry5.services.HttpServletRequestFilter;
    020    import org.apache.tapestry5.services.HttpServletRequestHandler;
    021    import org.apache.tapestry5.services.ResponseCompressionAnalyzer;
    022
    023    import javax.servlet.http.HttpServletRequest;
    024    import javax.servlet.http.HttpServletResponse;
    025    import java.io.IOException;
    026
    027    /**
    028     * Filter that adds GZIP compression to the response, if the client supports it.
    029     */
    030    public class GZipFilter implements HttpServletRequestFilter
    031    {
    032        private final int cutover;
    033
    034        private final ResponseCompressionAnalyzer analyzer;
    035
    036        public GZipFilter(
    037                @Symbol(SymbolConstants.MIN_GZIP_SIZE)
    038                int cutover,
    039
    040                ResponseCompressionAnalyzer analyzer)
    041        {
    042            this.cutover = cutover;
    043            this.analyzer = analyzer;
    044        }
    045
    046        public boolean service(HttpServletRequest request, HttpServletResponse response, HttpServletRequestHandler handler)
    047                throws IOException
    048        {
    049            HttpServletResponse newResponse = analyzer.isGZipSupported()
    050                                              ? new GZIPEnabledResponse(response, request, cutover, analyzer)
    051                                              : response;
    052
    053            return handler.service(request, newResponse);
    054        }
    055    }