    001    // Copyright 2009, 2010 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.internal.InternalConstants;
    018    import org.apache.tapestry5.services.ResponseCompressionAnalyzer;
    019
    020    import javax.servlet.ServletOutputStream;
    021    import javax.servlet.http.HttpServletRequest;
    022    import javax.servlet.http.HttpServletResponse;
    023    import javax.servlet.http.HttpServletResponseWrapper;
    024    import java.io.IOException;
    025
    026    public class GZIPEnabledResponse extends HttpServletResponseWrapper
    027    {
    028        private final int cutover;
    029
    030        private final HttpServletRequest request;
    031
    032        private final HttpServletResponse response;
    033
    034        private final ResponseCompressionAnalyzer analyzer;
    035
    036        private boolean contentLengthSet = false;
    037
    038        public GZIPEnabledResponse(HttpServletResponse response, HttpServletRequest request, int cutover,
    039                ResponseCompressionAnalyzer analyzer)
    040        {
    041            super(response);
    042
    043            this.request = request;
    044            this.response = response;
    045            this.cutover = cutover;
    046            this.analyzer = analyzer;
    047        }
    048
    049        public void setContentLength(int len)
    050        {
    051            super.setContentLength(len);
    052
    053            contentLengthSet = true;
    054        }
    055
    056        @Override
    057        public ServletOutputStream getOutputStream() throws IOException
    058        {
    059            if (contentLengthSet || isCompressionDisabled())
    060                return super.getOutputStream();
    061
    062            String contentType = getContentType();
    063
    064            return new BufferedGZipOutputStream(contentType, response, cutover, analyzer);
    065        }
    066
    067        private boolean isCompressionDisabled()
    068        {
    069            return request.getAttribute(InternalConstants.SUPPRESS_COMPRESSION) != null;
    070        }
    071    }