JAL-1641 Further refactoring of JSON export option, introduction of Viewport to the...
[jalview.git] / src / jalview / httpserver / HttpServer.java
1 package jalview.httpserver;
2
3 import java.net.BindException;
4 import java.net.URI;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.Map;
8
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 import org.eclipse.jetty.server.Handler;
13 import org.eclipse.jetty.server.Server;
14 import org.eclipse.jetty.server.ServerConnector;
15 import org.eclipse.jetty.server.handler.ContextHandler;
16 import org.eclipse.jetty.server.handler.HandlerCollection;
17 import org.eclipse.jetty.util.thread.QueuedThreadPool;
18
19 import jalview.rest.RestHandler;
20
21 /**
22  * An HttpServer built on Jetty. To use it
23  * <ul>
24  * <li>call getInstance() to create and start the server</li>
25  * <li>call registerHandler to add a handler for a path (below /jalview)</li>
26  * <li>when finished, call removedHandler</li>
27  * </ul>
28  * 
29  * @author gmcarstairs
30  * @see http://eclipse.org/jetty/documentation/current/embedding-jetty.html
31  */
32 public class HttpServer
33 {
34   /*
35    * 'context root' - actually just prefixed to the path for each handler for
36    * now - see registerHandler
37    */
38   private static final String JALVIEW_PATH = "jalview";
39
40   /*
41    * Singleton instance of this server
42    */
43   private static HttpServer instance;
44
45   /*
46    * The Http server
47    */
48   private Server server;
49
50   /*
51    * Registered handlers for context paths
52    */
53   private HandlerCollection contextHandlers;
54
55   /*
56    * Lookup of ContextHandler by its wrapped handler
57    */
58   Map<Handler, ContextHandler> myHandlers = new HashMap<Handler, ContextHandler>();
59
60   /*
61    * The context root for the server
62    */
63   private URI contextRoot;
64
65   /**
66    * Returns the singleton instance of this class.
67    * 
68    * @return
69    * @throws BindException
70    */
71   public static HttpServer getInstance() throws BindException
72   {
73     synchronized (HttpServer.class)
74     {
75       if (instance == null) {
76         instance = new HttpServer();
77       }
78       return instance;
79     }
80   }
81
82   /**
83    * Private constructor to enforce use of singleton
84    * 
85    * @throws BindException
86    *           if no free port can be assigned
87    */
88   private HttpServer() throws BindException
89   {
90     startServer();
91
92     /*
93      * Provides a REST server by default; add more programmatically as required
94      */
95     registerHandler(RestHandler.getInstance());
96   }
97
98   /**
99    * Start the http server
100    * 
101    * @throws BindException
102    */
103   private void startServer() throws BindException
104   {
105     try
106     {
107       /*
108        * Create a server with a small number of threads; jetty will allocate a
109        * free port
110        */
111       QueuedThreadPool tp = new QueuedThreadPool(4, 1); // max, min
112       server = new Server(tp);
113       // 2 selector threads to handle incoming connections
114       ServerConnector connector = new ServerConnector(server, 0, 2);
115       server.addConnector(connector);
116
117       /*
118        * HttpServer shuts down with Jalview process
119        */
120       server.setStopAtShutdown(true);
121
122       /*
123        * Create a mutable set of handlers (can add handlers while the server is
124        * running). Using vanilla handlers here rather than servlets
125        */
126       // TODO how to properly configure context root "/jalview"
127       contextHandlers = new HandlerCollection(true);
128       server.setHandler(contextHandlers);
129       server.start();
130       // System.out.println(String.format(
131       // "HttpServer started with %d threads", server.getThreadPool()
132       // .getThreads()));
133       contextRoot = server.getURI();
134       System.out.println("Jalview endpoint " + contextRoot);
135     } catch (Exception e)
136     {
137       System.err.println("Error trying to start HttpServer: "
138               + e.getMessage());
139       try
140       {
141         server.stop();
142       } catch (Exception e1)
143       {
144         e1.printStackTrace();
145       }
146     }
147     if (server == null)
148     {
149       throw new BindException("HttpServer failed to allocate a port");
150     }
151   }
152
153   /**
154    * Returns the URI on which we are listening
155    * 
156    * @return
157    */
158   public URI getUri()
159   {
160     return server == null ? null : server.getURI();
161   }
162
163   /**
164    * For debug - write HTTP request details to stdout
165    * 
166    * @param request
167    * @param response
168    */
169   protected void dumpRequest(HttpServletRequest request,
170           HttpServletResponse response)
171   {
172     for (String hdr : Collections.list(request.getHeaderNames()))
173     {
174       for (String val : Collections.list(request.getHeaders(hdr)))
175       {
176         System.out.println(hdr + ": " + val);
177       }
178     }
179     for (String param : Collections.list(request.getParameterNames()))
180     {
181       for (String val : request.getParameterValues(param))
182       {
183         System.out.println(param + "=" + val);
184       }
185     }
186   }
187
188   /**
189    * Stop the Http server.
190    */
191   public void stopServer()
192   {
193     if (server != null)
194     {
195       if (server.isStarted())
196       {
197         try
198         {
199           server.stop();
200         } catch (Exception e)
201         {
202           System.err.println("Error stopping Http Server on "
203                   + server.getURI() + ": " + e.getMessage());
204         }
205       }
206     }
207   }
208
209   /**
210    * Register a handler for the given path and set its URI
211    * 
212    * @param handler
213    * @return
214    * @throws IllegalStateException
215    *           if handler path has not been set
216    */
217   public void registerHandler(AbstractRequestHandler handler)
218   {
219     String path = handler.getPath();
220     if (path == null)
221     {
222       throw new IllegalStateException(
223               "Must set handler path before registering handler");
224     }
225
226     // http://stackoverflow.com/questions/20043097/jetty-9-embedded-adding-handlers-during-runtime
227     ContextHandler ch = new ContextHandler();
228     ch.setAllowNullPathInfo(true);
229     ch.setContextPath("/" + JALVIEW_PATH + "/" + path);
230     ch.setResourceBase(".");
231     ch.setClassLoader(Thread.currentThread()
232             .getContextClassLoader());
233     ch.setHandler(handler);
234
235     /*
236      * Remember the association so we can remove it later
237      */
238     this.myHandlers.put(handler, ch);
239
240     /*
241      * A handler added to a running server must be started explicitly
242      */
243     contextHandlers.addHandler(ch);
244     try
245     {
246       ch.start();
247     } catch (Exception e)
248     {
249       System.err.println("Error starting handler for " + path + ": "
250               + e.getMessage());
251     }
252
253     handler.setUri(this.contextRoot + ch.getContextPath().substring(1));
254     System.out.println("Jalview " + handler.getName()
255             + " handler started on " + handler.getUri());
256   }
257
258   /**
259    * Removes the handler from the server; more precisely, remove the
260    * ContextHandler wrapping the specified handler
261    * 
262    * @param handler
263    */
264   public void removeHandler(Handler handler)
265   {
266     /*
267      * Have to use this cached lookup table since there is no method
268      * ContextHandler.getHandler()
269      */
270     ContextHandler ch = myHandlers.get(handler);
271     if (ch != null)
272     {
273       contextHandlers.removeHandler(ch);
274       myHandlers.remove(handler);
275     }
276   }
277 }