This repository has been archived by the owner on Jun 2, 2021. It is now read-only.
forked from dropwizard/dropwizard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ContextRoutingHandler.java
61 lines (53 loc) · 1.95 KB
/
ContextRoutingHandler.java
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
package io.dropwizard.jetty;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandlerContainer;
import org.eclipse.jetty.util.ArrayTernaryTrie;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
/**
* A Jetty router which routes requests based on context path.
*/
public class ContextRoutingHandler extends AbstractHandlerContainer {
private final ArrayTernaryTrie<Handler> handlers;
public ContextRoutingHandler(Map<String, ? extends Handler> handlers) {
this.handlers = new ArrayTernaryTrie<>(false);
for (Map.Entry<String, ? extends Handler> entry : handlers.entrySet()) {
if (!this.handlers.put(entry.getKey(), entry.getValue())) {
throw new IllegalStateException("Too many handlers");
}
addBean(entry.getValue());
}
}
@Override
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
final Handler handler = handlers.getBest(baseRequest.getRequestURI());
if (handler != null) {
handler.handle(target, baseRequest, request, response);
}
}
@Override
protected void doStart() throws Exception {
super.doStart();
for (String key : handlers.keySet()) {
handlers.get(key).start();
}
}
@Override
protected void doStop() throws Exception {
super.doStop();
for (String key : handlers.keySet()) {
handlers.get(key).stop();
}
}
@Override
public Handler[] getHandlers() {
return handlers.entrySet().stream().map(Map.Entry::getValue).toArray(Handler[]::new);
}
}