Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) OSGi Alliance (2000, 2012). All Rights Reserved.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.osgi.util.tracker;
 
The ServiceTracker class simplifies using services from the Framework's service registry.

A ServiceTracker object is constructed with search criteria and a ServiceTrackerCustomizer object. A ServiceTracker can use a ServiceTrackerCustomizer to customize the service objects to be tracked. The ServiceTracker can then be opened to begin tracking all services in the Framework's service registry that match the specified search criteria. The ServiceTracker correctly handles all of the details of listening to ServiceEvents and getting and ungetting services.

The getServiceReferences method can be called to get references to the services being tracked. The getService and getServices methods can be called to get the service objects for the tracked service.

The ServiceTracker class is thread-safe. It does not call a ServiceTrackerCustomizer while holding any locks. ServiceTrackerCustomizer implementations must also be thread-safe.

Parameters:
<S> The type of the service being tracked.
<T> The type of the tracked object.
Version:
$Id: 21926ad8717a91633face6bbf570febfcd23b1c7 $
ThreadSafe:
 
 public class ServiceTracker<S, T> implements ServiceTrackerCustomizer<S, T> {
 	/* set this to true to compile in debug messages */
 	static final boolean					DEBUGfalse;
The Bundle Context used by this ServiceTracker.
 
 	protected final BundleContext			context;
The Filter used by this ServiceTracker which specifies the search criteria for the services to track.

Since:
1.1
 
 	protected final Filter					filter;
The ServiceTrackerCustomizer for this tracker.
 
Filter string for use when adding the ServiceListener. If this field is set, then certain optimizations can be taken since we don't have a user supplied filter.
 
Class name to be tracked. If this field is set, then we are tracking by class name.
 
 	private final String					trackClass;
Reference to be tracked. If this field is set, then we are tracking a single ServiceReference.
 
 	private final ServiceReference<S>		trackReference;
Tracked services: ServiceReference -> customized Object and ServiceListener object
 
 	private volatile Tracked				tracked;

Accessor method for the current Tracked object. This method is only intended to be used by the unsynchronized methods which do not modify the tracked field.

Returns:
The current Tracked object.
	private Tracked tracked() {
		return ;
	}

Cached ServiceReference for getServiceReference. This field is volatile since it is accessed by multiple threads.
	private volatile ServiceReference<S>	cachedReference;
Cached service object for getService. This field is volatile since it is accessed by multiple threads.
	private volatile T						cachedService;

Create a ServiceTracker on the specified ServiceReference .

The service referenced by the specified ServiceReference will be tracked by this ServiceTracker.

Parameters:
context The BundleContext against which the tracking is done.
reference The ServiceReference for the service to be tracked.
customizer The customizer object to call when services are added, modified, or removed in this ServiceTracker. If customizer is null, then this ServiceTracker will be used as the ServiceTrackerCustomizer and this ServiceTracker will call the ServiceTrackerCustomizer methods on itself.
	public ServiceTracker(final BundleContext contextfinal ServiceReference<S> referencefinal ServiceTrackerCustomizer<S, T> customizer) {
		this. = context;
		this. = reference;
		this. = null;
		this. = (customizer == null) ? this : customizer;
		this. = "(" + . + "=" + reference.getProperty(.).toString() + ")";
		try {
catch (InvalidSyntaxException e) {
			/*
			 * we could only get this exception if the ServiceReference was
			 * invalid
			 */
			IllegalArgumentException iae = new IllegalArgumentException("unexpected InvalidSyntaxException: " + e.getMessage());
			iae.initCause(e);
			throw iae;
		}
	}

Create a ServiceTracker on the specified class name.

Services registered under the specified class name will be tracked by this ServiceTracker.

Parameters:
context The BundleContext against which the tracking is done.
clazz The class name of the services to be tracked.
customizer The customizer object to call when services are added, modified, or removed in this ServiceTracker. If customizer is null, then this ServiceTracker will be used as the ServiceTrackerCustomizer and this ServiceTracker will call the ServiceTrackerCustomizer methods on itself.
	public ServiceTracker(final BundleContext contextfinal String clazzfinal ServiceTrackerCustomizer<S, T> customizer) {
		this. = context;
		this. = null;
		this. = clazz;
		this. = (customizer == null) ? this : customizer;
		// we call clazz.toString to verify clazz is non-null!
		this. = "(" + . + "=" + clazz.toString() + ")";
		try {
catch (InvalidSyntaxException e) {
			/*
			 * we could only get this exception if the clazz argument was
			 * malformed
			 */
			IllegalArgumentException iae = new IllegalArgumentException("unexpected InvalidSyntaxException: " + e.getMessage());
			iae.initCause(e);
			throw iae;
		}
	}

Create a ServiceTracker on the specified Filter object.

Services which match the specified Filter object will be tracked by this ServiceTracker.

Parameters:
context The BundleContext against which the tracking is done.
filter The Filter to select the services to be tracked.
customizer The customizer object to call when services are added, modified, or removed in this ServiceTracker. If customizer is null, then this ServiceTracker will be used as the ServiceTrackerCustomizer and this ServiceTracker will call the ServiceTrackerCustomizer methods on itself.
Since:
1.1
	public ServiceTracker(final BundleContext contextfinal Filter filterfinal ServiceTrackerCustomizer<S, T> customizer) {
		this. = context;
		this. = null;
		this. = null;
		this. = filter.toString();
		this. = filter;
		this. = (customizer == null) ? this : customizer;
		if ((context == null) || (filter == null)) {
			/*
			 * we throw a NPE here to be consistent with the other constructors
			 */
			throw new NullPointerException();
		}
	}

Create a ServiceTracker on the specified class.

Services registered under the name of the specified class will be tracked by this ServiceTracker.

Parameters:
context The BundleContext against which the tracking is done.
clazz The class of the services to be tracked.
customizer The customizer object to call when services are added, modified, or removed in this ServiceTracker. If customizer is null, then this ServiceTracker will be used as the ServiceTrackerCustomizer and this ServiceTracker will call the ServiceTrackerCustomizer methods on itself.
Since:
1.5
	public ServiceTracker(final BundleContext contextfinal Class<S> clazzfinal ServiceTrackerCustomizer<S, T> customizer) {
		this(contextclazz.getName(), customizer);
	}

Open this ServiceTracker and begin tracking services.

This implementation calls open(false).

Throws:
java.lang.IllegalStateException If the BundleContext with which this ServiceTracker was created is no longer valid.
See also:
open(boolean)
	public void open() {
		open(false);
	}

Open this ServiceTracker and begin tracking services.

Services which match the search criteria specified when this ServiceTracker was created are now tracked by this ServiceTracker.

Parameters:
trackAllServices If true, then this ServiceTracker will track all matching services regardless of class loader accessibility. If false, then this ServiceTracker will only track matching services which are class loader accessible to the bundle whose BundleContext is used by this ServiceTracker.
Throws:
java.lang.IllegalStateException If the BundleContext with which this ServiceTracker was created is no longer valid.
Since:
1.3
	public void open(boolean trackAllServices) {
		final Tracked t;
		synchronized (this) {
			if ( != null) {
				return;
			}
			if () {
				..println("ServiceTracker.open: " + );
			}
			t = trackAllServices ? new AllTracked() : new Tracked();
			synchronized (t) {
				try {
					ServiceReference<S>[] references = null;
					if ( != null) {
						references = getInitialReferences(trackAllServicesnull);
else {
						if ( != null) {
							if (.getBundle() != null) {
								references = single;
							}
else { /* user supplied filter */
							references = getInitialReferences(trackAllServicesnull);
						}
					}
					/* set tracked with the initial references */
					t.setInitial(references);
catch (InvalidSyntaxException e) {
					throw new RuntimeException("unexpected InvalidSyntaxException: " + e.getMessage(), e);
				}
			}
			 = t;
		}
		/* Call tracked outside of synchronized region */
		t.trackInitial(); /* process the initial references */
	}

Returns the list of initial ServiceReferences that will be tracked by this ServiceTracker.

Parameters:
trackAllServices If true, use getAllServiceReferences.
className The class name with which the service was registered, or null for all services.
filterString The filter criteria or null for all services.
Returns:
The list of initial ServiceReferences.
Throws:
org.osgi.framework.InvalidSyntaxException If the specified filterString has an invalid syntax.
	private ServiceReference<S>[] getInitialReferences(boolean trackAllServicesString classNameString filterStringthrows InvalidSyntaxException {
		ServiceReference<S>[] result = (ServiceReference<S>[]) ((trackAllServices) ? .getAllServiceReferences(classNamefilterString) : .getServiceReferences(classNamefilterString));
		return result;
	}

Close this ServiceTracker.

This method should be called when this ServiceTracker should end the tracking of services.

This implementation calls getServiceReferences() to get the list of tracked services to remove.

	public void close() {
		final Tracked outgoing;
		final ServiceReference<S>[] references;
		synchronized (this) {
			outgoing = ;
			if (outgoing == null) {
				return;
			}
			if () {
				..println("ServiceTracker.close: " + );
			}
			outgoing.close();
			references = getServiceReferences();
			 = null;
			try {
catch (IllegalStateException e) {
				/* In case the context was stopped. */
			}
		}
		modified(); /* clear the cache */
		synchronized (outgoing) {
			outgoing.notifyAll(); /* wake up any waiters */
		}
		if (references != null) {
			for (int i = 0; i < references.lengthi++) {
				outgoing.untrack(references[i], null);
			}
		}
		if () {
			if (( == null) && ( == null)) {
				..println("ServiceTracker.close[cached cleared]: " + );
			}
		}
	}

Default implementation of the ServiceTrackerCustomizer.addingService method.

This method is only called when this ServiceTracker has been constructed with a null ServiceTrackerCustomizer argument.

This implementation returns the result of calling getService on the BundleContext with which this ServiceTracker was created passing the specified ServiceReference.

This method can be overridden in a subclass to customize the service object to be tracked for the service being added. In that case, take care not to rely on the default implementation of removedService to unget the service.

Parameters:
reference The reference to the service being added to this ServiceTracker.
Returns:
The service object to be tracked for the service added to this ServiceTracker.
See also:
ServiceTrackerCustomizer.addingService(org.osgi.framework.ServiceReference)
	public T addingService(ServiceReference<S> reference) {
result = (T) .getService(reference);
		return result;
	}

Default implementation of the ServiceTrackerCustomizer.modifiedService method.

This method is only called when this ServiceTracker has been constructed with a null ServiceTrackerCustomizer argument.

This implementation does nothing.

Parameters:
reference The reference to modified service.
service The service object for the modified service.
See also:
ServiceTrackerCustomizer.modifiedService(org.osgi.framework.ServiceReference,java.lang.Object)
	public void modifiedService(ServiceReference<S> reference, T service) {
		/* do nothing */
	}

Default implementation of the ServiceTrackerCustomizer.removedService method.

This method is only called when this ServiceTracker has been constructed with a null ServiceTrackerCustomizer argument.

This implementation calls ungetService, on the BundleContext with which this ServiceTracker was created, passing the specified ServiceReference.

This method can be overridden in a subclass. If the default implementation of addingService method was used, this method must unget the service.

Parameters:
reference The reference to removed service.
service The service object for the removed service.
See also:
ServiceTrackerCustomizer.removedService(org.osgi.framework.ServiceReference,java.lang.Object)
	public void removedService(ServiceReference<S> reference, T service) {
	}

Wait for at least one service to be tracked by this ServiceTracker. This method will also return when this ServiceTracker is closed.

It is strongly recommended that waitForService is not used during the calling of the BundleActivator methods. BundleActivator methods are expected to complete in a short period of time.

This implementation calls getService() to determine if a service is being tracked.

Parameters:
timeout The time interval in milliseconds to wait. If zero, the method will wait indefinitely.
Returns:
Returns the result of getService().
Throws:
java.lang.InterruptedException If another thread has interrupted the current thread.
java.lang.IllegalArgumentException If the value of timeout is negative.
	public T waitForService(long timeoutthrows InterruptedException {
		if (timeout < 0) {
			throw new IllegalArgumentException("timeout value is negative");
		}
object = getService();
		if (object != null) {
			return object;
		}
		final long endTime = (timeout == 0) ? 0 : (System.currentTimeMillis() + timeout);
		do {
			final Tracked t = tracked();
			if (t == null) { /* if ServiceTracker is not open */
				return null;
			}
			synchronized (t) {
				if (t.size() == 0) {
					t.wait(timeout);
				}
			}
			object = getService();
			if (endTime > 0) { // if we have a timeout
				timeout = endTime - System.currentTimeMillis();
				if (timeout <= 0) { // that has expired
					break;
				}
			}
while (object == null);
		return object;
	}

Return an array of ServiceReferences for all services being tracked by this ServiceTracker.

Returns:
Array of ServiceReferences or null if no services are being tracked.
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			return null;
		}
		synchronized (t) {
			int length = t.size();
			if (length == 0) {
				return null;
			}
			ServiceReference<S>[] result = new ServiceReference[length];
			return t.copyKeys(result);
		}
	}

Returns a ServiceReference for one of the services being tracked by this ServiceTracker.

If multiple services are being tracked, the service with the highest ranking (as specified in its service.ranking property) is returned. If there is a tie in ranking, the service with the lowest service ID (as specified in its service.id property); that is, the service that was registered first is returned. This is the same algorithm used by BundleContext.getServiceReference.

This implementation calls getServiceReferences() to get the list of references for the tracked services.

Returns:
A ServiceReference or null if no services are being tracked.
Since:
1.1
		if (reference != null) {
			if () {
				..println("ServiceTracker.getServiceReference[cached]: " + );
			}
			return reference;
		}
		if () {
			..println("ServiceTracker.getServiceReference: " + );
		}
		ServiceReference<S>[] references = getServiceReferences();
		int length = (references == null) ? 0 : references.length;
		if (length == 0) { /* if no service is being tracked */
			return null;
		}
		int index = 0;
		if (length > 1) { /* if more than one service, select highest ranking */
			int rankings[] = new int[length];
			int count = 0;
			int maxRanking = .;
			for (int i = 0; i < lengthi++) {
				Object property = references[i].getProperty(.);
				int ranking = (property instanceof Integer) ? ((Integerproperty).intValue() : 0;
				rankings[i] = ranking;
				if (ranking > maxRanking) {
					index = i;
					maxRanking = ranking;
					count = 1;
else {
					if (ranking == maxRanking) {
						count++;
					}
				}
			}
			if (count > 1) { /* if still more than one service, select lowest id */
				long minId = .;
				for (int i = 0; i < lengthi++) {
					if (rankings[i] == maxRanking) {
						long id = ((Long) (references[i].getProperty(.))).longValue();
						if (id < minId) {
							index = i;
							minId = id;
						}
					}
				}
			}
		}
		return  = references[index];
	}

Returns the service object for the specified ServiceReference if the specified referenced service is being tracked by this ServiceTracker.

Parameters:
reference The reference to the desired service.
Returns:
A service object or null if the service referenced by the specified ServiceReference is not being tracked.
	public T getService(ServiceReference<S> reference) {
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			return null;
		}
		synchronized (t) {
			return t.getCustomizedObject(reference);
		}
	}

Return an array of service objects for all services being tracked by this ServiceTracker.

This implementation calls getServiceReferences() to get the list of references for the tracked services and then calls getService(org.osgi.framework.ServiceReference) for each reference to get the tracked service object.

Returns:
An array of service objects or null if no services are being tracked.
	public Object[] getServices() {
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			return null;
		}
		synchronized (t) {
			ServiceReference<S>[] references = getServiceReferences();
			int length = (references == null) ? 0 : references.length;
			if (length == 0) {
				return null;
			}
			Object[] objects = new Object[length];
			for (int i = 0; i < lengthi++) {
				objects[i] = getService(references[i]);
			}
			return objects;
		}
	}

Returns a service object for one of the services being tracked by this ServiceTracker.

If any services are being tracked, this implementation returns the result of calling getService(getServiceReference()).

Returns:
A service object or null if no services are being tracked.
	public T getService() {
service = ;
		if (service != null) {
			if () {
				..println("ServiceTracker.getService[cached]: " + );
			}
			return service;
		}
		if () {
			..println("ServiceTracker.getService: " + );
		}
		if (reference == null) {
			return null;
		}
		return  = getService(reference);
	}

Remove a service from this ServiceTracker. The specified service will be removed from this ServiceTracker. If the specified service was being tracked then the ServiceTrackerCustomizer.removedService method will be called for that service.

Parameters:
reference The reference to the service to be removed.
	public void remove(ServiceReference<S> reference) {
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			return;
		}
		t.untrack(referencenull);
	}

Return the number of services being tracked by this ServiceTracker.

Returns:
The number of services being tracked.
	public int size() {
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			return 0;
		}
		synchronized (t) {
			return t.size();
		}
	}

Returns the tracking count for this ServiceTracker. The tracking count is initialized to 0 when this ServiceTracker is opened. Every time a service is added, modified or removed from this ServiceTracker, the tracking count is incremented.

The tracking count can be used to determine if this ServiceTracker has added, modified or removed a service by comparing a tracking count value previously collected with the current tracking count value. If the value has not changed, then no service has been added, modified or removed from this ServiceTracker since the previous tracking count was collected.

Returns:
The tracking count for this ServiceTracker or -1 if this ServiceTracker is not open.
Since:
1.2
	public int getTrackingCount() {
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			return -1;
		}
		synchronized (t) {
			return t.getTrackingCount();
		}
	}

Called by the Tracked object whenever the set of tracked services is modified. Clears the cache.
	/*
	 * This method must not be synchronized since it is called by Tracked while
	 * Tracked is synchronized. We don't want synchronization interactions
	 * between the listener thread and the user thread.
	 */
	void modified() {
		 = null/* clear cached value */
		 = null/* clear cached value */
		if () {
			..println("ServiceTracker.modified: " + );
		}
	}

Return a SortedMap of the ServiceReferences and service objects for all services being tracked by this ServiceTracker. The map is sorted in reverse natural order of ServiceReference. That is, the first entry is the service with the highest ranking and the lowest service id.

Returns:
A SortedMap with the ServiceReferences and service objects for all services being tracked by this ServiceTracker. If no services are being tracked, then the returned map is empty.
Since:
1.5
		SortedMap<ServiceReference<S>, T> map = new TreeMap<ServiceReference<S>, T>(Collections.reverseOrder());
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			return map;
		}
		synchronized (t) {
			return t.copyEntries(map);
		}
	}

Return if this ServiceTracker is empty.

Returns:
true if this ServiceTracker is not tracking any services.
Since:
1.5
	public boolean isEmpty() {
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			return true;
		}
		synchronized (t) {
			return t.isEmpty();
		}
	}

Return an array of service objects for all services being tracked by this ServiceTracker. The runtime type of the returned array is that of the specified array.

This implementation calls getServiceReferences() to get the list of references for the tracked services and then calls getService(org.osgi.framework.ServiceReference) for each reference to get the tracked service object.

Parameters:
array An array into which the tracked service objects will be stored, if the array is large enough.
Returns:
An array of service objects being tracked. If the specified array is large enough to hold the result, then the specified array is returned. If the specified array is longer then necessary to hold the result, the array element after the last service object is set to null. If the specified array is not large enough to hold the result, a new array is created and returned.
Since:
1.5
	public T[] getServices(T[] array) {
		final Tracked t = tracked();
		if (t == null) { /* if ServiceTracker is not open */
			if (array.length > 0) {
				array[0] = null;
			}
			return array;
		}
		synchronized (t) {
			ServiceReference<S>[] references = getServiceReferences();
			int length = (references == null) ? 0 : references.length;
			if (length == 0) {
				if (array.length > 0) {
					array[0] = null;
				}
				return array;
			}
			if (length > array.length) {
				array = (T[]) Array.newInstance(array.getClass().getComponentType(), length);
			}
			for (int i = 0; i < lengthi++) {
				array[i] = getService(references[i]);
			}
			if (array.length > length) {
				array[length] = null;
			}
			return array;
		}
	}

Inner class which subclasses AbstractTracked. This class is the ServiceListener object for the tracker.

ThreadSafe:
	private class Tracked extends AbstractTracked<ServiceReference<S>, T, ServiceEventimplements ServiceListener {
Tracked constructor.
			super();
		}

ServiceListener method for the ServiceTracker class. This method must NOT be synchronized to avoid deadlock potential.

Parameters:
event ServiceEvent object from the framework.
		final public void serviceChanged(final ServiceEvent event) {
			/*
			 * Check if we had a delayed call (which could happen when we
			 * close).
			 */
			if () {
				return;
			}
			final ServiceReference<S> reference = (ServiceReference<S>) event.getServiceReference();
			if () {
				..println("ServiceTracker.Tracked.serviceChanged[" + event.getType() + "]: " + reference);
			}
			switch (event.getType()) {
					track(referenceevent);
					/*
					 * If the customizer throws an unchecked exception, it is
					 * safe to let it propagate
					 */
					break;
					untrack(referenceevent);
					/*
					 * If the customizer throws an unchecked exception, it is
					 * safe to let it propagate
					 */
					break;
			}
		}

Increment the tracking count and tell the tracker there was a modification.

GuardedBy:
this
		final void modified() {
			super.modified(); /* increment the modification count */
		}

Call the specific customizer adding method. This method must not be called while synchronized on this object.

Parameters:
item Item to be tracked.
related Action related object.
Returns:
Customized object for the tracked item or null if the item is not to be tracked.
		final T customizerAdding(final ServiceReference<S> itemfinal ServiceEvent related) {
		}

Call the specific customizer modified method. This method must not be called while synchronized on this object.

Parameters:
item Tracked item.
related Action related object.
object Customized object for the tracked item.
		final void customizerModified(final ServiceReference<S> itemfinal ServiceEvent relatedfinal T object) {
		}

Call the specific customizer removed method. This method must not be called while synchronized on this object.

Parameters:
item Tracked item.
related Action related object.
object Customized object for the tracked item.
		final void customizerRemoved(final ServiceReference<S> itemfinal ServiceEvent relatedfinal T object) {
			.removedService(itemobject);
		}
	}

Subclass of Tracked which implements the AllServiceListener interface. This class is used by the ServiceTracker if open is called with true.

Since:
1.3
ThreadSafe:
	private class AllTracked extends Tracked implements AllServiceListener {
AllTracked constructor.
			super();
		}
	}
New to GrepCode? Check out our FAQ X