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 package org.apache.hc.core5.testing.nio;
28
29 import java.io.IOException;
30 import java.nio.ByteBuffer;
31
32 import org.apache.hc.core5.http.ContentType;
33 import org.apache.hc.core5.http.nio.StreamChannel;
34 import org.apache.hc.core5.http.nio.entity.AbstractBinAsyncEntityProducer;
35
36 public class MultiBinEntityProducer extends AbstractBinAsyncEntityProducer {
37
38 private final byte[] bin;
39 private final int total;
40 private final ByteBuffer bytebuf;
41
42 private int count;
43
44 public MultiBinEntityProducer(final byte[] bin, final int total, final ContentType contentType) {
45 super(-1, contentType);
46 this.bin = bin;
47 this.total = total;
48 this.bytebuf = ByteBuffer.allocate(4096);
49 this.count = 0;
50 }
51
52 @Override
53 public boolean isRepeatable() {
54 return true;
55 }
56
57 @Override
58 protected int availableData() {
59 return Integer.MAX_VALUE;
60 }
61
62 @Override
63 protected void produceData(final StreamChannel<ByteBuffer> channel) throws IOException {
64 while (bytebuf.remaining() > bin.length + 2 && count < total) {
65 bytebuf.put(bin);
66 count++;
67 }
68 if (bytebuf.position() > 0) {
69 bytebuf.flip();
70 channel.write(bytebuf);
71 bytebuf.compact();
72 }
73 if (count >= total && bytebuf.position() == 0) {
74 channel.endStream();
75 }
76 }
77
78 @Override
79 public boolean isChunked() {
80 return false;
81 }
82
83 @Override
84 public long getContentLength() {
85 return bin.length * total;
86 }
87
88 @Override
89 public void failed(final Exception cause) {
90 }
91
92 @Override
93 public void releaseResources() {
94 count = 0;
95 bytebuf.clear();
96 super.releaseResources();
97 }
98
99 }