1 package de.mxro.webapiexample.internal;
2
3 import org.eclipse.jetty.server.Connector;
4 import org.eclipse.jetty.server.Server;
5 import org.eclipse.jetty.server.ServerConnector;
6 import org.eclipse.jetty.servlet.ServletContextHandler;
7
8 import de.mxro.webapiexample.WebApiServer;
9 import de.mxro.webapiexample.internal.services.ApplicationMetadataServlet;
10 import de.mxro.webapiexample.internal.services.HealthServlet;
11 import de.mxro.webapiexample.internal.services.HelloWorldServlet;
12
13
14
15
16
17
18 public class WebApiServerImpl implements WebApiServer {
19
20 private Boolean started;
21 private Server server;
22
23 public void start(int port) {
24
25 synchronized (started) {
26 if (started) {
27 throw new IllegalStateException("This server is already started.");
28 }
29 started = true;
30 }
31
32 server = new Server();
33 ServerConnector connector = new ServerConnector(server);
34 connector.setPort(port);
35 server.setConnectors(new Connector[] { connector });
36
37
38
39 ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
40 context.setContextPath("/");
41 server.setHandler(context);
42
43 context.addServlet(HealthServlet.class, "/health");
44 context.addServlet(HelloWorldServlet.class, "/hello-world");
45 context.addServlet(ApplicationMetadataServlet.class, "/meta");
46
47 try {
48 server.start();
49
50 } catch (Exception e) {
51 throw new RuntimeException(e);
52 }
53
54 }
55
56 public void stop() {
57 synchronized (started) {
58 if (!started) {
59 throw new IllegalStateException("This server is not running.");
60 }
61 }
62
63
64 synchronized (server) {
65
66 try {
67 server.stop();
68 server = null;
69 } catch (Exception e) {
70 throw new RuntimeException(e);
71 }
72 }
73
74 }
75
76 public WebApiServerImpl() {
77 super();
78 this.started = false;
79 this.server = null;
80 }
81
82 }