Skip to content

Commit 739c3a6

Browse files
author
Stephane Landelle
committed
BodyChunkedInput clean up
1 parent 6af397e commit 739c3a6

File tree

1 file changed

+29
-36
lines changed

1 file changed

+29
-36
lines changed

src/main/java/com/ning/http/client/providers/netty/BodyChunkedInput.java

Lines changed: 29 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -16,68 +16,61 @@
1616
import org.jboss.netty.buffer.ChannelBuffers;
1717
import org.jboss.netty.handler.stream.ChunkedInput;
1818

19-
import java.io.IOException;
2019
import java.nio.ByteBuffer;
2120

2221
/**
2322
* Adapts a {@link Body} to Netty's {@link ChunkedInput}.
2423
*/
25-
class BodyChunkedInput
26-
implements ChunkedInput {
24+
class BodyChunkedInput implements ChunkedInput {
2725

28-
private final Body body;
29-
30-
private final int chunkSize = 1024 * 8;
26+
private static final int DEFAULT_CHUNK_SIZE = 8 * 1024;
3127

32-
private ByteBuffer nextChunk;
28+
private final Body body;
29+
private final int contentLength;
30+
private final int chunkSize;
3331

34-
private static final ByteBuffer EOF = ByteBuffer.allocate(0);
32+
private boolean endOfInput;
3533

3634
public BodyChunkedInput(Body body) {
3735
if (body == null) {
3836
throw new IllegalArgumentException("no body specified");
3937
}
4038
this.body = body;
39+
contentLength = (int) body.getContentLength();
40+
if (contentLength <= 0)
41+
chunkSize = DEFAULT_CHUNK_SIZE;
42+
else
43+
chunkSize = Math.min(contentLength, DEFAULT_CHUNK_SIZE);
4144
}
4245

43-
private ByteBuffer peekNextChuck()
44-
throws IOException {
46+
public boolean hasNextChunk() throws Exception {
47+
// unused
48+
throw new UnsupportedOperationException();
49+
}
4550

46-
if (nextChunk == null) {
51+
public Object nextChunk() throws Exception {
52+
if (endOfInput) {
53+
return null;
54+
} else {
4755
ByteBuffer buffer = ByteBuffer.allocate(chunkSize);
48-
if (body.read(buffer) < 0) {
49-
nextChunk = EOF;
56+
long r = body.read(buffer);
57+
if (r < 0L) {
58+
endOfInput = true;
59+
return null;
5060
} else {
61+
endOfInput = r == contentLength || r < chunkSize;
5162
buffer.flip();
52-
nextChunk = buffer;
63+
return ChannelBuffers.wrappedBuffer(buffer);
5364
}
5465
}
55-
return nextChunk;
56-
}
57-
58-
public boolean hasNextChunk()
59-
throws Exception {
60-
return !isEndOfInput();
61-
}
62-
63-
public Object nextChunk()
64-
throws Exception {
65-
ByteBuffer buffer = peekNextChuck();
66-
if (buffer == EOF) {
67-
return null;
68-
}
69-
nextChunk = null;
70-
return ChannelBuffers.wrappedBuffer(buffer);
7166
}
7267

73-
public boolean isEndOfInput()
74-
throws Exception {
75-
return peekNextChuck() == EOF;
68+
public boolean isEndOfInput() throws Exception {
69+
// called by ChunkedWriteHandler AFTER nextChunk
70+
return endOfInput;
7671
}
7772

78-
public void close()
79-
throws Exception {
73+
public void close() throws Exception {
8074
body.close();
8175
}
82-
8376
}

0 commit comments

Comments
 (0)