    001// Copyright 2009, 2012 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
    015package org.apache.tapestry5.http.internal.gzip;
    016
    017import java.io.IOException;
    018
    019import javax.servlet.http.HttpServletRequest;
    020import javax.servlet.http.HttpServletResponse;
    021
    022import org.apache.tapestry5.http.TapestryHttpSymbolConstants;
    023import org.apache.tapestry5.http.services.CompressionAnalyzer;
    024import org.apache.tapestry5.http.services.HttpServletRequestFilter;
    025import org.apache.tapestry5.http.services.HttpServletRequestHandler;
    026import org.apache.tapestry5.http.services.ResponseCompressionAnalyzer;
    027import org.apache.tapestry5.ioc.annotations.Symbol;
    028
    029/**
    030 * Filter that adds GZIP compression to the response, if the client supports it.
    031 */
    032public class GZipFilter implements HttpServletRequestFilter
    033{
    034    private final int cutover;
    035
    036    private final ResponseCompressionAnalyzer responseAnalyzer;
    037
    038    private final CompressionAnalyzer compressionAnalyzer;
    039
    040    public GZipFilter(
    041            @Symbol(TapestryHttpSymbolConstants.MIN_GZIP_SIZE)
    042            int cutover,
    043
    044            ResponseCompressionAnalyzer responseAnalyzer,
    045
    046            CompressionAnalyzer compressionAnalyzer)
    047    {
    048        this.cutover = cutover;
    049        this.responseAnalyzer = responseAnalyzer;
    050        this.compressionAnalyzer = compressionAnalyzer;
    051    }
    052
    053    public boolean service(HttpServletRequest request, HttpServletResponse response, HttpServletRequestHandler handler)
    054            throws IOException
    055    {
    056        HttpServletResponse newResponse = responseAnalyzer.isGZipSupported()
    057                ? new GZIPEnabledResponse(response, request, cutover, compressionAnalyzer)
    058                : response;
    059
    060        return handler.service(request, newResponse);
    061    }
    062}