2
* $Header: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ChunkedInputStream.java,v 1.16.2.2 2004/02/22 18:21:13 olegk Exp $
3
* $Revision: 1.16.2.2 $
4
* $Date: 2004/02/22 18:21:13 $
6
* ====================================================================
8
* Copyright 2002-2004 The Apache Software Foundation
10
* Licensed under the Apache License, Version 2.0 (the "License");
11
* you may not use this file except in compliance with the License.
12
* You may obtain a copy of the License at
14
* http://www.apache.org/licenses/LICENSE-2.0
16
* Unless required by applicable law or agreed to in writing, software
17
* distributed under the License is distributed on an "AS IS" BASIS,
18
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
* See the License for the specific language governing permissions and
20
* limitations under the License.
21
* ====================================================================
23
* This software consists of voluntary contributions made by many
24
* individuals on behalf of the Apache Software Foundation. For more
25
* information on the Apache Software Foundation, please see
26
* <http://www.apache.org/>.
28
* [Additional notices, if required by prior licensing conditions]
32
package org.apache.commons.httpclient;
34
import java.io.ByteArrayOutputStream;
35
import java.io.IOException;
36
import java.io.InputStream;
40
* <p>Transparently coalesces chunks of a HTTP stream that uses
41
* Transfer-Encoding chunked.</p>
43
* <p>Note that this class NEVER closes the underlying stream, even when close
44
* gets called. Instead, it will read until the "end" of its chunking on close,
45
* which allows for the seamless invocation of subsequent HTTP 1.1 calls, while
46
* not requiring the client to remember to read the entire contents of the
49
* @see ResponseInputStream
51
* @author Ortwin Glļæ½ck
52
* @author Sean C. Sullivan
53
* @author Martin Elwin
54
* @author Eric Johnson
55
* @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
56
* @author Michael Becke
57
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
63
public class ChunkedInputStream extends InputStream {
64
/** The inputstream that we're wrapping */
65
private InputStream in;
68
private int chunkSize;
70
/** The current position within the current chunk */
73
/** True if we'are at the beginning of stream */
74
private boolean bof = true;
76
/** True if we've reached the end of stream */
77
private boolean eof = false;
79
/** True if this stream is closed */
80
private boolean closed = false;
82
/** The method that this stream came from */
83
private HttpMethod method;
88
* @param in must be non-null
89
* @param method must be non-null
91
* @throws IOException If an IO error occurs
93
public ChunkedInputStream(
94
final InputStream in, final HttpMethod method) throws IOException {
97
throw new IllegalArgumentException("InputStream parameter may not be null");
100
throw new IllegalArgumentException("HttpMethod parameter may not be null");
103
this.method = method;
108
* <p> Returns all the data in a chunked stream in coalesced form. A chunk
109
* is followed by a CRLF. The method returns -1 as soon as a chunksize of 0
112
* <p> Trailer headers are read automcatically at the end of the stream and
113
* can be obtained with the getResponseFooters() method.</p>
115
* @return -1 of the end of the stream has been reached or the next data
117
* @throws IOException If an IO problem occurs
119
* @see HttpMethod#getResponseFooters()
121
public int read() throws IOException {
124
throw new IOException("Attempted read from closed stream.");
129
if (pos >= chunkSize) {
140
* Read some bytes from the stream.
141
* @param b The byte array that will hold the contents from the stream.
142
* @param off The offset into the byte array at which bytes will start to be
144
* @param len the maximum number of bytes that can be returned.
145
* @return The number of bytes returned or -1 if the end of stream has been
147
* @see java.io.InputStream#read(byte[], int, int)
148
* @throws IOException if an IO problem occurs.
150
public int read (byte[] b, int off, int len) throws IOException {
153
throw new IOException("Attempted read from closed stream.");
159
if (pos >= chunkSize) {
165
len = Math.min(len, chunkSize - pos);
166
int count = in.read(b, off, len);
172
* Read some bytes from the stream.
173
* @param b The byte array that will hold the contents from the stream.
174
* @return The number of bytes returned or -1 if the end of stream has been
176
* @see java.io.InputStream#read(byte[])
177
* @throws IOException if an IO problem occurs.
179
public int read (byte[] b) throws IOException {
180
return read(b, 0, b.length);
184
* Read the CRLF terminator.
185
* @throws IOException If an IO error occurs.
187
private void readCRLF() throws IOException {
190
if ((cr != '\r') || (lf != '\n')) {
191
throw new IOException(
192
"CRLF expected at end of chunk: " + cr + "/" + lf);
198
* Read the next chunk.
199
* @throws IOException If an IO error occurs.
201
private void nextChunk() throws IOException {
205
chunkSize = getChunkSizeFromInputStream(in);
208
if (chunkSize == 0) {
210
parseTrailerHeaders();
215
* Expects the stream to start with a chunksize in hex with optional
216
* comments after a semicolon. The line must end with a CRLF: "a3; some
217
* comment\r\n" Positions the stream at the start of the next line.
219
* @param in The new input stream.
221
* @return the chunk size as integer
223
* @throws IOException when the chunk size could not be parsed
225
private static int getChunkSizeFromInputStream(final InputStream in)
228
ByteArrayOutputStream baos = new ByteArrayOutputStream();
229
// States: 0=normal, 1=\r was scanned, 2=inside quoted string, -1=end
231
while (state != -1) {
234
throw new IOException("chunked stream ended unexpectedly");
255
throw new IOException("Protocol violation: Unexpected"
256
+ " single newline character in chunk size");
273
default: throw new RuntimeException("assertion failed");
278
String dataString = HttpConstants.getString(baos.toByteArray());
279
int separator = dataString.indexOf(';');
280
dataString = (separator > 0)
281
? dataString.substring(0, separator).trim()
286
result = Integer.parseInt(dataString.trim(), 16);
287
} catch (NumberFormatException e) {
288
throw new IOException ("Bad chunk size: " + dataString);
294
* Reads and stores the Trailer headers.
295
* @throws IOException If an IO problem occurs
297
private void parseTrailerHeaders() throws IOException {
298
Header[] footers = HttpParser.parseHeaders(in);
300
for (int i = 0; i < footers.length; i++) {
301
method.addResponseFooter(footers[i]);
306
* Upon close, this reads the remainder of the chunked message,
307
* leaving the underlying socket at a position to start reading the
308
* next response without scanning.
309
* @throws IOException If an IO problem occurs.
311
public void close() throws IOException {
315
exhaustInputStream(this);
325
* Exhaust an input stream, reading until EOF has been encountered.
327
* <p>Note that this function is intended as a non-public utility.
328
* This is a little weird, but it seemed silly to make a utility
329
* class for this one function, so instead it is just static and
330
* shared that way.</p>
332
* @param inStream The {@link InputStream} to exhaust.
333
* @throws IOException If an IO problem occurs
335
static void exhaustInputStream(InputStream inStream) throws IOException {
336
// read and discard the remainder of the message
337
byte buffer[] = new byte[1024];
338
while (inStream.read(buffer) >= 0) {