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
28 package org.apache.hc.client5.http.impl.compat;
29
30 import java.io.IOException;
31 import java.io.InterruptedIOException;
32 import java.util.concurrent.Future;
33
34 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
35 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
36 import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
37 import org.apache.hc.core5.annotation.Contract;
38 import org.apache.hc.core5.annotation.Experimental;
39 import org.apache.hc.core5.annotation.Internal;
40 import org.apache.hc.core5.annotation.ThreadingBehavior;
41 import org.apache.hc.core5.concurrent.CancellableDependency;
42 import org.apache.hc.core5.http.ClassicHttpRequest;
43 import org.apache.hc.core5.http.ClassicHttpResponse;
44 import org.apache.hc.core5.http.HttpHost;
45 import org.apache.hc.core5.http.protocol.HttpContext;
46 import org.apache.hc.core5.io.CloseMode;
47 import org.apache.hc.core5.util.Timeout;
48
49
50
51
52
53
54
55
56 @Experimental
57 @Internal
58 @Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
59 public class ClassicToAsyncAdaptor extends CloseableHttpClient {
60
61 private final CloseableHttpAsyncClient client;
62 private final Timeout operationTimeout;
63
64 public ClassicToAsyncAdaptor(final CloseableHttpAsyncClient client, final Timeout operationTimeout) {
65 super();
66 this.client = client;
67 this.operationTimeout = operationTimeout;
68 }
69
70 @Override
71 protected CloseableHttpResponse doExecute(
72 final HttpHost target,
73 final ClassicHttpRequest request,
74 final HttpContext context) throws IOException {
75 final ClassicToAsyncRequestProducer requestProducer = new ClassicToAsyncRequestProducer(request, operationTimeout);
76 final ClassicToAsyncResponseConsumer responseConsumer = new ClassicToAsyncResponseConsumer(operationTimeout);
77 final Future<Void> resultFuture = client.execute(target, requestProducer, responseConsumer, null, context, null);
78 if (request instanceof CancellableDependency) {
79 ((CancellableDependency) request).setDependency(() -> resultFuture.cancel(true));
80 }
81 try {
82 requestProducer.blockWaiting().execute();
83 final ClassicHttpResponse response = responseConsumer.blockWaiting();
84 return CloseableHttpResponse.create(response,
85 (closeable, closeMode) -> {
86 try {
87 if (closeMode == CloseMode.GRACEFUL) {
88 closeable.close();
89 }
90 } finally {
91 resultFuture.cancel(true);
92 }
93 });
94 } catch (final InterruptedException ex) {
95 Thread.currentThread().interrupt();
96 throw new InterruptedIOException();
97 }
98 }
99
100 @Override
101 public void close() throws IOException {
102 client.close();
103 }
104
105 @Override
106 public void close(final CloseMode closeMode) {
107 client.close(closeMode);
108 }
109
110 }