01: package pygmy.core;
02:
03: import java.io.FilterOutputStream;
04: import java.io.OutputStream;
05: import java.io.IOException;
06:
07: public class ChunkedEncodingOutputStream extends FilterOutputStream {
08:
09: static final int DEFAULT_CHUNK_SIZE = 4096;
10: byte[] buf = null;
11: int count = 0;
12:
13: public ChunkedEncodingOutputStream(OutputStream out,
14: int maxChunkSize) {
15: super (out);
16: this .buf = new byte[maxChunkSize];
17: }
18:
19: public ChunkedEncodingOutputStream(OutputStream out) {
20: this (out, DEFAULT_CHUNK_SIZE);
21: }
22:
23: public void write(int b) throws IOException {
24: if (count >= buf.length) {
25: flush();
26: }
27: buf[count++] = (byte) b;
28: }
29:
30: public void write(byte b[]) throws IOException {
31: this .write(b, 0, b.length);
32: }
33:
34: public void write(byte b[], int off, int len) throws IOException {
35: for (int i = off; i < len; i++) {
36: if (count >= buf.length) {
37: flush();
38: }
39: buf[count++] = b[i];
40: }
41: }
42:
43: public void flush() throws IOException {
44: writeChunkSize(count);
45: writeChunkData(buf, count);
46: count = 0;
47: out.flush();
48: }
49:
50: public void close() throws IOException {
51: if (count > 0) {
52: flush();
53: }
54: writeChunkEnding();
55: out.close();
56: }
57:
58: private void writeChunkSize(int count) throws IOException {
59: if (count > 0) {
60: out.write((Integer.toHexString(count)).getBytes());
61: out.write(Http.CRLF.getBytes());
62: }
63: }
64:
65: private void writeChunkData(byte[] buf, int count)
66: throws IOException {
67: if (count > 0) {
68: out.write(buf, 0, count);
69: out.write(Http.CRLF.getBytes());
70: }
71: }
72:
73: private void writeChunkEnding() throws IOException {
74: out.write("0".getBytes());
75: out.write(Http.CRLF.getBytes());
76: out.write(Http.CRLF.getBytes());
77: }
78:
79: }
|