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.http.nio.entity;
28
29 import java.io.IOException;
30 import java.nio.CharBuffer;
31 import java.util.concurrent.atomic.AtomicReference;
32
33 import org.apache.hc.core5.http.ContentType;
34 import org.apache.hc.core5.http.nio.StreamChannel;
35 import org.apache.hc.core5.util.Args;
36 import org.apache.hc.core5.util.Asserts;
37
38
39
40
41
42
43
44 public class StringAsyncEntityProducer extends AbstractCharAsyncEntityProducer {
45
46 private final CharBuffer content;
47 private final AtomicReference<Exception> exception;
48
49 public StringAsyncEntityProducer(
50 final CharSequence content,
51 final int bufferSize,
52 final int fragmentSizeHint,
53 final ContentType contentType) {
54 super(bufferSize, fragmentSizeHint, contentType);
55 Args.notNull(content, "Content");
56 this.content = CharBuffer.wrap(content);
57 this.exception = new AtomicReference<>();
58 }
59
60 public StringAsyncEntityProducer(final CharSequence content, final int bufferSize, final ContentType contentType) {
61 this(content, bufferSize, -1, contentType);
62 }
63
64 public StringAsyncEntityProducer(final CharSequence content, final ContentType contentType) {
65 this(content, 4096, contentType);
66 }
67
68 public StringAsyncEntityProducer(final CharSequence content) {
69 this(content, ContentType.TEXT_PLAIN);
70 }
71
72 @Override
73 public boolean isRepeatable() {
74 return true;
75 }
76
77 @Override
78 protected int availableData() {
79 return Integer.MAX_VALUE;
80 }
81
82 @Override
83 protected void produceData(final StreamChannel<CharBuffer> channel) throws IOException {
84 Asserts.notNull(channel, "Channel");
85 channel.write(content);
86 if (!content.hasRemaining()) {
87 channel.endStream();
88 }
89 }
90
91 @Override
92 public void failed(final Exception cause) {
93 if (exception.compareAndSet(null, cause)) {
94 releaseResources();
95 }
96 }
97
98 public Exception getException() {
99 return exception.get();
100 }
101
102 @Override
103 public void releaseResources() {
104 this.content.clear();
105 super.releaseResources();
106 }
107
108 }