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