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.io.UnsupportedEncodingException;
31 import java.nio.charset.UnsupportedCharsetException;
32
33 import org.apache.hc.core5.concurrent.FutureCallback;
34 import org.apache.hc.core5.http.ContentType;
35 import org.apache.hc.core5.http.EntityDetails;
36 import org.apache.hc.core5.http.HttpException;
37 import org.apache.hc.core5.http.config.CharCodingConfig;
38 import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
39 import org.apache.hc.core5.util.Args;
40
41
42
43
44
45
46
47
48 public abstract class AbstractCharAsyncEntityConsumer<T> extends AbstractCharDataConsumer implements AsyncEntityConsumer<T> {
49
50 private volatile FutureCallback<T> resultCallback;
51 private volatile T content;
52
53 protected AbstractCharAsyncEntityConsumer(final int bufSize, final CharCodingConfig charCodingConfig) {
54 super(bufSize, charCodingConfig);
55 }
56
57 public AbstractCharAsyncEntityConsumer() {
58 }
59
60
61
62
63
64
65 protected abstract void streamStart(ContentType contentType) throws HttpException, IOException;
66
67
68
69
70
71
72 protected abstract T generateContent() throws IOException;
73
74 @Override
75 public final void streamStart(
76 final EntityDetails entityDetails,
77 final FutureCallback<T> resultCallback) throws IOException, HttpException {
78 Args.notNull(resultCallback, "Result callback");
79 this.resultCallback = resultCallback;
80 try {
81 final ContentType contentType = entityDetails != null ? ContentType.parse(entityDetails.getContentType()) : null;
82 setCharset(ContentType.getCharset(contentType, null));
83 streamStart(contentType);
84 } catch (final UnsupportedCharsetException ex) {
85 throw new UnsupportedEncodingException(ex.getMessage());
86 }
87 }
88
89 @Override
90 protected final void completed() throws IOException {
91 content = generateContent();
92 if (resultCallback != null) {
93 resultCallback.completed(content);
94 }
95 releaseResources();
96 }
97
98 @Override
99 public final void failed(final Exception cause) {
100 if (resultCallback != null) {
101 resultCallback.failed(cause);
102 }
103 releaseResources();
104 }
105
106 @Override
107 public final T getContent() {
108 return content;
109 }
110
111 }