01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.http;
04:
05: import java.nio.ByteBuffer;
06:
07: public class ChunkedResponse extends Response {
08: private ResponseSender sender;
09: private int bytesSent = 0;
10: private boolean isReadyToSend = false;
11:
12: public void readyToSend(ResponseSender sender) throws Exception {
13: this .sender = sender;
14: addStandardHeaders();
15: sender.send(makeHttpHeaders().getBytes());
16: isReadyToSend = true;
17: synchronized (this ) {
18: notify();
19: }
20: }
21:
22: public boolean isReadyToSend() {
23: return isReadyToSend;
24: }
25:
26: protected void addSpecificHeaders() {
27: addHeader("Transfer-Encoding", "chunked");
28: }
29:
30: public static String asHex(int value) {
31: return Integer.toHexString(value);
32: }
33:
34: public void add(String text) throws Exception {
35: if (text != null)
36: add(getEncodedBytes(text));
37: }
38:
39: public void add(byte[] bytes) throws Exception {
40: if (bytes == null || bytes.length == 0)
41: return;
42: String sizeLine = asHex(bytes.length) + CRLF;
43: ByteBuffer chunk = ByteBuffer.allocate(sizeLine.length()
44: + bytes.length + 2);
45: chunk.put(sizeLine.getBytes()).put(bytes).put(CRLF.getBytes());
46: sender.send(chunk.array());
47: bytesSent += bytes.length;
48: }
49:
50: public void addTrailingHeader(String key, String value)
51: throws Exception {
52: String header = key + ": " + value + CRLF;
53: sender.send(header.getBytes());
54: }
55:
56: public void closeChunks() throws Exception {
57: sender.send(("0" + CRLF).getBytes());
58: }
59:
60: public void closeTrailer() throws Exception {
61: sender.send(CRLF.getBytes());
62: }
63:
64: public void close() throws Exception {
65: sender.close();
66: }
67:
68: public void closeAll() throws Exception {
69: closeChunks();
70: closeTrailer();
71: close();
72: }
73:
74: public int getContentSize() {
75: return bytesSent;
76: }
77: }
|