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.extension;
29
30 import java.io.IOException;
31 import java.util.function.Consumer;
32
33 import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
34 import org.apache.hc.core5.http2.impl.nio.bootstrap.H2ServerBootstrap;
35 import org.apache.hc.core5.http2.ssl.H2ServerTlsStrategy;
36 import org.apache.hc.core5.io.CloseMode;
37 import org.apache.hc.core5.testing.SSLTestContexts;
38 import org.apache.hc.core5.testing.nio.LoggingExceptionCallback;
39 import org.apache.hc.core5.testing.nio.LoggingH2StreamListener;
40 import org.apache.hc.core5.testing.nio.LoggingHttp1StreamListener;
41 import org.apache.hc.core5.testing.nio.LoggingIOSessionDecorator;
42 import org.apache.hc.core5.testing.nio.LoggingIOSessionListener;
43 import org.junit.jupiter.api.Assertions;
44 import org.junit.jupiter.api.extension.AfterEachCallback;
45 import org.junit.jupiter.api.extension.BeforeEachCallback;
46 import org.junit.jupiter.api.extension.ExtensionContext;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 public class H2AsyncServerResource implements BeforeEachCallback, AfterEachCallback {
51
52 private static final Logger LOG = LoggerFactory.getLogger(H2AsyncServerResource.class);
53
54 private final Consumer<H2ServerBootstrap> bootstrapCustomizer;
55
56 private HttpAsyncServer server;
57
58 public H2AsyncServerResource(final Consumer<H2ServerBootstrap> bootstrapCustomizer) {
59 this.bootstrapCustomizer = bootstrapCustomizer;
60 }
61
62 @Override
63 public void beforeEach(final ExtensionContext extensionContext) throws Exception {
64 LOG.debug("Starting up test server");
65
66 final H2ServerBootstrap bootstrap = H2ServerBootstrap.bootstrap()
67 .setTlsStrategy(new H2ServerTlsStrategy(SSLTestContexts.createServerSSLContext()))
68 .setStreamListener(LoggingHttp1StreamListener.INSTANCE_SERVER)
69 .setStreamListener(LoggingH2StreamListener.INSTANCE)
70 .setIOSessionDecorator(LoggingIOSessionDecorator.INSTANCE)
71 .setExceptionCallback(LoggingExceptionCallback.INSTANCE)
72 .setIOSessionListener(LoggingIOSessionListener.INSTANCE);
73 bootstrapCustomizer.accept(bootstrap);
74 server = bootstrap.create();
75 }
76
77 @Override
78 public void afterEach(final ExtensionContext extensionContext) throws Exception {
79 LOG.debug("Shutting down test server");
80 if (server != null) {
81 try {
82 server.close(CloseMode.IMMEDIATE);
83 } catch (final Exception ignore) {
84 }
85 }
86 }
87
88 public HttpAsyncServer start() throws IOException {
89 Assertions.assertNotNull(server);
90 server.start();
91 return server;
92 }
93
94 }