1 18 package filters.gzip; 19 20 import java.io.ByteArrayOutputStream ; 21 import java.io.IOException ; 22 import java.io.OutputStreamWriter ; 23 import java.io.PrintWriter ; 24 import java.util.zip.GZIPOutputStream ; 25 26 import javax.servlet.ServletContext ; 27 import javax.servlet.ServletOutputStream ; 28 import javax.servlet.http.HttpServletResponse ; 29 import javax.servlet.http.HttpServletResponseWrapper ; 30 31 39 public class GzipResponseWrapper extends HttpServletResponseWrapper { 40 41 private ByteArrayServletOutputStream bufferStream; 42 private PrintWriter bufferWriter; 43 private ServletContext context; 44 45 public GzipResponseWrapper(HttpServletResponse response, ServletContext context) { 46 super(response); 47 this.context = context; 48 setHeader("Content-Encoding", "gzip"); 49 } 50 51 public void close() throws IOException { 52 53 if (this.bufferWriter != null) { 54 this.bufferWriter.flush(); 55 } 56 57 if (this.bufferStream != null) { 59 byte content[] = this.bufferStream.getContent(); 60 long startTime = System.currentTimeMillis(); 61 62 int initialContentLength = content.length; 63 ByteArrayOutputStream buffer = new ByteArrayOutputStream (); 64 GZIPOutputStream gzip = new GZIPOutputStream (buffer); 65 gzip.write(content); 66 gzip.close(); 67 content = buffer.toByteArray(); 68 buffer.close(); 69 70 context.log("Gzipped " + initialContentLength + " bytes of " + 71 "response content to " + content.length + " bytes in " + 72 (System.currentTimeMillis() - startTime) + "ms"); 73 74 super.setContentLength(content.length); 76 ServletOutputStream out = null; 77 try { 78 out = super.getOutputStream(); 79 } catch (IllegalStateException err) { 80 throw new IOException ("Can't use a gzip response wrapper on included files"); 81 } 82 out.write(content); 83 out.flush(); 84 } 85 } 86 87 public void setContentLength(int length) {} 88 89 92 public ServletOutputStream getOutputStream() throws IOException { 93 if (this.bufferStream != null) { 94 return this.bufferStream; 95 } else { 96 this.bufferStream = new ByteArrayServletOutputStream(); 98 return this.bufferStream; 99 } 100 } 101 102 105 public PrintWriter getWriter() throws IOException { 106 if (this.bufferWriter != null) { 107 return this.bufferWriter; 108 } else { 109 if (this.bufferStream == null) { 112 this.bufferStream = new ByteArrayServletOutputStream(); 113 } 114 this.bufferWriter = new PrintWriter ( 115 new OutputStreamWriter (this.bufferStream, 116 getCharacterEncoding()), true); 117 return this.bufferWriter; 118 } 119 } 120 } 121 | Popular Tags |