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