Sunday, April 6, 2008

How to launch an OSGi runtime in your application with Equinox

Here's a useful code snippet for launching an OSGi runtime from within your application. This is useful where you want to use OSGi in your own application as a plug-in mechanism.

I use Equinox, the Eclipse OSGi implementation.


import org.eclipse.osgi.baseadaptor.BaseAdaptor;
import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
import org.eclipse.osgi.framework.internal.core.OSGi;

...

/**
* Launch the OSGi framework.
*
* @param installArea Directory path to where the OSGi bundles remain.
* @param configArea Direcotory path to where OSGi should store its configuration data.
*/
public void launchOsgi( String installArea, String configArea )
{
System.setProperty( "osgi.install.area", installArea );
System.setProperty( "osgi.configuration.area", configArea );
FrameworkAdaptor adaptor = new BaseAdaptor( null );
OSGi osgiInstance = new OSGi( adaptor );
osgiInstance.launch();
}

...


The installation area points to a location in the file system where you want to make your OSGi runtime believe it is "installed", i.e. where it would look for bundles if you used the install file:mybundle_1.0.0.jar command.

The config area points to the location where you want your OSGi runtime to store configuration information about bundles you install while it is running. As you probably know, OSGi stores information about every bundle you install such that upon the next restart, you will not have to install all bundles from scratch again.

Instead of setting system properties, which is admittedly a bit cumbersome, you could pass parameters to the BaseAdaptor constructor, but I havent figured out the parameter names yet :-)

From the OSGi instance you have created you can use osgiInstance.getBundleContext() to install and manage bundles.

That's basically all you need to build an OSGi-based plugin mechanism into your application.

Well, almost. Of course you will need to write some code to detect new bundles in the install area or other locations (at start time of your application or dynamically at runtime of your application). You could use functionality like Peter Kriens' FileInstall bundle, for example. Equinox has something similar but I have not looked at it yet :-)

I might cover this topic in one of my future posts.

1 comment:

astralarse said...

This works just fine, thank you for that. But how do I base that on my config.ini, because your solution doesn't seem to take any note of my config.ini file which is located unter configuration/.

Another question I have: How would you initialize a FrameworkConsole based on your solution? My FrameworkConsole console = new FrameworkConsole(osgiInstance, cmds) starts just fine when I invoke console.run(). But right after that any following code is just ignored completly. I don't even get a System.out in my finally-block in main(). Again: how would you do that? Thanks a lot!