1 package jodd.servlet.filters; 2 3 import java.io.IOException; 4 import java.io.OutputStreamWriter; 5 import java.io.PrintWriter; 6 7 import javax.servlet.ServletOutputStream; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.HttpServletResponseWrapper; 10 11 15 16 public class GzipResponseWrapper extends HttpServletResponseWrapper { 17 18 24 public GzipResponseWrapper(HttpServletResponse response) { 25 super(response); 26 origResponse = response; 27 } 28 29 30 31 34 protected HttpServletResponse origResponse = null; 35 36 40 protected ServletOutputStream stream = null; 41 42 46 protected PrintWriter writer = null; 47 48 51 protected int threshold = 0; 52 53 56 protected String contentType = null; 57 58 60 61 66 public void setContentType(String contentType) { 67 this.contentType = contentType; 68 origResponse.setContentType(contentType); 69 } 70 71 76 public void setCompressionThreshold(int threshold) { 77 this.threshold = threshold; 78 } 79 80 88 public ServletOutputStream createOutputStream() throws IOException { 89 GzipResponseStream stream = new GzipResponseStream(origResponse); 90 stream.setBuffer(threshold); 91 return stream; 92 } 93 94 95 98 public void finishResponse() { 99 try { 100 if (writer != null) { 101 writer.close(); 102 } else { 103 if (stream != null) 104 stream.close(); 105 } 106 } catch (IOException e) { 107 } 108 } 109 110 112 113 119 public void flushBuffer() throws IOException { 120 if (stream != null) { 121 ((GzipResponseStream)stream).flush(); 122 } 123 } 124 125 135 public ServletOutputStream getOutputStream() throws IOException { 136 137 if (writer != null) { 138 throw new IllegalStateException("getWriter() has already been called for this response"); 139 } 140 if (stream == null) { 141 stream = createOutputStream(); 142 } 143 return(stream); 144 145 } 146 147 157 public PrintWriter getWriter() throws IOException { 158 159 if (writer != null) { 160 return writer; 161 } 162 163 if (stream != null) { 164 throw new IllegalStateException("getOutputStream() has already been called for this response"); 165 } 166 167 stream = createOutputStream(); 168 169 String charEnc = origResponse.getCharacterEncoding(); 170 if (charEnc != null) { 171 writer = new PrintWriter(new OutputStreamWriter(stream, charEnc)); 172 } else { 173 writer = new PrintWriter(stream); 174 } 175 return(writer); 176 } 177 178 179 public void setContentLength(int length) { 180 } 181 182 } 183 | Popular Tags |