1 package org.simantics.scl.rest;
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 import org.eclipse.jetty.servlet.ServletHolder;
8 import org.glassfish.jersey.jackson.JacksonFeature;
9 import org.glassfish.jersey.media.multipart.MultiPartFeature;
10 import org.glassfish.jersey.server.ResourceConfig;
11 import org.glassfish.jersey.servlet.ServletContainer;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
15 public class SCLRESTServer {
17 private static final Logger LOGGER = LoggerFactory.getLogger(SCLRESTServer.class);
19 private static SCLRESTServer INSTANCE = null;
20 private static Server server;
21 private static ServiceServerThread serverThread;
23 private SCLRESTServer(String token, int preferablePort) {
24 ResourceConfig config = new ResourceConfig();
25 // JSON serialization/deserialization
26 config.register(JacksonFeature.class);
28 config.register(MultiPartFeature.class);
30 config.register(SCLRESTAPI.class);
32 config.register(new AuthorizationFilter(token));
34 ServletHolder holder = new ServletHolder(new ServletContainer(config));
36 server = new Server();
37 ServerConnector connector = new ServerConnector(server);
38 connector.setPort(preferablePort);
40 server.setConnectors(new Connector[] { connector });
42 ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
43 context.addServlet(holder, "/*");
46 private static class ServiceServerThread extends Thread {
53 } catch (Exception e) {
54 LOGGER.error("Could not start server ", e);
59 private static synchronized SCLRESTServer getInstance(String token, int port) {
61 if (INSTANCE == null) {
62 INSTANCE = new SCLRESTServer(token, port);
64 } catch (Exception e) {
65 LOGGER.error("Could not initialize SCL REST server", e);
70 public static synchronized void start(String token, int port) throws Exception {
71 // Ensure that an instance is created
72 getInstance(token, port);
73 if (serverThread == null && server != null) {
74 serverThread = new ServiceServerThread();
79 public static synchronized void stop() throws Exception {