user2992151
user2992151

Reputation: 3

Access OSGI bundle context in application

I'm trying to access to the context of OSGI bundle in a java application to obtain a running service.

ctx.getServiceReference(ReceiverService.class.getName());

I tried with this:

BundleContext ctx = FrameworkUtil.getBundle(ReceiverService.class).getBundleContext();

but it returns null

I init Knopflerfish in graphic mode with preinstalled bundles, and I start the SenderSevice bundle and the ReceiveService bundle. I want to access to ReceiveService to use the received objects in Java application. So I need to access to the ReceiveService bundle context.

Upvotes: 0

Views: 1104

Answers (2)

Neil Bartlett
Neil Bartlett

Reputation: 23948

Where is the ReceiveService interface loaded from? Is it exported from a bundle? Unfortunately the system bundle cannot import packages from ordinary bundles.

Since you are embedding OSGi, and communicating in terms of services between the outer application and the inner framework, the interfaces packages must be loaded by the outer application and exported using the org.osgi.framework.system.packages.extra property. This property is passed via the Map that you provide to FrameworkFactory.newFramework(). Then the ordinary bundles can import the service interface and publish the service.

To access a BundleContext from the outer application you must use the getBundleContext() method on the Framework object. This returns the BundleContext of the system bundle.

Upvotes: 1

Harald Wellmann
Harald Wellmann

Reputation: 12865

You seem to be using an OSGi framework embedded in a Java application - how did you start that framework?

The standard way would be

Framework framework = FrameworkFactory.newFramework(props);

Then you can get the system bundle context from the framework instance:

BundleContext ctx = framework.getBundleContext();

In your example, ReceiverService was most likely loaded by the application classloader and not by a bundle classloader, so FrameworkUtil cannot determine the bundle that loaded this class.

Upvotes: 2

Related Questions