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.CharBuffer;
31 import java.nio.charset.Charset;
32 import java.nio.charset.StandardCharsets;
33
34 import org.apache.hc.core5.http.ContentType;
35 import org.apache.hc.core5.http.nio.StreamChannel;
36 import org.apache.hc.core5.http.nio.entity.AbstractCharAsyncEntityProducer;
37
38 public class MultiLineEntityProducer extends AbstractCharAsyncEntityProducer {
39
40 private final String text;
41 private final int total;
42 private final CharBuffer charbuf;
43
44 private int count;
45
46 public MultiLineEntityProducer(final String text, final int total, final Charset charset) {
47 super(1024, -1, ContentType.TEXT_PLAIN.withCharset(charset));
48 this.text = text;
49 this.total = total;
50 this.charbuf = CharBuffer.allocate(4096);
51 this.count = 0;
52 }
53
54 public MultiLineEntityProducer(final String text, final int total) {
55 this(text, total, StandardCharsets.US_ASCII);
56 }
57
58 @Override
59 public boolean isRepeatable() {
60 return true;
61 }
62
63 @Override
64 protected int availableData() {
65 return Integer.MAX_VALUE;
66 }
67
68 @Override
69 protected void produceData(final StreamChannel<CharBuffer> channel) throws IOException {
70 while (charbuf.remaining() > text.length() + 2 && count < total) {
71 charbuf.put(text + "\r\n");
72 count++;
73 }
74 if (charbuf.position() > 0) {
75 charbuf.flip();
76 channel.write(charbuf);
77 charbuf.compact();
78 }
79 if (count >= total && charbuf.position() == 0) {
80 channel.endStream();
81 }
82 }
83
84 @Override
85 public void failed(final Exception cause) {
86 }
87
88 @Override
89 public void releaseResources() {
90 count = 0;
91 charbuf.clear();
92 super.releaseResources();
93 }
94
95 }