1 17 18 package org.apache.coyote.http11.filters; 19 20 import java.io.IOException ; 21 import java.io.OutputStream ; 22 import java.util.zip.GZIPOutputStream ; 23 24 import org.apache.tomcat.util.buf.ByteChunk; 25 26 import org.apache.coyote.OutputBuffer; 27 import org.apache.coyote.Response; 28 import org.apache.coyote.http11.OutputFilter; 29 30 35 public class GzipOutputFilter implements OutputFilter { 36 37 38 40 41 protected static final String ENCODING_NAME = "gzip"; 42 protected static final ByteChunk ENCODING = new ByteChunk(); 43 44 45 47 48 static { 49 ENCODING.setBytes(ENCODING_NAME.getBytes(), 0, ENCODING_NAME.length()); 50 } 51 52 53 55 56 59 protected OutputBuffer buffer; 60 61 62 65 protected GZIPOutputStream compressionStream = null; 66 67 68 71 protected OutputStream fakeOutputStream = new FakeOutputStream(); 72 73 74 76 77 82 public int doWrite(ByteChunk chunk, Response res) 83 throws IOException { 84 if (compressionStream == null) { 85 compressionStream = new GZIPOutputStream (fakeOutputStream); 86 } 87 compressionStream.write(chunk.getBytes(), chunk.getStart(), 88 chunk.getLength()); 89 return chunk.getLength(); 90 } 91 92 93 95 96 101 public void setResponse(Response response) { 102 } 103 104 105 108 public void setBuffer(OutputBuffer buffer) { 109 this.buffer = buffer; 110 } 111 112 113 117 public long end() 118 throws IOException { 119 if (compressionStream == null) { 120 compressionStream = new GZIPOutputStream (fakeOutputStream); 121 } 122 compressionStream.finish(); 123 compressionStream.close(); 124 return ((OutputFilter) buffer).end(); 125 } 126 127 128 131 public void recycle() { 132 compressionStream = null; 134 } 135 136 137 141 public ByteChunk getEncodingName() { 142 return ENCODING; 143 } 144 145 146 148 149 protected class FakeOutputStream 150 extends OutputStream { 151 protected ByteChunk outputChunk = new ByteChunk(); 152 protected byte[] singleByteBuffer = new byte[1]; 153 public void write(int b) 154 throws IOException { 155 singleByteBuffer[0] = (byte) (b & 0xff); 158 outputChunk.setBytes(singleByteBuffer, 0, 1); 159 buffer.doWrite(outputChunk, null); 160 } 161 public void write(byte[] b, int off, int len) 162 throws IOException { 163 outputChunk.setBytes(b, off, len); 164 buffer.doWrite(outputChunk, null); 165 } 166 public void flush() throws IOException {} 167 public void close() throws IOException {} 168 } 169 170 171 } 172 | Popular Tags |