1 9 package org.snipsnap.net.filter; 10 11 import javax.servlet.ServletOutputStream ; 12 import javax.servlet.http.HttpServletResponse ; 13 import java.io.ByteArrayOutputStream ; 14 import java.io.IOException ; 15 import java.util.zip.GZIPOutputStream ; 16 17 public class GZIPResponseStream extends ServletOutputStream { 18 protected ByteArrayOutputStream baos = null; 19 protected GZIPOutputStream gzipstream = null; 20 protected boolean closed = false; 21 protected HttpServletResponse response = null; 22 protected ServletOutputStream output = null; 23 24 public GZIPResponseStream(HttpServletResponse response) throws IOException { 25 super(); 26 closed = false; 27 this.response = response; 28 this.output = response.getOutputStream(); 29 baos = new ByteArrayOutputStream (); 30 gzipstream = new GZIPOutputStream (baos); 31 } 32 33 public void close() throws IOException { 34 if (closed) { 35 return; 37 } 38 gzipstream.finish(); 39 40 byte[] bytes = baos.toByteArray(); 41 42 if (bytes.length > 0) { 44 response.setHeader("Content-Length", 45 Integer.toString(bytes.length)); 46 response.setHeader("Content-Encoding", "gzip"); 47 output.write(bytes); 48 } 49 50 output.flush(); 51 output.close(); 52 closed = true; 53 } 54 55 public void flush() throws IOException { 56 if (!closed) { 57 gzipstream.flush(); 58 } 59 } 60 61 public void write(int b) throws IOException { 62 if (closed) { 63 throw new IOException ("Cannot write to a closed output stream"); 64 } 65 gzipstream.write((byte) b); 66 } 67 68 public void write(byte b[]) throws IOException { 69 write(b, 0, b.length); 70 } 71 72 public void write(byte b[], int off, int len) throws IOException { 73 if (closed) { 75 throw new IOException ("Cannot write to a closed output stream"); 76 } 77 gzipstream.write(b, off, len); 78 } 79 80 public boolean closed() { 81 return (this.closed); 82 } 83 84 public void reset() { 85 } 87 } 88 | Popular Tags |