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.support;
28
29 import java.io.IOException;
30 import java.nio.ByteBuffer;
31 import java.util.List;
32
33 import org.apache.hc.core5.concurrent.FutureCallback;
34 import org.apache.hc.core5.http.EntityDetails;
35 import org.apache.hc.core5.http.Header;
36 import org.apache.hc.core5.http.HttpException;
37 import org.apache.hc.core5.http.HttpRequest;
38 import org.apache.hc.core5.http.HttpResponse;
39 import org.apache.hc.core5.http.nio.AsyncPushConsumer;
40 import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
41 import org.apache.hc.core5.http.nio.CapacityChannel;
42 import org.apache.hc.core5.http.protocol.HttpContext;
43 import org.apache.hc.core5.util.Args;
44
45
46
47
48
49
50
51
52 public abstract class AbstractAsyncPushHandler<T> implements AsyncPushConsumer {
53
54 private final AsyncResponseConsumer<T> responseConsumer;
55
56 public AbstractAsyncPushHandler(final AsyncResponseConsumer<T> responseConsumer) {
57 this.responseConsumer = Args.notNull(responseConsumer, "Response consumer");
58 }
59
60
61
62
63
64
65
66 protected abstract void handleResponse(
67 final HttpRequest promise, final T responseMessage) throws IOException, HttpException;
68
69
70
71
72
73
74
75 protected void handleError(final HttpRequest promise, final Exception cause) {
76 }
77
78 @Override
79 public final void consumePromise(
80 final HttpRequest promise,
81 final HttpResponse response,
82 final EntityDetails entityDetails,
83 final HttpContext httpContext) throws HttpException, IOException {
84 responseConsumer.consumeResponse(response, entityDetails, httpContext, new FutureCallback<T>() {
85
86 @Override
87 public void completed(final T result) {
88 try {
89 handleResponse(promise, result);
90 } catch (final Exception ex) {
91 failed(ex);
92 }
93 }
94
95 @Override
96 public void failed(final Exception cause) {
97 handleError(promise, cause);
98 releaseResources();
99 }
100
101 @Override
102 public void cancelled() {
103 releaseResources();
104 }
105
106 });
107 }
108
109 @Override
110 public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
111 responseConsumer.updateCapacity(capacityChannel);
112 }
113
114 @Override
115 public final void consume(final ByteBuffer src) throws IOException {
116 responseConsumer.consume(src);
117 }
118
119 @Override
120 public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
121 responseConsumer.streamEnd(trailers);
122 }
123
124 @Override
125 public final void failed(final Exception cause) {
126 responseConsumer.failed(cause);
127 releaseResources();
128 }
129
130 @Override
131 public final void releaseResources() {
132 if (responseConsumer != null) {
133 responseConsumer.releaseResources();
134 }
135 }
136
137 }