1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.http.nio.util;
28
29 import java.io.IOException;
30
31 import org.apache.http.annotation.NotThreadSafe;
32 import org.apache.http.nio.ContentDecoder;
33
34
35
36
37
38
39
40
41 @NotThreadSafe
42 public class SimpleInputBuffer extends ExpandableBuffer implements ContentInputBuffer {
43
44 private boolean endOfStream = false;
45
46 public SimpleInputBuffer(final int buffersize, final ByteBufferAllocator allocator) {
47 super(buffersize, allocator);
48 }
49
50
51
52
53 public SimpleInputBuffer(final int buffersize) {
54 this(buffersize, HeapByteBufferAllocator.INSTANCE);
55 }
56
57 public void reset() {
58 this.endOfStream = false;
59 super.clear();
60 }
61
62 public int consumeContent(final ContentDecoder decoder) throws IOException {
63 setInputMode();
64 int totalRead = 0;
65 int bytesRead;
66 while ((bytesRead = decoder.read(this.buffer)) != -1) {
67 if (bytesRead == 0) {
68 if (!this.buffer.hasRemaining()) {
69 expand();
70 } else {
71 break;
72 }
73 } else {
74 totalRead += bytesRead;
75 }
76 }
77 if (bytesRead == -1 || decoder.isCompleted()) {
78 this.endOfStream = true;
79 }
80 return totalRead;
81 }
82
83 public boolean isEndOfStream() {
84 return !hasData() && this.endOfStream;
85 }
86
87 public int read() throws IOException {
88 if (isEndOfStream()) {
89 return -1;
90 }
91 setOutputMode();
92 return this.buffer.get() & 0xff;
93 }
94
95 public int read(final byte[] b, final int off, final int len) throws IOException {
96 if (isEndOfStream()) {
97 return -1;
98 }
99 if (b == null) {
100 return 0;
101 }
102 setOutputMode();
103 int chunk = len;
104 if (chunk > this.buffer.remaining()) {
105 chunk = this.buffer.remaining();
106 }
107 this.buffer.get(b, off, chunk);
108 return chunk;
109 }
110
111 public int read(final byte[] b) throws IOException {
112 if (isEndOfStream()) {
113 return -1;
114 }
115 if (b == null) {
116 return 0;
117 }
118 return read(b, 0, b.length);
119 }
120
121 public void shutdown() {
122 this.endOfStream = true;
123 }
124
125 }