1 package jodd.servlet.filters; 2 3 import java.io.IOException; 4 import java.util.zip.GZIPOutputStream; 5 6 import javax.servlet.ServletOutputStream; 7 import javax.servlet.http.HttpServletResponse; 8 9 10 11 public class GzipResponseStream extends ServletOutputStream { 12 13 20 public GzipResponseStream(HttpServletResponse response) throws IOException { 21 super(); 22 closed = false; 23 this.response = response; 24 this.output = response.getOutputStream(); 25 } 26 27 28 31 protected int compressionThreshold = 0; 32 33 36 protected byte[] buffer = null; 37 38 41 protected int bufferCount = 0; 42 43 46 protected GZIPOutputStream gzipstream = null; 47 48 51 protected boolean closed = false; 52 53 57 protected int length = -1; 58 59 62 protected HttpServletResponse response = null; 63 64 67 protected ServletOutputStream output = null; 68 69 70 71 76 protected void setBuffer(int threshold) { 77 compressionThreshold = threshold; 78 buffer = new byte[compressionThreshold]; 79 } 80 81 87 public void close() throws IOException { 88 if (closed == true) { 89 return; 90 } 91 if (gzipstream != null) { 92 flushToGZip(); 93 gzipstream.close(); 94 gzipstream = null; 95 } else { 96 if (bufferCount > 0) { 97 output.write(buffer, 0, bufferCount); 98 bufferCount = 0; 99 } 100 } 101 output.close(); 102 closed = true; 103 } 104 105 106 112 public void flush() throws IOException { 113 114 if (closed) { 115 return; 116 } 117 if (gzipstream != null) { 118 gzipstream.flush(); 119 } 120 121 } 122 123 public void flushToGZip() throws IOException { 124 if (bufferCount > 0) { 125 writeToGZip(buffer, 0, bufferCount); 126 bufferCount = 0; 127 } 128 } 129 130 138 public void write(int b) throws IOException { 139 140 if (closed) { 141 throw new IOException("Cannot write to a closed output stream"); 142 } 143 if (bufferCount >= buffer.length) { 144 flushToGZip(); 145 } 146 buffer[bufferCount++] = (byte) b; 147 } 148 149 150 159 public void write(byte b[]) throws IOException { 160 write(b, 0, b.length); 161 } 162 163 164 175 public void write(byte b[], int off, int len) throws IOException { 176 177 if (closed) { 178 throw new IOException("Cannot write to a closed output stream"); 179 } 180 181 if (len == 0) { 182 return; 183 } 184 185 if (len <= (buffer.length - bufferCount)) { 187 System.arraycopy(b, off, buffer, bufferCount, len); 188 bufferCount += len; 189 return; 190 } 191 192 flushToGZip(); 194 195 if (len <= (buffer.length - bufferCount)) { 197 System.arraycopy(b, off, buffer, bufferCount, len); 198 bufferCount += len; 199 return; 200 } 201 202 writeToGZip(b, off, len); 204 } 205 206 public void writeToGZip(byte b[], int off, int len) throws IOException { 207 208 if (gzipstream == null) { 209 gzipstream = new GZIPOutputStream(output); 210 response.addHeader("Content-Encoding", "gzip"); 211 } 212 gzipstream.write(b, off, len); 213 214 } 215 216 217 222 public boolean closed() { 223 return(this.closed); 224 } 225 226 } 227 | Popular Tags |