javaliferayosgiliferay-7wab

How can I obtain the BundleWiring of the calling Bundle in OSGi?


I have an active bundle called bundleA which implements a class called Example with a method called doSomething() from another bundle. ExampleImpl implements Example and is loaded via ServiceLoader (thanks to SPI Fly). In ExampleImpl.doSomething() from bundleA, I need to get the BundleWiring of the bundle which called doSomething() (without passing the Bundle or BundleContext since I cannot change the API). I can get bundleA's BundleWiring, but not the calling bundle's BundleWiring:

Bundle bundleA = FrameworkUtil.getBundle(ExampleClass.class);
BundleWiring bundleWiringOfBundleA = bundle.adapt(BundleWiring.class);

How can I obtain the calling bundle's BundleWiring?

In my particular case, the calling bundle will always be a WAB which happens to be running in Liferay Portal 7.0. So if there's a solution specific to Liferay Portal, I would accept that, but a more general OSGi solution would be fine as well.

Note that I want the calling bundle's bundle wiring not the bundle wiring of every bundle that depends on the current bundle wiring. I know that I can obtain the bundle wirings that are dependent on the current bundle wiring, but that won't help me obtain the calling bundle specifically:

Bundle bundleA = FrameworkUtil.getBundle(ExampleClass.class);
List<BundleWires> bundleWires =
    bundleWiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE);
bundleWires.get(0).getRequirerWiring();

Solution

  • In Liferay, the calling WAB's BundleContext is stored in the ServletContext as "osgi-bundlecontext":

    BundleContext bundleContext = servletContext.getAttribute("osgi-bundlecontext");
    Bundle bundle = bundleContext.getBundle();
    BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
    

    So as long as you have access to the ServletContext in Liferay you can obtain the calling bundle's Bundle and BundleWiring.