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.WritableByteChannel;
34
35 import org.apache.http.impl.io.HttpTransportMetricsImpl;
36 import org.apache.http.nio.FileContentEncoder;
37 import org.apache.http.nio.reactor.SessionOutputBuffer;
38
39
40
41
42
43
44
45
46
47
48
49
50
51 public class IdentityEncoder extends AbstractContentEncoder
52 implements FileContentEncoder {
53
54 private final int fragHint;
55
56
57
58
59
60
61
62
63
64
65
66 public IdentityEncoder(
67 final WritableByteChannel channel,
68 final SessionOutputBuffer buffer,
69 final HttpTransportMetricsImpl metrics,
70 final int fragementSizeHint) {
71 super(channel, buffer, metrics);
72 this.fragHint = fragementSizeHint > 0 ? fragementSizeHint : 0;
73 }
74
75 public IdentityEncoder(
76 final WritableByteChannel channel,
77 final SessionOutputBuffer buffer,
78 final HttpTransportMetricsImpl metrics) {
79 this(channel, buffer, metrics, 0);
80 }
81
82 @Override
83 public int write(final ByteBuffer src) throws IOException {
84 if (src == null) {
85 return 0;
86 }
87 assertNotCompleted();
88
89 int total = 0;
90 while (src.hasRemaining()) {
91 if (this.buffer.hasData() || this.fragHint > 0) {
92 if (src.remaining() <= this.fragHint) {
93 final int capacity = this.fragHint - this.buffer.length();
94 if (capacity > 0) {
95 final int limit = Math.min(capacity, src.remaining());
96 final int bytesWritten = writeToBuffer(src, limit);
97 total += bytesWritten;
98 }
99 }
100 }
101 if (this.buffer.hasData()) {
102 if (this.buffer.length() >= this.fragHint || src.hasRemaining()) {
103 final int bytesWritten = flushToChannel();
104 if (bytesWritten == 0) {
105 break;
106 }
107 }
108 }
109 if (!this.buffer.hasData() && src.remaining() > this.fragHint) {
110 final int bytesWritten = writeToChannel(src);
111 total += bytesWritten;
112 if (bytesWritten == 0) {
113 break;
114 }
115 }
116 }
117 return total;
118 }
119
120 @Override
121 public long transfer(
122 final FileChannel src,
123 final long position,
124 final long count) throws IOException {
125
126 if (src == null) {
127 return 0;
128 }
129 assertNotCompleted();
130
131 flushToChannel();
132 if (this.buffer.hasData()) {
133 return 0;
134 }
135
136 final long bytesWritten = src.transferTo(position, count, this.channel);
137 if (bytesWritten > 0) {
138 this.metrics.incrementBytesTransferred(bytesWritten);
139 }
140 return bytesWritten;
141 }
142
143 @Override
144 public String toString() {
145 final StringBuilder sb = new StringBuilder();
146 sb.append("[identity; completed: ");
147 sb.append(isCompleted());
148 sb.append("]");
149 return sb.toString();
150 }
151
152 }