Should I create myself a method that gets an array of all bundles from BundleContext.getBundles(). Then traverse such array adapting each bundle for BundleRevision and then trying to match against the capabilities returned by its getDeclaredCapabilities() method ? or there are other simple ways?
Almost. You should:
- Get the available bundles from bundleContext
- adapt the bundles to BundleWirings
- get the capabilities from BundleWirings
e.g.:
Bundle[] bundles = context.getBundles();
foreach(Bundle : bundles) {
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
List<BundleCapability> capabilities = bundleWiring.getCapabilities(null);
myCapabilityBasedLogic(capabilities);
}
For more information, see the documentation of BundleWiring class.
Update
In case a Bundle is in installed state, it has no BundleWiring. I wrote a code snippet to get the capabilities of the installed bundles before: https://github.com/everit-org/osgi-lqmg/blob/master/src/main/java/org/everit/osgi/dev/lqmg/internal/EquinoxHackUtilImpl.java.
See the function getAllCapabilities(bundles, state).
The relevant code snippet:
PlatformAdmin platformAdmin = systemBundleContext.getService(platformServiceSR);
State state = platformAdmin.getState();
Bundle[] bundles = systemBundleContext.getBundles();
List<BundleCapability> availableCapabilities = new ArrayList<BundleCapability>();
for (Bundle bundle : bundles) {
BundleDescription bundleDescription = state.getBundle(bundle.getBundleId());
List<BundleCapability> declaredCapabilities = bundleDescription.getDeclaredCapabilities(null);
availableCapabilities.addAll(declaredCapabilities);
}
return availableCapabilities;
I guess there is a similar possibility in Felix. If you find out how it works, please share it with me and I will create a HackUtil implementation for Felix, too ;).
If you want an universal handmade solution, you can parse the Provide-Capability and Export-Package headers of the installed Bundle. You can parse a header with felix-utils. This library is embedded into many technologies, butI also re-packaged it and uploaded it to maven-central as an OSGi bundle. You code can look similar to the following:
Dictionary<String, String> headers = installedBundle.getHeaders();
String header = headers.get("Provide-Capability");
if (header != null) {
// Parse with felix-utils
Clause[] clauses = Parse.parseHeader(header);
for(Clause clause : clauses) {
String nameSpace = clause.getName();
Attribute[] attributes = clause.getAttributes();
Directive[] directives = clause.getDirectives();
processCapability(nameSpace, attributes, directives);
}
}
You must implement processCapability as you want. You can also parse the Export-Package headers and convert them to capabilities based on the OSGi spec.