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