-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenApiServer.java
More file actions
220 lines (189 loc) · 7.33 KB
/
Copy pathOpenApiServer.java
File metadata and controls
220 lines (189 loc) · 7.33 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package com.retailsvc.http;
import static java.lang.Thread.ofVirtual;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.Executors.newThreadPerTaskExecutor;
import com.retailsvc.http.internal.DispatchHandler;
import com.retailsvc.http.internal.ExceptionFilter;
import com.retailsvc.http.internal.RequestPreparationFilter;
import com.retailsvc.http.internal.Router;
import com.retailsvc.http.spec.Spec;
import com.retailsvc.http.validate.DefaultValidator;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Set up an {@link HttpServer} exposing endpoints declared in an OpenAPI 3.1.x specification.
*
* @author thced
*/
public class OpenApiServer implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(OpenApiServer.class);
private static final int DEFAULT_PORT = 8080;
private final HttpServer httpServer;
private final int shutdownTimeoutSeconds;
/**
* @param spec The parsed {@link Spec}
* @param jsonMapper Body deserializer
* @param handlers Mappings between operationId and {@link HttpHandler}
* @param exceptionHandler Error handler receiving exceptions thrown from a handler
* @throws IOException If an error occurs during server start
*/
public OpenApiServer(
Spec spec,
JsonMapper jsonMapper,
Map<String, HttpHandler> handlers,
ExceptionHandler exceptionHandler)
throws IOException {
this(spec, jsonMapper, handlers, exceptionHandler, DEFAULT_PORT, Map.of(), 0);
}
/**
* @param spec The parsed {@link Spec}
* @param jsonMapper Body deserializer
* @param handlers Mappings between operationId and {@link HttpHandler}
* @param exceptionHandler Error handler receiving exceptions thrown from a handler
* @param port The server port to use
* @throws IOException If an error occurs during server start
*/
public OpenApiServer(
Spec spec,
JsonMapper jsonMapper,
Map<String, HttpHandler> handlers,
ExceptionHandler exceptionHandler,
int port)
throws IOException {
this(spec, jsonMapper, handlers, exceptionHandler, port, Map.of(), 0);
}
OpenApiServer(
Spec spec,
JsonMapper jsonMapper,
Map<String, HttpHandler> handlers,
ExceptionHandler exceptionHandler,
int port,
Map<String, HttpHandler> extras,
int shutdownTimeoutSeconds)
throws IOException {
requireNonNull(spec, "Spec must not be null");
requireNonNull(jsonMapper, "JsonMapper must not be null");
requireNonNull(handlers, "handlers must not be null");
if (exceptionHandler == null) {
LOG.warn("No ExceptionHandler set, using default");
exceptionHandler = Handlers.defaultExceptionHandler();
}
long t0 = System.currentTimeMillis();
Router router = new Router(spec.operations());
DefaultValidator validator = new DefaultValidator(spec::resolveSchema);
this.httpServer = HttpServer.create(new InetSocketAddress(port), 0);
httpServer.setExecutor(newThreadPerTaskExecutor(ofVirtual().name("http-", 0).factory()));
HttpContext ctx = httpServer.createContext(Optional.ofNullable(spec.basePath()).orElse("/"));
ctx.getFilters().add(new ExceptionFilter(exceptionHandler));
ctx.getFilters().add(new RequestPreparationFilter(spec, router, validator, jsonMapper));
ctx.setHandler(new DispatchHandler(handlers));
for (Map.Entry<String, HttpHandler> e : extras.entrySet()) {
HttpContext extraCtx = httpServer.createContext(e.getKey());
extraCtx.getFilters().add(new ExceptionFilter(exceptionHandler));
extraCtx.setHandler(e.getValue());
}
httpServer.createContext("/", Handlers.notFoundHandler());
httpServer.start();
this.shutdownTimeoutSeconds = shutdownTimeoutSeconds;
LOG.info("Server started (port {}) in {}ms", port, System.currentTimeMillis() - t0);
}
public int listenPort() {
return httpServer.getAddress().getPort();
}
/**
* Stops the server, waiting up to {@code delaySeconds} for active exchanges to finish before
* closing them. {@code 0} stops immediately.
*
* @param delaySeconds maximum seconds to wait for in-flight exchanges; must be non-negative
*/
public void stop(int delaySeconds) {
if (delaySeconds < 0) {
throw new IllegalArgumentException("delaySeconds must be non-negative, got " + delaySeconds);
}
if (httpServer != null) {
httpServer.stop(delaySeconds);
}
}
@Override
public void close() {
stop(shutdownTimeoutSeconds);
}
public static Builder builder() {
return new Builder();
}
/** Fluent builder for {@link OpenApiServer}. */
public static final class Builder {
private Spec spec;
private JsonMapper jsonMapper;
private Map<String, HttpHandler> handlers;
private ExceptionHandler exceptionHandler;
private int port = DEFAULT_PORT;
private int shutdownTimeoutSeconds = 0;
private final LinkedHashMap<String, HttpHandler> extras = new LinkedHashMap<>();
private Builder() {}
public Builder spec(Spec spec) {
this.spec = spec;
return this;
}
public Builder jsonMapper(JsonMapper jsonMapper) {
this.jsonMapper = jsonMapper;
return this;
}
public Builder handlers(Map<String, HttpHandler> handlers) {
this.handlers = handlers;
return this;
}
public Builder exceptionHandler(ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
public Builder port(int port) {
this.port = port;
return this;
}
/**
* Sets the default drain timeout used by {@link OpenApiServer#close()}. {@code 0} (the default)
* stops immediately; positive values wait up to that many seconds for in-flight exchanges to
* finish.
*/
public Builder shutdownTimeoutSeconds(int shutdownTimeoutSeconds) {
if (shutdownTimeoutSeconds < 0) {
throw new IllegalArgumentException(
"shutdownTimeoutSeconds must be non-negative, got " + shutdownTimeoutSeconds);
}
this.shutdownTimeoutSeconds = shutdownTimeoutSeconds;
return this;
}
public Builder addHandler(String path, HttpHandler handler) {
requireNonNull(path, "path must not be null");
requireNonNull(handler, "handler must not be null");
if (extras.containsKey(path)) {
throw new IllegalStateException("duplicate extra handler path: " + path);
}
extras.put(path, handler);
return this;
}
public OpenApiServer build() throws IOException {
requireNonNull(spec, "Spec must not be null");
requireNonNull(jsonMapper, "JsonMapper must not be null");
requireNonNull(handlers, "handlers must not be null");
String basePath = Optional.ofNullable(spec.basePath()).orElse("/");
for (String path : extras.keySet()) {
if (path.equals(basePath)) {
throw new IllegalStateException(
"extra handler path " + path + " conflicts with spec basePath " + basePath);
}
}
return new OpenApiServer(
spec, jsonMapper, handlers, exceptionHandler, port, extras, shutdownTimeoutSeconds);
}
}
}