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.http.localserver;
29
30 import java.util.concurrent.TimeUnit;
31
32 import org.apache.http.HttpHost;
33 import org.apache.http.config.SocketConfig;
34 import org.apache.http.impl.bootstrap.HttpServer;
35 import org.apache.http.impl.bootstrap.ServerBootstrap;
36 import org.apache.http.impl.client.CloseableHttpClient;
37 import org.apache.http.impl.client.HttpClientBuilder;
38 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
39 import org.junit.After;
40 import org.junit.Before;
41
42
43
44
45
46 public abstract class LocalServerTestBase {
47
48 public enum ProtocolScheme { http, https }
49
50 public static final String ORIGIN = "TEST/1.1";
51
52 protected final ProtocolScheme scheme;
53
54 protected ServerBootstrap serverBootstrap;
55 protected HttpServer server;
56 protected PoolingHttpClientConnectionManager connManager;
57 protected HttpClientBuilder clientBuilder;
58 protected CloseableHttpClient httpclient;
59
60 public LocalServerTestBase(final ProtocolScheme scheme) {
61 this.scheme = scheme;
62 }
63
64 public LocalServerTestBase() {
65 this(ProtocolScheme.http);
66 }
67
68 public String getSchemeName() {
69 return this.scheme.name();
70 }
71
72 @Before
73 public void setUp() throws Exception {
74 final SocketConfig socketConfig = SocketConfig.custom()
75 .setSoTimeout(15000)
76 .build();
77 this.serverBootstrap = ServerBootstrap.bootstrap()
78 .setSocketConfig(socketConfig)
79 .setServerInfo(ORIGIN)
80 .registerHandler("/echo/*", new EchoHandler())
81 .registerHandler("/random/*", new RandomHandler());
82 if (this.scheme.equals(ProtocolScheme.https)) {
83 this.serverBootstrap.setSslContext(SSLTestContexts.createServerSSLContext());
84 }
85
86 this.connManager = new PoolingHttpClientConnectionManager();
87 this.clientBuilder = HttpClientBuilder.create()
88 .setDefaultSocketConfig(socketConfig)
89 .setConnectionManager(this.connManager);
90 }
91
92 @After
93 public void shutDown() throws Exception {
94 if (this.httpclient != null) {
95 this.httpclient.close();
96 }
97 if (this.server != null) {
98 this.server.shutdown(10, TimeUnit.SECONDS);
99 }
100 }
101
102 public HttpHost start() throws Exception {
103 this.server = this.serverBootstrap.create();
104 this.server.start();
105
106 if (this.httpclient == null) {
107 this.httpclient = this.clientBuilder.build();
108 }
109
110 return new HttpHost("localhost", this.server.getLocalPort(), this.scheme.name());
111 }
112
113 }