I have recently started using OSGi framework. I am trying to launch an OSGi framework from Java main application. I was following this tutorial to embed OSGI container into my project.
Below is my Java main application which I am using to launch an OSGi container. In the below class, I am able to get BundleContext
using the framework
object and then I can use this BundleContext
to install actual OSGi bundles
.
public class OSGiBundleTest1 {
public static Framework framework = null;
public static void main(String[] args) throws BundleException {
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Map<String, String> config = new HashMap<String, String>();
framework = frameworkFactory.newFramework(config);
framework.start();
callMethod();
callMethodOfAnotherClass();
}
private static void callMethodOfAnotherClass() {
OSGiBundleTest2 ss = new OSGiBundleTest2();
ss.someMethod();
}
private static void callMethod() throws BundleException {
BundleContext context = framework.getBundleContext();
System.out.println(context);
}
}
Now this is my second class in the same maven based project. And I need to use BundleContext here as well. So I thought I can use FrameworkUtil.getBundle(OSGiBundleTest2.class).getBundleContext()
to get the BundleContext but it is not working here and I get NPE there. So that means, this class is not loaded by OSGi classloader. So now what is the best way to use BundleContext in the below class.
public class OSGiBundleTest2 {
public OSGiBundleTest2() {
}
public static void callMethodOfAnotherClass() {
System.out.println(FrameworkUtil.getBundle(OSGiBundleTest2.class));
BundleContext bundleContext = FrameworkUtil.getBundle(OSGiBundleTest2.class).getBundleContext();
}
}
callMethodOfAnotherClass
will get called from the OSGiBundleTest1 class. I am not thinking of passing framework
object to the constructor of OSGiBundleTest2 class or some method to use the framework object and then get the BundleContext from there... Is there any other way to do this thing?
Any way to make sure all the classes get loaded by OSGI classloader only?
The way to make sure classes get loaded by an OSGi classloader is to put them in bundles and actually use OSGi to load them.