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.core5.testing.nio;
29
30 import java.io.IOException;
31 import java.net.InetSocketAddress;
32 import java.net.SocketAddress;
33 import java.util.concurrent.Future;
34 import java.util.concurrent.ThreadFactory;
35
36 import org.apache.hc.core5.concurrent.FutureCallback;
37 import org.apache.hc.core5.function.Callback;
38 import org.apache.hc.core5.http.HttpHost;
39 import org.apache.hc.core5.http.URIScheme;
40 import org.apache.hc.core5.net.NamedEndpoint;
41 import org.apache.hc.core5.reactor.ConnectionInitiator;
42 import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
43 import org.apache.hc.core5.reactor.IOEventHandlerFactory;
44 import org.apache.hc.core5.reactor.IOReactorConfig;
45 import org.apache.hc.core5.reactor.IOSession;
46 import org.apache.hc.core5.util.Args;
47 import org.apache.hc.core5.util.Timeout;
48
49 public class AsyncRequester extends IOReactorExecutor<DefaultConnectingIOReactor> implements ConnectionInitiator {
50
51 public AsyncRequester(final IOReactorConfig ioReactorConfig) {
52 super(ioReactorConfig, null);
53 }
54
55 @Override
56 DefaultConnectingIOReactor createIOReactor(
57 final IOEventHandlerFactory ioEventHandlerFactory,
58 final IOReactorConfig ioReactorConfig,
59 final ThreadFactory threadFactory,
60 final Callback<IOSession> sessionShutdownCallback) throws IOException {
61 return new DefaultConnectingIOReactor(
62 ioEventHandlerFactory,
63 ioReactorConfig,
64 threadFactory,
65 LoggingIOSessionDecorator.INSTANCE,
66 LoggingExceptionCallback.INSTANCE,
67 LoggingIOSessionListener.INSTANCE,
68 sessionShutdownCallback);
69 }
70
71 private InetSocketAddress toSocketAddress(final HttpHost host) {
72 int port = host.getPort();
73 if (port < 0) {
74 final String scheme = host.getSchemeName();
75 if (URIScheme.HTTP.same(scheme)) {
76 port = 80;
77 } else if (URIScheme.HTTPS.same(scheme)) {
78 port = 443;
79 }
80 }
81 final String hostName = host.getHostName();
82 return new InetSocketAddress(hostName, port);
83 }
84
85 public Future<IOSession> requestSession(final HttpHost host, final Timeout timeout, final FutureCallback<IOSession> callback) {
86 Args.notNull(host, "Host");
87 return reactor().connect(host, toSocketAddress(host), null, timeout, null, callback);
88 }
89
90 @Override
91 public Future<IOSession> connect(
92 final NamedEndpoint remoteEndpoint,
93 final SocketAddress remoteAddress,
94 final SocketAddress localAddress,
95 final Timeout timeout,
96 final Object attachment,
97 final FutureCallback<IOSession> callback) {
98 return reactor().connect(remoteEndpoint, remoteAddress, localAddress, timeout, attachment, callback);
99 }
100
101 }