1 17 18 package org.apache.coyote.http11.filters; 19 20 import java.io.IOException ; 21 22 import org.apache.tomcat.util.buf.ByteChunk; 23 import org.apache.tomcat.util.buf.HexUtils; 24 25 import org.apache.coyote.OutputBuffer; 26 import org.apache.coyote.Response; 27 import org.apache.coyote.http11.OutputFilter; 28 29 34 public class ChunkedOutputFilter implements OutputFilter { 35 36 37 39 40 protected static final String ENCODING_NAME = "chunked"; 41 protected static final ByteChunk ENCODING = new ByteChunk(); 42 43 44 47 protected static final ByteChunk END_CHUNK = new ByteChunk(); 48 49 50 52 53 static { 54 ENCODING.setBytes(ENCODING_NAME.getBytes(), 0, ENCODING_NAME.length()); 55 byte[] END_CHUNK_BYTES = {(byte) '0', (byte) '\r', (byte) '\n', 56 (byte) '\r', (byte) '\n'}; 57 END_CHUNK.setBytes(END_CHUNK_BYTES, 0, END_CHUNK_BYTES.length); 58 } 59 60 61 63 64 67 public ChunkedOutputFilter() { 68 chunkLength = new byte[10]; 69 chunkLength[8] = (byte) '\r'; 70 chunkLength[9] = (byte) '\n'; 71 } 72 73 74 76 77 80 protected OutputBuffer buffer; 81 82 83 86 protected byte[] chunkLength = new byte[10]; 87 88 89 92 protected ByteChunk chunkHeader = new ByteChunk(); 93 94 95 97 98 100 101 106 public int doWrite(ByteChunk chunk, Response res) 107 throws IOException { 108 109 int result = chunk.getLength(); 110 111 if (result <= 0) { 112 return 0; 113 } 114 115 int pos = 7; 117 int current = result; 118 while (current > 0) { 119 int digit = current % 16; 120 current = current / 16; 121 chunkLength[pos--] = HexUtils.HEX[digit]; 122 } 123 chunkHeader.setBytes(chunkLength, pos + 1, 9 - pos); 124 buffer.doWrite(chunkHeader, res); 125 126 buffer.doWrite(chunk, res); 127 128 chunkHeader.setBytes(chunkLength, 8, 2); 129 buffer.doWrite(chunkHeader, res); 130 131 return result; 132 133 } 134 135 136 138 139 144 public void setResponse(Response response) { 145 } 146 147 148 151 public void setBuffer(OutputBuffer buffer) { 152 this.buffer = buffer; 153 } 154 155 156 160 public long end() 161 throws IOException { 162 163 buffer.doWrite(END_CHUNK, null); 165 166 return 0; 167 168 } 169 170 171 174 public void recycle() { 175 } 176 177 178 182 public ByteChunk getEncodingName() { 183 return ENCODING; 184 } 185 186 187 } 188 | Popular Tags |