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.http.EntityDetails;
34 import org.apache.hc.core5.http.Header;
35 import org.apache.hc.core5.http.HttpException;
36 import org.apache.hc.core5.http.HttpRequest;
37 import org.apache.hc.core5.http.HttpResponse;
38 import org.apache.hc.core5.http.message.BasicHttpResponse;
39 import org.apache.hc.core5.http.nio.AsyncResponseProducer;
40 import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
41 import org.apache.hc.core5.http.nio.CapacityChannel;
42 import org.apache.hc.core5.http.nio.DataStreamChannel;
43 import org.apache.hc.core5.http.nio.ResponseChannel;
44 import org.apache.hc.core5.http.nio.entity.AsyncEntityProducers;
45 import org.apache.hc.core5.http.protocol.HttpContext;
46 import org.apache.hc.core5.util.Args;
47
48
49
50
51
52
53
54
55 public final class ImmediateResponseExchangeHandler implements AsyncServerExchangeHandler {
56
57 private final AsyncResponseProducer responseProducer;
58
59 public ImmediateResponseExchangeHandler(final AsyncResponseProducer responseProducer) {
60 this.responseProducer = Args.notNull(responseProducer, "Response producer");
61 }
62
63 public ImmediateResponseExchangeHandler(final HttpResponse response, final String message) {
64 this(new BasicResponseProducer(response, AsyncEntityProducers.create(message)));
65 }
66
67 public ImmediateResponseExchangeHandler(final int status, final String message) {
68 this(new BasicHttpResponse(status), message);
69 }
70
71 @Override
72 public void handleRequest(
73 final HttpRequest request,
74 final EntityDetails entityDetails,
75 final ResponseChannel responseChannel,
76 final HttpContext context) throws HttpException, IOException {
77 responseProducer.sendResponse(responseChannel, context);
78 }
79
80 @Override
81 public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
82 capacityChannel.update(Integer.MAX_VALUE);
83 }
84
85 @Override
86 public void consume(final ByteBuffer src) throws IOException {
87 }
88
89 @Override
90 public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
91 }
92
93 @Override
94 public int available() {
95 return responseProducer.available();
96 }
97
98 @Override
99 public void produce(final DataStreamChannel channel) throws IOException {
100 responseProducer.produce(channel);
101 }
102
103 @Override
104 public void failed(final Exception cause) {
105 responseProducer.failed(cause);
106 releaseResources();
107 }
108
109 @Override
110 public void releaseResources() {
111 responseProducer.releaseResources();
112 }
113
114 }