OSGi Bundles…creating reference to BundleContext

This week I was tasked with a relatively complex task by a client, which is requiring me to create an OSGi component that directly interacts with other OSGi services within the repository. My experience with OSGi being relatively minimal, I ran into a little snag: how to reference other OSGi services (a service can be an Interface or a Component) in the repository from MY OSGi component.

As much as it seems like this should be simple, it actually is not. OSGi components are compiled from .java files, and within those .java files, there are really no inherent references to any global objects. Whereas in an .esp or .jsp script, you have inherent reference to the “sling” object (among others), here you have to create your own references in order to take advantage of the other OSGi services that are already registered in the repository.

The first thing you have to do is create an “activate” method. This creates a means to store the ComponentContext object that is passed into your component as the repository activates it. Mine looks something like this:

protected BundleContext context;

protected void activate(ComponentContext c) throws Exception {
    context = c.getBundleContext();

You can note that, while the repository passes in a ComponentContext object, I actually needed a BundleContext object to be stored at a class level, so I retrieve this by calling the “getBundleContext()” method on the ComponentContext object. This will effectively give you a class-level reference to your BundleContext for use later.

Skip ahead to where I actually make use of this BundleContext, and I did something like the following to pull out a reference to the ResourceCollectionManager interface:

ServiceReference rcmRef = context.getServiceReference(ResourceCollectionManager.class.getName());
ResourceCollectionManager rcManager = (ResourceCollectionManager) context.getService(rcmRef);

Now, perhaps this seems like a small amount of effort and code, and indeed it is, but it’s also just a tiny bit counter-intuitive, and the fact is that there is very little actual documentation on OSGi out there. You really has to wade through a lot of useless information delivered via a Google search before you’ll piece together bits and pieces of what you need to know about something like this, so I figured I’d just go ahead and post a very simple example all in one place.


Leave a Reply

You must be logged in to post a comment.