Java Reference
In-Depth Information
Other tracker methods get all active instances and access the underlying service refer-
ences; there's even a method that helps you wait until a service appears. Often, a raw
service tracker is all you need, but sometimes you'll want to extend it. Perhaps you
want to decorate a service with additional behavior, or you need to acquire or release
resources as services appear and disappear. You could extend the ServiceTracker
class, but you'd have to be careful not to break the behavior of any methods you over-
ride. Thankfully, there's a way to extend a service tracker without subclassing it: with a
customizer object. The ServiceTrackerCustomizer interface shown here provides a
safe way to enhance a tracker by intercepting tracked service instances:
public interface ServiceTrackerCustomizer {
public Object addingService(ServiceReference reference);
public void modifiedService(ServiceReference reference,
Object service);
public void removedService(ServiceReference reference,
Object service);
}
Like a service listener, a customizer is based on the three major events in the life of a
service: adding, modifying, and removing. The addingService() method is where
most of the customization normally occurs. The associated tracker calls this whenever
a matching service is added to the OSG i service registry. You're free to do whatever you
want with the incoming service; you can initialize some resources or wrap it in another
object, for example. The object you return is tied to the service by the tracker and
returned wherever the tracker would normally return the service instance. If you
decide you don't want to track a particular service instance, return null . The other
two methods in the customizer are typically used for housekeeping tasks like updating
or releasing resources.
Suppose you want to decorate the Log Service, such as adding some text around
the log messages. The service tracker customizer may look something like the follow-
ing listing.
Listing 4.14 Customized tracker example—decorated Log Service
class LogServiceDecorator implements ServiceTrackerCustomizer {
private final BundleContext m_context;
public LogServiceDecorator(BundleContext context) {
m_context = context;
}
public Object addingService(final ServiceReference ref) {
return new LogService() {
public void log(int level, String message) {
((LogService) m_context.getService(ref)).log(level,
"<<" + message + ">>");
}
Wraps code
around original
Log Service
public void log(int level, String message,
Throwable exception) {}
 
Search WWH ::




Custom Search