Created
May 8, 2012 18:17
-
-
Save njbartlett/2638180 to your computer and use it in GitHub Desktop.
Building an index for OSGi service properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IndexingTracker extends ServiceTracker { | |
private final ConcurrentMap<Object, ServiceReference> index = new ConcurrentHashMap<Object, ServiceReference>(); | |
private final String keyProperty; | |
public IndexingTracker(BundleContext context, String serviceClass, String keyProperty) { | |
super(context, serviceClass, null); | |
this.keyProperty = keyProperty; | |
} | |
@Override | |
public Object addingService(ServiceReference reference) { | |
Object id = reference.getProperty(keyProperty); | |
ServiceReference existing = index.putIfAbsent(id, reference); | |
if (existing != null) { | |
// TODO: what should happen if multiple services have the same key? | |
} | |
return id; | |
} | |
@Override | |
public void removedService(ServiceReference reference, Object id) { | |
index.remove(id); | |
} | |
public ServiceReference findByKey(Object key) { | |
return index.get(key); | |
} | |
} | |
// Example use: | |
IndexingTracker indexer = new IndexingTracker(context, MyService.class.getName(), "ID"); | |
indexer.open(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment