Search OSGI services by properties
java, osgi
Solution
Assuming that you want to retrieve registered services based on certain values for properties, you need to use a filter (which is based on the LDAP syntax).
For example:
int myport = 5000;
String filter = "&(objectClass=" + MyInterface.class.getName()
+ ")(port=" + myport + ")";
ServiceReference[] serviceReferences = bundleContext.getServiceReferences(null,filter);
where you want to look for services both implementing `MyInterface` and having a value of the `port` property equal to `myport`.
Here is the relevant javadoc for getting the references.
Remark 1:
The above example and javadoc refer to the Release 4.2. If you are not restricted to a J2SE 1.4 runtime, I suggest you to have a look at the Release 4.3 syntax, where you can use generics.
Remark 2: (courtesy of Ray)
You can also pre-check the correctness of your filter by instead creating a Filter object from a `filterStr` string:
Filter filter = bundleContext.createFilter(filterStr);
which also allows you to match the filter with other criteria. You still pass `filterStr` to get the references, since there is no overloading that accounts for a `Filter` argument. Please be aware, however, that in this way you will check the correctness twice: both `getServiceReferences` and `createFilter` throw `InvalidSyntaxException` on parsing the filter. Certainly not a show-stopper inefficiency, I guess, but it is worth mentioning.
Problem
How can I distinguish between published OSGI services implementing same interface by their properties?