001// Copyright 2009-2013 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.services;
016
017import javax.servlet.http.HttpServletRequest;
018
019import org.apache.tapestry5.SymbolConstants;
020import org.apache.tapestry5.internal.TapestryInternalUtils;
021import org.apache.tapestry5.ioc.annotations.Symbol;
022import org.apache.tapestry5.services.ResponseCompressionAnalyzer;
023import org.apache.tapestry5.services.assets.CompressionAnalyzer;
024
025public class ResponseCompressionAnalyzerImpl implements ResponseCompressionAnalyzer
026{
027    private final HttpServletRequest request;
028
029    private final boolean gzipCompressionEnabled;
030
031    private final CompressionAnalyzer compressionAnalyzer;
032
033    public ResponseCompressionAnalyzerImpl(HttpServletRequest request,
034                                           @Symbol(SymbolConstants.GZIP_COMPRESSION_ENABLED)
035                                           boolean gzipCompressionEnabled, CompressionAnalyzer compressionAnalyzer)
036    {
037        this.request = request;
038        this.gzipCompressionEnabled = gzipCompressionEnabled;
039        this.compressionAnalyzer = compressionAnalyzer;
040    }
041
042    public boolean isGZipSupported()
043    {
044        if (!gzipCompressionEnabled)
045        {
046            return false;
047        }
048
049        // TAP5-1880:
050        if (request.getProtocol() == "HTTP/1.0")
051        {
052            return false;
053        }
054
055        String supportedEncodings = request.getHeader("Accept-Encoding");
056
057        if (supportedEncodings == null)
058        {
059            return false;
060        }
061
062        for (String encoding : TapestryInternalUtils.splitAtCommas(supportedEncodings))
063        {
064            if (encoding.equalsIgnoreCase("gzip"))
065            {
066                return true;
067            }
068        }
069
070        return false;
071    }
072
073    public boolean isGZipEnabled(String contentType)
074    {
075        return isGZipSupported() && compressionAnalyzer.isCompressable(contentType);
076    }
077}