wiki:HowToUseOsgiService

How To Use an OSGi Service

xeraph ( xeraph@nchovy.com)

Almost all kraken bundles export  OSGi service. At least, they implement and export  ScriptFactory service interface. The core interface of OSGi is  BundleContext interface. Through this interface, you can register or unregister service, search service reference, and get service object.

I excerpted most frequently used methods:

public interface BundleContext {
	ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException;
	ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException;
	ServiceReference getServiceReference(String clazz);

	ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties);
	ServiceRegistration registerService(String clazz, Object service, Dictionary properties);

	Object getService(ServiceReference reference);

	..omitted..
}

That is, you need  BundleContext to do whatever you want. Then where is BundleContext reference? The answer is  BundleActivator. Every valid OSGi bundle has OSGi manifest in MANIFEST.MF metadata. One of them is Bundle-Activator, and it describes class name which implements BundleActivator interface.

public interface BundleActivator {
	void start(BundleContext context) throws Exception;

	void stop(BundleContext context) throws Exception;
}

OSGi container invokes BundleActivator.start(BundleContext) at bundle startup, and invokes BundleActivator.stop(BundleContext) at bundle stop.  BundleActivator is the entry point in OSGi world. If you feel hard to understand, just think it as main(). You can obtain bundle context from bundle activator.

At this point, you can get any OSGi service or register new OSGi service. For example, if you installed kraken-geoip bundle and started it, you can use  GeoIpService like this:

BundleContext bc;
ServiceReference reference = bc.getServiceReference(GeoIpService.class.getName());
GeoIpService geoip = (GeoIpService) bc.getService(reference);

It's a bit complicated, but it's cost of dynamic plugin system.  iPOJO simplifies and reduces this complexity drastically.