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