tags:

views:

28

answers:

2

Inside one of my implementation libraries I want to know from which user library request is coming from?

Bundle A ClientCode -- > ServiceInterface

Bundle B ClientCode -- > ServiceInterface

Bundle C ServiceInterface ServiceImpl.

And those interfaces are resolved by one of impl. bundles (Bundle C). Inside that bundle I want to know from which bundle request is coming from (A or B)?

Thanks.

A: 

You could add a parameter for the BundleContext to your interface methods. Then, when the client code calls into your service, passing in its bundle context, you can call context.getBundle().getSymbolicName() or other methods to get information about the bundle from which the call came.

Critical Failure
A: 

The correct way to do this is to use a ServiceFactory, as explained in the OSGi specification. If you register your service as a service factory, you can supply an implementation for each "client" (where "client" is defined as bundle, invoking your service). This allows you to know who is invoking you, without the client having to specify anything as it's clearly not good design to add a parameter called BundleContext (unless there is no other way).

Some "pseudo" code:

class Bundle_C_Activator implements BundleActivator {
  public void start(BundleContext c) {
    c.registerService(ServiceInterface.class.getName(),
      new ServiceFactory() {
        Object getService(Bundle b, ServiceRegistration r) {
          return new ServiceImpl(b); // <- here you hold on to the invoking bundle
        }
        public void ungetService(Bundle b, ServiceRegistration r, Object s) {}
      }, null);
  }
}

class ServiceImpl implements ServiceInterface {
  ServiceImpl(Bundle b) {
    this.b = b; // <- so we know who is invoking us later
  }
  // proceed here with the implementation...
}
Marcel Offermans