This repository was archived by the owner on Sep 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathWebServer.java
More file actions
267 lines (225 loc) · 8.09 KB
/
WebServer.java
File metadata and controls
267 lines (225 loc) · 8.09 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/**
* Copyright (C) 2013 all@code-story.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package net.codestory.http;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.*;
import java.nio.file.Path;
import java.util.*;
import net.codestory.http.errors.*;
import net.codestory.http.filters.log.*;
import net.codestory.http.internal.*;
import net.codestory.http.misc.*;
import net.codestory.http.payload.*;
import net.codestory.http.reload.*;
import net.codestory.http.routes.*;
import net.codestory.http.servlet.WebServerConfig;
import net.codestory.http.ssl.*;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.*;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WebServer implements Filter {
private final static Logger LOG = LoggerFactory.getLogger(WebServer.class);
private Server server;
private RoutesProvider routesProvider;
private int port;
public WebServer() {
this(routes -> {
});
}
public WebServer(Configuration configuration) {
configure(configuration);
}
public static void main(String[] args) throws Exception {
new WebServer(routes -> routes
.filter(new LogRequestFilter()))
.start(8080);
}
public WebServer configure(Configuration configuration) {
routesProvider = Env.INSTANCE.prodMode()
? RoutesProvider.fixed(configuration)
: RoutesProvider.reloading(configuration);
return this;
}
public WebServer startOnRandomPort() {
Random random = new Random();
for (int i = 0; i < 20; i++) {
try {
int port = 8183 + random.nextInt(1000);
start(port);
return this;
} catch (Exception e) {
LOG.error("Unable to bind server", e);
}
}
throw new IllegalStateException("Unable to start server");
}
public WebServer start() {
return start(8080);
}
public WebServer start(int port) {
return startWithContext(port, null);
}
public WebServer startSSL(int port, Path pathCertificate, Path pathPrivateKey) {
SslContextFactory context;
try {
context = new SSLContextFactory().create(pathCertificate, pathPrivateKey);
} catch (Exception e) {
throw new IllegalStateException("Unable to read certificate or key", e);
}
return startWithContext(port, context);
}
private WebServer startWithContext(int port, SslContextFactory context) {
try {
this.port = Env.INSTANCE.overriddenPort(port);
embedded = true;
if (context == null) {
server = new Server(this.port);
} else {
server = new Server();
HttpConfiguration https = new HttpConfiguration();
https.addCustomizer(new SecureRequestCustomizer());
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(context, "http/1.1"),
new HttpConnectionFactory(https));
sslConnector.setPort(this.port);
server.addConnector(sslConnector);
}
ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
servletHandler.addFilter(new FilterHolder(this), "/*", EnumSet.of(DispatcherType.REQUEST));
server.setHandler(servletHandler);
server.start();
LOG.info("Server started on port {}", this.port);
} catch (RuntimeException e) {
throw e;
} catch (BindException e) {
throw new IllegalStateException("Port already in use " + this.port);
} catch (Exception e) {
throw new IllegalStateException("Unable to bind the web server on port " + this.port, e);
}
return this;
}
public int port() {
return port;
}
public void reset() {
configure(routes -> {
});
}
public void stop() {
try {
server.stop();
} catch (Exception e) {
throw new IllegalStateException("Unable to stop the web server", e);
}
}
protected void applyRoutes(RouteCollection routeCollection, Context context) throws IOException {
Payload payload = routeCollection.apply(context);
if (payload.isError()) {
payload = errorPage(payload);
}
payload.writeTo(context);
}
protected void handleServerError(Context context, Exception e) {
if (!(e instanceof HttpException)) {
e.printStackTrace();
}
try {
errorPage(e).writeTo(context);
} catch (IOException error) {
LOG.warn("Unable to serve an error page", error);
}
}
protected Payload errorPage(Payload payload) {
return errorPage(payload, null);
}
protected Payload errorPage(Exception e) {
int code = (e instanceof HttpException) ? ((HttpException) e).code() : 500;
return errorPage(new Payload(code), e);
}
protected Payload errorPage(Payload payload, Exception e) {
Exception shownError = Env.INSTANCE.prodMode() ? null : e;
return new ErrorPage(payload, shownError).payload();
}
private boolean embedded = false;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (embedded) {
return;
}
String configClassName = filterConfig.getInitParameter("configClass");
if (configClassName == null) {
throw new IllegalArgumentException("Parameter configClass must be specified for the filter.");
}
try {
Class<?> configClass = Class.forName(configClassName);
Constructor<?> constructor = configClass.getConstructor();
Object configObject = constructor.newInstance();
if (!(configObject instanceof WebServerConfig)) {
throw new IllegalArgumentException(configClassName + " must implement WebServerConfig");
}
WebServerConfig webServerConfig = (WebServerConfig) configObject;
webServerConfig.configure(this);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Parameter configClass must be set with a class", e);
} catch (NoSuchMethodException|InvocationTargetException|InstantiationException|IllegalAccessException e) {
throw new IllegalArgumentException(configClassName + " must have a public constructor with no args", e);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Context context = null;
try {
RouteCollection routes = routesProvider.get();
context = new Context((HttpServletRequest)request, (HttpServletResponse)response, routes.getIocAdapter());
applyRoutes(routes, context);
} catch (Exception e) {
if (context == null) {
// Didn't manage to initialize a full context
// because the routes failed to load
//
context = new Context((HttpServletRequest)request, (HttpServletResponse)response, null);
}
handleServerError(context, e);
} finally {
try {
response.getOutputStream().close();
} catch (IOException e) {
// Ignore
}
}
}
@Override
public void destroy() {
}
}