2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.httpserver;
23 import jalview.bin.ApplicationSingletonProvider;
24 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
25 import jalview.rest.RestHandler;
27 import java.net.BindException;
29 import java.util.Collections;
30 import java.util.HashMap;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
36 import org.eclipse.jetty.server.Handler;
37 import org.eclipse.jetty.server.Server;
38 import org.eclipse.jetty.server.ServerConnector;
39 import org.eclipse.jetty.server.handler.ContextHandler;
40 import org.eclipse.jetty.server.handler.HandlerCollection;
41 import org.eclipse.jetty.util.thread.QueuedThreadPool;
44 * An HttpServer built on Jetty. To use it
46 * <li>call getInstance() to create and start the server</li>
47 * <li>call registerHandler to add a handler for a path (below /jalview)</li>
48 * <li>when finished, call removedHandler</li>
52 * @see http://eclipse.org/jetty/documentation/current/embedding-jetty.html
54 public class HttpServer implements ApplicationSingletonI
57 * Returns the singleton instance of this class.
60 * @throws BindException
62 public static HttpServer getInstance() throws BindException
64 synchronized (HttpServer.class)
66 return (HttpServer) ApplicationSingletonProvider.getInstance(HttpServer.class);
71 * Private constructor to enforce use of singleton
73 * @throws BindException
74 * if no free port can be assigned
76 private HttpServer() throws BindException
81 * Provides a REST server by default; add more programmatically as required
83 registerHandler(RestHandler.getInstance());
88 * 'context root' - actually just prefixed to the path for each handler for
89 * now - see registerHandler
91 private static final String JALVIEW_PATH = "jalview";
96 private Server server;
99 * Registered handlers for context paths
101 private HandlerCollection contextHandlers;
104 * Lookup of ContextHandler by its wrapped handler
106 Map<Handler, ContextHandler> myHandlers = new HashMap<Handler, ContextHandler>();
109 * The context root for the server
111 private URI contextRoot;
115 * Start the http server
117 * @throws BindException
119 private void startServer() throws BindException
124 * Create a server with a small number of threads; jetty will allocate a
127 QueuedThreadPool tp = new QueuedThreadPool(4, 1); // max, min
128 server = new Server(tp);
129 // 2 selector threads to handle incoming connections
130 ServerConnector connector = new ServerConnector(server, 0, 2);
131 // restrict to localhost
132 connector.setHost("localhost");
133 server.addConnector(connector);
136 * HttpServer shuts down with Jalview process
138 server.setStopAtShutdown(true);
141 * Create a mutable set of handlers (can add handlers while the server is
142 * running). Using vanilla handlers here rather than servlets
144 // TODO how to properly configure context root "/jalview"
145 contextHandlers = new HandlerCollection(true);
146 server.setHandler(contextHandlers);
148 // System.out.println(String.format(
149 // "HttpServer started with %d threads", server.getThreadPool()
151 contextRoot = server.getURI();
152 } catch (Exception e)
155 "Error trying to start HttpServer: " + e.getMessage());
159 } catch (Exception e1)
161 e1.printStackTrace();
166 throw new BindException("HttpServer failed to allocate a port");
171 * Returns the URI on which we are listening
177 return server == null ? null : server.getURI();
181 * For debug - write HTTP request details to stdout
186 protected void dumpRequest(HttpServletRequest request,
187 HttpServletResponse response)
189 for (String hdr : Collections.list(request.getHeaderNames()))
191 for (String val : Collections.list(request.getHeaders(hdr)))
193 System.out.println(hdr + ": " + val);
196 for (String param : Collections.list(request.getParameterNames()))
198 for (String val : request.getParameterValues(param))
200 System.out.println(param + "=" + val);
206 * Stop the Http server.
208 public void stopServer()
212 if (server.isStarted())
217 } catch (Exception e)
219 System.err.println("Error stopping Http Server on "
220 + server.getURI() + ": " + e.getMessage());
227 * Register a handler for the given path and set its URI
231 * @throws IllegalStateException
232 * if handler path has not been set
234 public void registerHandler(AbstractRequestHandler handler)
236 String path = handler.getPath();
239 throw new IllegalStateException(
240 "Must set handler path before registering handler");
243 // http://stackoverflow.com/questions/20043097/jetty-9-embedded-adding-handlers-during-runtime
244 ContextHandler ch = new ContextHandler();
245 ch.setAllowNullPathInfo(true);
246 ch.setContextPath("/" + JALVIEW_PATH + "/" + path);
247 ch.setResourceBase(".");
248 ch.setClassLoader(Thread.currentThread().getContextClassLoader());
249 ch.setHandler(handler);
252 * Remember the association so we can remove it later
254 this.myHandlers.put(handler, ch);
257 * A handler added to a running server must be started explicitly
259 contextHandlers.addHandler(ch);
263 } catch (Exception e)
266 "Error starting handler for " + path + ": " + e.getMessage());
269 handler.setUri(this.contextRoot + ch.getContextPath().substring(1));
270 System.out.println("Jalview " + handler.getName()
271 + " handler started on " + handler.getUri());
275 * Removes the handler from the server; more precisely, remove the
276 * ContextHandler wrapping the specified handler
280 public void removeHandler(AbstractRequestHandler handler)
283 * Have to use this cached lookup table since there is no method
284 * ContextHandler.getHandler()
286 ContextHandler ch = myHandlers.get(handler);
289 contextHandlers.removeHandler(ch);
290 myHandlers.remove(handler);
291 System.out.println("Stopped Jalview " + handler.getName()
292 + " handler on " + handler.getUri());