Skip to content

Instantly share code, notes, and snippets.

@valotas
Created May 1, 2012 13:43
Show Gist options
  • Save valotas/2568004 to your computer and use it in GitHub Desktop.
Save valotas/2568004 to your computer and use it in GitHub Desktop.
Jersey + Guice + Grizzly
public class GrizzlyWebServer {
private static final Logger logger = LoggerFactory.getLogger(GrizzlyWebServerService.class);
public static final void main(String[] args) throws IllegalArgumentException, IOException {
HttpServer server = startWebServer();
System.out.println("Jersey started");
if (logger.isInfoEnabled()) {
logger.info("Jersey web app started with Grizzly web container");
}
System.in.read();
server.stop();
System.exit(0);
}
/**
* Start the grizzly web container as described at
* http://blog.msbbc.co.uk/2008/11/java-using-jersey-and-grizzly-to-create.html
*
* @return
* @throws IOException
*/
private static HttpServer startWebServer() throws IOException {
SLF4JBridgeHandler.install();
URI u = baseURI();
HttpServer server = createHttpServer(u);
WebappContext context = createWebappContext(u.getPath());
context.deploy(server);
return server;
}
private static URI baseURI() {
return UriBuilder
.fromUri("http://localhost:8080/")
.build();
}
private static final WebappContext createWebappContext(String path) {
if (path == null) throw new NullPointerException("Can not create WebappContext with a null context path");
if ("/".equals(path)) path = ""; //In order for Guice to work ok
WebappContext context = new WebappContext(GrizzlyWebServerService.class.getSimpleName() + "Context", path);
context.addListener(MediacdnServletContextListener.class);
context.addFilter(GuiceFilter.class.getName(), GuiceFilter.class)
.addMappingForUrlPatterns(null, "/*");
return context;
}
// As per https://blogs.oracle.com/oleksiys/entry/grizzly_2_0_httpserver_api
private static HttpServer createHttpServer(URI u) throws IOException {
HttpServer server = new HttpServer();
NetworkListener listener = new NetworkListener("grizzly-listener", u.getHost(), u.getPort());
server.addListener(listener);
server.getServerConfiguration()
.addHttpHandler(
new StaticHttpHandler("/path/to/the/static/files"),
"/");
server.start();
return server;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment