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.FileChannel;
33 import java.nio.channels.ReadableByteChannel;
34
35 import org.apache.hc.core5.http.impl.BasicHttpTransportMetrics;
36 import org.apache.hc.core5.http.nio.FileContentDecoder;
37 import org.apache.hc.core5.http.nio.SessionInputBuffer;
38 import org.apache.hc.core5.util.Args;
39
40
41
42
43
44
45
46
47
48
49
50
51
52 public class IdentityDecoder extends AbstractContentDecoder implements FileContentDecoder {
53
54 public IdentityDecoder(
55 final ReadableByteChannel channel,
56 final SessionInputBuffer buffer,
57 final BasicHttpTransportMetrics metrics) {
58 super(channel, buffer, metrics);
59 }
60
61 @Override
62 public int read(final ByteBuffer dst) throws IOException {
63 Args.notNull(dst, "Byte buffer");
64 if (isCompleted()) {
65 return -1;
66 }
67
68 final int bytesRead;
69 if (this.buffer.hasData()) {
70 bytesRead = this.buffer.read(dst);
71 } else {
72 bytesRead = readFromChannel(dst);
73 }
74 if (bytesRead == -1) {
75 setCompleted();
76 }
77 return bytesRead;
78 }
79
80 @Override
81 public long transfer(
82 final FileChannel dst,
83 final long position,
84 final long count) throws IOException {
85
86 if (dst == null) {
87 return 0;
88 }
89 if (isCompleted()) {
90 return 0;
91 }
92
93 long bytesRead;
94 if (this.buffer.hasData()) {
95 final int maxLen = this.buffer.length();
96 dst.position(position);
97 bytesRead = this.buffer.read(dst, count < maxLen ? (int)count : maxLen);
98 } else {
99 if (this.channel.isOpen()) {
100 if (position > dst.size()) {
101 throw new IOException("Position past end of file [" + position +
102 " > " + dst.size() + "]");
103 }
104 bytesRead = dst.transferFrom(this.channel, position, count);
105 if (count > 0 && bytesRead == 0) {
106 bytesRead = this.buffer.fill(this.channel);
107 }
108 } else {
109 bytesRead = -1;
110 }
111 if (bytesRead > 0) {
112 this.metrics.incrementBytesTransferred(bytesRead);
113 }
114 }
115 if (bytesRead == -1) {
116 setCompleted();
117 }
118 return bytesRead;
119 }
120
121 @Override
122 public String toString() {
123 final StringBuilder sb = new StringBuilder();
124 sb.append("[identity; completed: ");
125 sb.append(this.completed);
126 sb.append("]");
127 return sb.toString();
128 }
129
130 }