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:
10: private int bytesSent = 0;
11:
12: private boolean isReadyToSend = false;
13:
14: public void readyToSend(ResponseSender sender) throws Exception {
15: this .sender = sender;
16: addStandardHeaders();
17: sender.send(makeHttpHeaders().getBytes());
18: isReadyToSend = true;
19: synchronized (this ) {
20: notify();
21: }
22: }
23:
24: public boolean isReadyToSend() {
25: return isReadyToSend;
26: }
27:
28: protected void addSpecificHeaders() {
29: addHeader("Transfer-Encoding", "chunked");
30: }
31:
32: public static String asHex(int value) {
33: return Integer.toHexString(value);
34: }
35:
36: public void add(String text) throws Exception {
37: if (text != null)
38: add(getEncodedBytes(text));
39: }
40:
41: public void add(byte[] bytes) throws Exception {
42: if (bytes == null || bytes.length == 0)
43: return;
44: String sizeLine = asHex(bytes.length) + CRLF;
45: ByteBuffer chunk = ByteBuffer.allocate(sizeLine.length()
46: + bytes.length + 2);
47: chunk.put(sizeLine.getBytes()).put(bytes).put(CRLF.getBytes());
48: sender.send(chunk.array());
49: bytesSent += bytes.length;
50: }
51:
52: public void addTrailingHeader(String key, String value)
53: throws Exception {
54: String header = key + ": " + value + CRLF;
55: sender.send(header.getBytes());
56: }
57:
58: public void closeChunks() throws Exception {
59: sender.send(("0" + CRLF).getBytes());
60: }
61:
62: public void closeTrailer() throws Exception {
63: sender.send(CRLF.getBytes());
64: }
65:
66: public void close() throws Exception {
67: sender.close();
68: }
69:
70: public void closeAll() throws Exception {
71: closeChunks();
72: closeTrailer();
73: close();
74: }
75:
76: public int getContentSize() {
77: return bytesSent;
78: }
79: }
|