Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search OSGI services by properties

Tags:

java

osgi

How can I distinguish between published OSGI services implementing same interface by their properties?

like image 876
John Smith Avatar asked Jun 22 '12 06:06

John Smith


People also ask

What are OSGi services?

The OSGi Service Platform provides a mechanism for developing applications by using a component model and deploying those applications into an OSGi framework. The OSGi architecture is separated into a number of layers that provide benefits to creating and managing Java™ applications.

What is service registry in OSGi?

The OSGi service registry enables a bundle to publish objects to a shared registry, advertised via a given set of Java interfaces. Published services also have service properties associated with them in the registry.

What is the default ranking of an OSGi service?

The default ranking is 0. A service with a ranking of Integer. MAX_VALUE is very likely to be returned as the default service, whereas a service with a ranking of Integer.


1 Answers

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.

like image 109
Luca Geretti Avatar answered Oct 30 '22 11:10

Luca Geretti