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