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.rest.RestHandler;
25 import java.net.BindException;
27 import java.util.Collections;
28 import java.util.HashMap;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
34 import org.eclipse.jetty.server.Handler;
35 import org.eclipse.jetty.server.Server;
36 import org.eclipse.jetty.server.ServerConnector;
37 import org.eclipse.jetty.server.handler.ContextHandler;
38 import org.eclipse.jetty.server.handler.HandlerCollection;
39 import org.eclipse.jetty.util.thread.QueuedThreadPool;
42 * An HttpServer built on Jetty. To use it
44 * <li>call getInstance() to create and start the server</li>
45 * <li>call registerHandler to add a handler for a path (below /jalview)</li>
46 * <li>when finished, call removedHandler</li>
50 * @see http://eclipse.org/jetty/documentation/current/embedding-jetty.html
52 public class HttpServer
55 * 'context root' - actually just prefixed to the path for each handler for
56 * now - see registerHandler
58 private static final String JALVIEW_PATH = "jalview";
61 * Singleton instance of this server
63 private static HttpServer instance;
68 private Server server;
71 * Registered handlers for context paths
73 private HandlerCollection contextHandlers;
76 * Lookup of ContextHandler by its wrapped handler
78 Map<Handler, ContextHandler> myHandlers = new HashMap<Handler, ContextHandler>();
81 * The context root for the server
83 private URI contextRoot;
86 * Returns the singleton instance of this class.
89 * @throws BindException
91 public static HttpServer getInstance() throws BindException
93 synchronized (HttpServer.class)
97 instance = new HttpServer();
104 * Private constructor to enforce use of singleton
106 * @throws BindException
107 * if no free port can be assigned
109 private HttpServer() throws BindException
114 * Provides a REST server by default; add more programmatically as required
116 registerHandler(RestHandler.getInstance());
120 * Start the http server
122 * @throws BindException
124 private void startServer() throws BindException
129 * Create a server with a small number of threads; jetty will allocate a
132 QueuedThreadPool tp = new QueuedThreadPool(4, 1); // max, min
133 server = new Server(tp);
134 // 2 selector threads to handle incoming connections
135 ServerConnector connector = new ServerConnector(server, 0, 2);
136 // restrict to localhost
137 connector.setHost("localhost");
138 server.addConnector(connector);
141 * HttpServer shuts down with Jalview process
143 server.setStopAtShutdown(true);
146 * Create a mutable set of handlers (can add handlers while the server is
147 * running). Using vanilla handlers here rather than servlets
149 // TODO how to properly configure context root "/jalview"
150 contextHandlers = new HandlerCollection(true);
151 server.setHandler(contextHandlers);
153 // System.out.println(String.format(
154 // "HttpServer started with %d threads", server.getThreadPool()
156 contextRoot = server.getURI();
157 } catch (Exception e)
159 System.err.println("Error trying to start HttpServer: "
164 } catch (Exception e1)
166 e1.printStackTrace();
171 throw new BindException("HttpServer failed to allocate a port");
176 * Returns the URI on which we are listening
182 return server == null ? null : server.getURI();
186 * For debug - write HTTP request details to stdout
191 protected void dumpRequest(HttpServletRequest request,
192 HttpServletResponse response)
194 for (String hdr : Collections.list(request.getHeaderNames()))
196 for (String val : Collections.list(request.getHeaders(hdr)))
198 System.out.println(hdr + ": " + val);
201 for (String param : Collections.list(request.getParameterNames()))
203 for (String val : request.getParameterValues(param))
205 System.out.println(param + "=" + val);
211 * Stop the Http server.
213 public void stopServer()
217 if (server.isStarted())
222 } catch (Exception e)
224 System.err.println("Error stopping Http Server on "
225 + server.getURI() + ": " + e.getMessage());
232 * Register a handler for the given path and set its URI
236 * @throws IllegalStateException
237 * if handler path has not been set
239 public void registerHandler(AbstractRequestHandler handler)
241 String path = handler.getPath();
244 throw new IllegalStateException(
245 "Must set handler path before registering handler");
248 // http://stackoverflow.com/questions/20043097/jetty-9-embedded-adding-handlers-during-runtime
249 ContextHandler ch = new ContextHandler();
250 ch.setAllowNullPathInfo(true);
251 ch.setContextPath("/" + JALVIEW_PATH + "/" + path);
252 ch.setResourceBase(".");
253 ch.setClassLoader(Thread.currentThread().getContextClassLoader());
254 ch.setHandler(handler);
257 * Remember the association so we can remove it later
259 this.myHandlers.put(handler, ch);
262 * A handler added to a running server must be started explicitly
264 contextHandlers.addHandler(ch);
268 } catch (Exception e)
270 System.err.println("Error starting handler for " + path + ": "
274 handler.setUri(this.contextRoot + ch.getContextPath().substring(1));
275 System.out.println("Jalview " + handler.getName()
276 + " handler started on " + handler.getUri());
280 * Removes the handler from the server; more precisely, remove the
281 * ContextHandler wrapping the specified handler
285 public void removeHandler(AbstractRequestHandler handler)
288 * Have to use this cached lookup table since there is no method
289 * ContextHandler.getHandler()
291 ContextHandler ch = myHandlers.get(handler);
294 contextHandlers.removeHandler(ch);
295 myHandlers.remove(handler);
296 System.out.println("Stopped Jalview " + handler.getName()
297 + " handler on " + handler.getUri());