01: package com.sun.portal.rproxy.rewriter.util.http;
02:
03: import java.io.ByteArrayOutputStream;
04: import com.sun.portal.log.common.PortalLogger;
05: import java.io.IOException;
06: import java.io.InputStream;
07: import java.util.StringTokenizer;
08:
09: /**
10: * @author Noble Paul
11: * Date: Dec 31, 2003
12: * The class handles content with chunked encoding
13: */
14: public class ChunkedContent {
15: public static byte[] readChunkedContent(InputStream in)
16: throws IOException {
17: ByteArrayOutputStream baos = new ByteArrayOutputStream();
18: byte[] buf;
19: int chunkSize = getChunkSize(in);//length := 0 .read chunk-size,chunk-ext (if any),and CRLF
20:
21: while (chunkSize > 0)// while (chunk-size > 0) {
22: {
23: buf = new byte[chunkSize];
24: in.read(buf);// read chunk-data
25: readCRLF(in);//and CRLF
26: baos.write(buf);//append chunk-data to entity-body .length := length + chunk-size
27: chunkSize = getChunkSize(in); //read chunk-size and CRLF
28:
29: }
30: return baos.toByteArray();
31: }
32:
33: private static int getChunkSize(InputStream in) throws IOException {
34: int chunksize = 0;
35: String line = readLine(in);
36: if (line == null)
37: throw new IOException("Could not read chunk block size");
38: StringTokenizer st = new StringTokenizer(line, "\t \n\r(;");
39: if (st.hasMoreTokens()) {
40: String hex = st.nextToken();
41: try {
42: chunksize = Integer.parseInt(hex, 16);
43: } catch (NumberFormatException e) {
44: throw new IOException(
45: "Chunk size should be a hex number: '" + line
46: + "', '" + hex + "'.");
47: }
48: } else {
49: throw new IOException("Chunk could not be read.");
50: }
51: return chunksize;
52: }
53:
54: public static void readCRLF(InputStream in) throws IOException {
55: int cr = in.read();
56: int lf = in.read();
57: if (cr != 13 && lf != 10)
58: throw new IOException("Could not read CR & LF correctly: "
59: + cr + ", " + lf);
60: }
61:
62: private static String readLine(InputStream in) throws IOException {
63: StringBuffer sb = new StringBuffer(50);
64: int l = -1;
65: int count = 0;
66: while (true) {
67: int c = in.read();
68: if (c == -1)
69: break;
70: count++;
71: if (l == '\r' && c == '\n') {
72: sb.setLength(sb.length() - 1);
73: break;
74: }
75: sb.append((char) c);
76: l = c;
77: }
78: if (count == 0)
79: return null;
80: return sb.toString();
81: }
82: }
|