001// Licensed under the Apache License, Version 2.0 (the "License");
002// you may not use this file except in compliance with the License.
003// You may obtain a copy of the License at
004//
005// http://www.apache.org/licenses/LICENSE-2.0
006//
007// Unless required by applicable law or agreed to in writing, software
008// distributed under the License is distributed on an "AS IS" BASIS,
009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
010// See the License for the specific language governing permissions and
011// limitations under the License.
012
013package org.apache.tapestry5.http.internal.services;
014
015import javax.servlet.http.HttpServletRequest;
016
017import org.apache.tapestry5.commons.util.CommonsUtils;
018import org.apache.tapestry5.http.ContentType;
019import org.apache.tapestry5.http.TapestryHttpConstants;
020import org.apache.tapestry5.http.TapestryHttpSymbolConstants;
021import org.apache.tapestry5.http.services.CompressionAnalyzer;
022import org.apache.tapestry5.http.services.ResponseCompressionAnalyzer;
023import org.apache.tapestry5.ioc.annotations.Symbol;
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(TapestryHttpSymbolConstants.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        // TAP5-2264:
056        if (request.getAttribute(TapestryHttpConstants.SUPPRESS_COMPRESSION) != null)
057        {
058            return false;
059        }
060
061        String supportedEncodings = request.getHeader("Accept-Encoding");
062
063        if (supportedEncodings == null)
064        {
065            return false;
066        }
067
068        for (String encoding : CommonsUtils.splitAtCommas(supportedEncodings))
069        {
070            if (encoding.equalsIgnoreCase("gzip"))
071            {
072                return true;
073            }
074        }
075
076        return false;
077    }
078
079    public boolean isGZipEnabled(ContentType contentType)
080    {
081        return isGZipSupported() && compressionAnalyzer.isCompressable(contentType.getMimeType());
082    }
083}