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.nio.ContentDecoder;
32
33
34
35
36
37
38
39
40 public class SimpleInputBuffer extends ExpandableBuffer implements ContentInputBuffer {
41
42 private boolean endOfStream = false;
43
44 public SimpleInputBuffer(final int bufferSize, final ByteBufferAllocator allocator) {
45 super(bufferSize, allocator);
46 }
47
48
49
50
51 public SimpleInputBuffer(final int bufferSize) {
52 this(bufferSize, HeapByteBufferAllocator.INSTANCE);
53 }
54
55 @Override
56 public void reset() {
57 this.endOfStream = false;
58 super.clear();
59 }
60
61 @Override
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 @Override
88 public int read() throws IOException {
89 if (isEndOfStream()) {
90 return -1;
91 }
92 setOutputMode();
93 return this.buffer.get() & 0xff;
94 }
95
96 @Override
97 public int read(final byte[] b, final int off, final int len) throws IOException {
98 if (isEndOfStream()) {
99 return -1;
100 }
101 if (b == null) {
102 return 0;
103 }
104 setOutputMode();
105 int chunk = len;
106 if (chunk > this.buffer.remaining()) {
107 chunk = this.buffer.remaining();
108 }
109 this.buffer.get(b, off, chunk);
110 return chunk;
111 }
112
113 public int read(final byte[] b) throws IOException {
114 if (isEndOfStream()) {
115 return -1;
116 }
117 if (b == null) {
118 return 0;
119 }
120 return read(b, 0, b.length);
121 }
122
123 public void shutdown() {
124 this.endOfStream = true;
125 }
126
127 }