Eclipse has a nice tutorial on how to embed a Jetty server in an OSGI framework. Unfortunately, this tutorial doesn’t help you if you want to run the server in a standalone Eclipse RCP application. One use case where you need to have a web server in your RCP application is when your application need to be able to be called by an external entity.
Fortunately, as pointed by the tutorial, Eclipse has provided a Jetty plugin in its Java IDE. The documentation of Eclipse is provided using this Jetty server.
So, how do you embed a Jetty server in your Eclipse RCP application? I assume you already have a grasp knowledge on how to create a RCP application (after all, Eclipse provided you with a simple generator for that).
First, let’s add the jetty plugin to our dependencies. Open the tab ‘Dependencies’ in your plugin configuration. Then add these six plugins to the ‘Required Plug-ins’:
This is actually all that we need. However, the OSGI framework will not activate these plugins automatically. And since there is no code in your application that actually refers to these plugins, they will not be activated at all! We have to force the framework to run these plugins from start. It can be done by changing the ‘Auto-Start’ value from your Run configuration.
In the list of plugins included at the launch of application you need to change the ‘Auto-Start’ value for three plugins to true (if you are lazy, you can turn the default behavior to auto start but this is another concern):
Now if you run the application you can check if your server is correctly running by accessing ‘http://localhost’. This should work flawlessly except maybe if you are not allowed to run server in port 80 or there is already a server running in port 80.
You can change the port by adding an argument to the VM arguments in ‘Run Configurations’. Add this value: ‘-Dorg.eclipse.equinox.http.jetty.http.port=8888’. Change ‘8888’ to whatever port you want the server to be running.
Now if you are running the application, you can access it from the port you mentioned before.
The next task is to define one (or several) servlet(s) that will serve any request the server gets. To do this, you need to open the ‘Extensions’ tab from your plugin configuration and add a new extension named ‘org.eclipse.equinox.http.registry.servlets’. After that add new ‘servlet’. You need to mention the class name of the servlet, and an alias for that. One note here is you need to add slash in front of the alias. For example, if you want to make the servlet accessible from ‘http://localhost:8888/webserviceInterface’, then the alias value is ‘/webserviceInterface’. Of course, you need to implement a servlet which will do the work you want.
Now sit down, run the application, and enjoy the service from your web server (running directly from your RCP application)!