Track a Set of Services with Components
Purpose
Show how you can track a set of services in the service registry while they are being registered and unregistered dynamically. This snipppet uses a component's set and get methods to simplify handling the dynamics's.
For example, assume you implemented Configuration Admin and need to follow the Configuration Listener services so you can appropriately update them.
Prerequisites
- Log Service - org.osgi.service.log
- Http Service - org.osgi.service.http
- Declarative services - org.osgi.service.component
- osgi interfaces, provides all service interfaces for the OSGi specifications.
Instructions
The snippet gets the log service and then starts tracking the Http Services. Anytime when an Http Service is found, a message is send to the log.
A component can indicate that it depends on a service; this is called a reference in the specification. A reference can define methods to bind and unbind the referred services. The Bnd Service Component rewrite will automatically assume a set and unset method with the name of the reference. That is, http=org.osgi.service.log.LogService will bind to a setHttp and unsetHttp method. If you want more finer grained control, you can of course insert a Declarative Services XML file.
Source: aQute.tracker.TrackerComponent package aQute.trackercomponent; import org.osgi.framework.*; import org.osgi.service.log.*; import org.osgi.service.http.*; public class TrackerComponent { LogService log; int count; public void setLog(LogService log) { this.log= log; } public void setHttp(HttpService reference) { log.log( LogService.LOG_INFO, "Adding http to component, #" + count); count++; } public void unsetHttp(HttpService reference) { count--; log.log( LogService.LOG_INFO, "Removing http to component, #" + count); } }
We need to bind static 1..1 to the Log Service. To the Http Service we refer to with dynamic (we want to see the changes), and a cardinality of 0..n. Therefore, the Bnd file necessary to create the bundle is as follows:
Bnd: aQute.trackercomponent.bnd Private-Package: aQute.trackercomponent Service-Component: aQute.trackercomponent.TrackerComponent; \
log=org.osgi.service.log.LogService; \
http=org.osgi.service.http.HttpService; \
multiple:=http; \
optional:=http; \
dynamic:=http
Links
- The specification discusses services in chapter 701 of the OSGi Compendium.
- BundleContext Javadoc
- Service Tracker Javadoc
- Log Service Javadoc
- Http Service Javadoc
- aQute.trackercomponent.jar



