Loading of OSGi bundle dynamically from a file sys

2020-02-09 22:57发布

问题:

I have a modular application which uses OSGi framework. Here I'm using org.eclipse.equinox.common_3.4.0 OSGi container. So now the application is already running with all the osgi bundles installed and active and I am displaying all the active OSGi bundles on the UI, by looping though a hash map, based on some action. Now the requirement is, while the application is already running, I want to instal a new OSGi bundle, from a file system, by giving this new bundle to the application's OSGi container so that it will start this bundle.

How do I achieve this ? I have tried reading the OSGi bundle as a JarInputstream and read the bundle activator fully qualified class path and tried to instantiate this using Class.forName("") and type casted to BundleActivator interface. But while starting it, it is taking bundle context as a argument to start method.

Is there way where I can just give the OSGi bundle to the container pragmatically so that it will take care of installing and starting the bundle and then my UI will automatically picks up this new bundle name in the display.

回答1:

Assuming you have the file to load, you can install the bundle like:

void install( BundleContext context, File file) throws Exception {
    Bundle b = context.installBundle( file.toURI().toString() );
    b.start();
}

And you can uninstall it (if the file is gone):

void uninstall( BundleContext context, File file) throws Exception {
    Bundle b = context.getBundle( file.toURI().toString() );
    b.uninstall();
}

You get the BundleContext from your activate or Declarative services component's activate method. These are the recommended methods but in dire cases you can also use:

BundleContext context = FrameworkUtil.getBundle( this.getClass() ).getBundleContext();

Though handy it bypasses some mechanism that you might want to use in the future so getting the context in the recommended way is much better