/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.util;
import org.osgi.framework.*;
import java.util.*;
/**
* Class keeps up to date list of services that implement given interface.
* Can be used as a replacement for expensive calls to
* getServiceReferences.
*
* @author Pawel Domas
*/
public class ServiceObserver
implements ServiceListener
{
/**
* Service instances list.
*/
private final List services;
/**
* Service class name.
*/
private final Class className;
/**
* The OSGi context.
*/
private BundleContext context;
/**
* Creates new instance of ServiceObserver that will observe
* services of given className.
*
* @param className class name of the service to observe.
*/
public ServiceObserver(Class className)
{
services = new ArrayList();
this.className = className;
}
/**
* This method must be called when OSGi i s starting to initialize the
* observer.
* @param ctx the OSGi bundle context.
*/
@SuppressWarnings("unchecked")
public void start(BundleContext ctx)
{
this.context = ctx;
ctx.addServiceListener(this);
ServiceReference[] refs
= ServiceUtils.getServiceReferences(ctx, className);
for(ServiceReference ref : refs)
services.add((T) ctx.getService(ref));
}
/**
* This method should be called on bundle shutdown to properly release
* the resources.
*
* @param ctx OSGi context
*/
public void stop(BundleContext ctx)
{
ctx.removeServiceListener(this);
services.clear();
this.context = null;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public void serviceChanged(ServiceEvent serviceEvent)
{
Object service
= context.getService(serviceEvent.getServiceReference());
if(!className.isInstance(service))
{
return;
}
int eventType = serviceEvent.getType();
if(eventType == ServiceEvent.REGISTERED)
{
services.add((T) service);
}
else if(eventType == ServiceEvent.UNREGISTERING)
{
services.remove(service);
}
}
/**
* Returns list of services compatible with service class observed by
* this instance.
* @return list of services compatible with service class observed by
* this instance.
*/
public List getServices()
{
return Collections.unmodifiableList(services);
}
}