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
28 package org.apache.hc.core5.http.impl.nio;
29
30 import java.io.IOException;
31 import java.nio.ByteBuffer;
32 import java.nio.channels.ReadableByteChannel;
33 import java.util.List;
34
35 import org.apache.hc.core5.http.Header;
36 import org.apache.hc.core5.http.impl.BasicHttpTransportMetrics;
37 import org.apache.hc.core5.http.nio.ContentDecoder;
38 import org.apache.hc.core5.http.nio.SessionInputBuffer;
39 import org.apache.hc.core5.util.Args;
40
41
42
43
44
45
46
47 public abstract class AbstractContentDecoder implements ContentDecoder {
48
49 final ReadableByteChannel channel;
50 final SessionInputBuffer buffer;
51 final BasicHttpTransportMetrics metrics;
52
53 protected boolean completed;
54
55
56
57
58
59
60
61
62
63 public AbstractContentDecoder(
64 final ReadableByteChannel channel,
65 final SessionInputBuffer buffer,
66 final BasicHttpTransportMetrics metrics) {
67 super();
68 Args.notNull(channel, "Channel");
69 Args.notNull(buffer, "Session input buffer");
70 Args.notNull(metrics, "Transport metrics");
71 this.buffer = buffer;
72 this.channel = channel;
73 this.metrics = metrics;
74 }
75
76 protected ReadableByteChannel channel() {
77 return this.channel;
78 }
79
80 protected SessionInputBuffer buffer() {
81 return this.buffer;
82 }
83
84 protected BasicHttpTransportMetrics metrics() {
85 return this.metrics;
86 }
87
88 @Override
89 public boolean isCompleted() {
90 return this.completed;
91 }
92
93
94
95
96
97
98
99
100
101
102
103 public void setCompleted(final boolean completed) {
104 this.completed = completed;
105 }
106
107
108
109
110
111
112
113
114
115
116 protected void setCompleted() {
117 this.completed = true;
118 }
119
120
121
122
123
124
125
126
127
128 protected int readFromChannel(final ByteBuffer dst) throws IOException {
129 final int bytesRead = this.channel.read(dst);
130 if (bytesRead > 0) {
131 this.metrics.incrementBytesTransferred(bytesRead);
132 }
133 return bytesRead;
134 }
135
136
137
138
139
140
141
142 protected int fillBufferFromChannel() throws IOException {
143 final int bytesRead = this.buffer.fill(this.channel);
144 if (bytesRead > 0) {
145 this.metrics.incrementBytesTransferred(bytesRead);
146 }
147 return bytesRead;
148 }
149
150
151
152
153
154
155
156
157
158
159 protected int readFromChannel(final ByteBuffer dst, final int limit) throws IOException {
160 final int bytesRead;
161 if (dst.remaining() > limit) {
162 final int oldLimit = dst.limit();
163 final int newLimit = oldLimit - (dst.remaining() - limit);
164 dst.limit(newLimit);
165 bytesRead = this.channel.read(dst);
166 dst.limit(oldLimit);
167 } else {
168 bytesRead = this.channel.read(dst);
169 }
170 if (bytesRead > 0) {
171 this.metrics.incrementBytesTransferred(bytesRead);
172 }
173 return bytesRead;
174 }
175
176 @Override
177 public List<? extends Header> getTrailers() {
178 return null;
179 }
180
181 }