Programmatic hot deploy with Jetty

aurelien.pupier
Blog Categories: 

Hot deployment - which consists in deploying an application without stopping the application server - can save a lot of time and of course, avoid interruption of service.

You may already know it, but Bonita Open Solution embeds Jetty when it comes to deploying your process-driven application. I tried to programmatically hot deploy an application with Jetty a few days ago but unfortunately didn't find any documentation on how to do this. After a lot of trial and error, I finally did it! I was mainly inspired from the depths of a mailing-list archive (BTW when will we have a Jetty forum?). Here is the results of my research...

I found several ways to use hot deployment with Jetty, including:

Context deployer. But this requires XML file configuration and replacing a war in a directory... and then waiting for a scan of the directory!!

OSGI service. This seems to be a great and easy solution but it also seems to be only available for Jetty 7.

And now it's high time to show you how to use hot deployment programmatically:

Note: As Bonita Open Solution is based on Eclipse 3.5, we are using Jetty version 6.

  1. Create the server: [cc lang="java" line_numbers="1"] Server jetty = new Server(); [/cc]
  2. Create a handlerCollection with a ContextHandlerCollection in it: [cc lang="java" line_numbers="1"] HandlerCollection hc = new HandlerCollection (); ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection(); hc.setHandlers(new Handler[]{contextHandlerCollection}); jetty.setHandler(hc); [/cc]
  3. Start the server: [cc lang="java" line_numbers="1"] jetty.start(); [/cc]
  4. Hot deploy your web application: [cc lang="java" line_numbers="1"] WebAppContext warWebappContext = new WebAppContext(); //configure it ... contextHandlerCollection.addHandler(warWebappContext); warWebappContext.start(); [/cc]
  5. Hot undeploy your application: [cc lang="java" line_numbers="1"] //get the WebAppContext to undeploy... WebAppContext toUndeploy = getWebAppContextToUndeploy(); //stop it toUndeploy.stop(); //and remove it from the handler collection contextHandlerCollection.removeHandler(toUndeploy); [/cc]

In a nutshell, the trick is to use a HandlerCollection for your WebAppContextHandler.

I hope that this article will help others to hot deploy with Jetty. You're welcome to  suggest better ways or to provide links to good documentation on this subject!

Notifications