1 3 package jodd.servlet.filter; 4 5 import java.io.IOException ; 6 import java.util.zip.GZIPOutputStream ; 7 8 import javax.servlet.ServletOutputStream ; 9 import javax.servlet.http.HttpServletResponse ; 10 11 12 13 public class GzipResponseStream extends ServletOutputStream { 14 15 22 public GzipResponseStream(HttpServletResponse response) throws IOException { 23 super(); 24 closed = false; 25 this.response = response; 26 this.output = response.getOutputStream(); 27 } 28 29 30 33 protected int compressionThreshold = 0; 34 35 38 protected byte[] buffer = null; 39 40 43 protected int bufferCount = 0; 44 45 48 protected GZIPOutputStream gzipstream = null; 49 50 53 protected boolean closed = false; 54 55 59 protected int length = -1; 60 61 64 protected HttpServletResponse response = null; 65 66 69 protected ServletOutputStream output = null; 70 71 72 73 78 protected void setBuffer(int threshold) { 79 compressionThreshold = threshold; 80 buffer = new byte[compressionThreshold]; 81 } 82 83 89 public void close() throws IOException { 90 if (closed == true) { 91 return; 92 } 93 if (gzipstream != null) { 94 flushToGZip(); 95 gzipstream.close(); 96 gzipstream = null; 97 } else { 98 if (bufferCount > 0) { 99 output.write(buffer, 0, bufferCount); 100 bufferCount = 0; 101 } 102 } 103 output.close(); 104 closed = true; 105 } 106 107 108 114 public void flush() throws IOException { 115 116 if (closed) { 117 return; 118 } 119 if (gzipstream != null) { 120 gzipstream.flush(); 121 } 122 123 } 124 125 public void flushToGZip() throws IOException { 126 if (bufferCount > 0) { 127 writeToGZip(buffer, 0, bufferCount); 128 bufferCount = 0; 129 } 130 } 131 132 140 public void write(int b) throws IOException { 141 142 if (closed) { 143 throw new IOException ("Cannot write to a closed output stream"); 144 } 145 if (bufferCount >= buffer.length) { 146 flushToGZip(); 147 } 148 buffer[bufferCount++] = (byte) b; 149 } 150 151 152 161 public void write(byte b[]) throws IOException { 162 write(b, 0, b.length); 163 } 164 165 166 177 public void write(byte b[], int off, int len) throws IOException { 178 179 if (closed) { 180 throw new IOException ("Cannot write to a closed output stream"); 181 } 182 183 if (len == 0) { 184 return; 185 } 186 187 if (len <= (buffer.length - bufferCount)) { 189 System.arraycopy(b, off, buffer, bufferCount, len); 190 bufferCount += len; 191 return; 192 } 193 194 flushToGZip(); 196 197 if (len <= (buffer.length - bufferCount)) { 199 System.arraycopy(b, off, buffer, bufferCount, len); 200 bufferCount += len; 201 return; 202 } 203 204 writeToGZip(b, off, len); 206 } 207 208 public void writeToGZip(byte b[], int off, int len) throws IOException { 209 210 if (gzipstream == null) { 211 gzipstream = new GZIPOutputStream (output); 212 response.addHeader("Content-Encoding", "gzip"); 213 } 214 gzipstream.write(b, off, len); 215 216 } 217 218 219 224 public boolean closed() { 225 return(this.closed); 226 } 227 228 } 229 | Popular Tags |