In the OSGi API, a call to BundleContext.getBundles() returns all bundles, whether they are fragments or not. For a given Bundle object, what is the best way to tell if this is a fragment or not?
Asked
Active
Viewed 1,531 times
3 Answers
9
Best way:
(bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0

BJ Hargrave
- 9,324
- 1
- 19
- 27
-
1Yeah, that's much more explicit than my way. Thanks! – Dan Gravell Jul 26 '12 at 08:23
-
4Be aware that this is a new API in OSGi 4.3. Also be aware that adapt() can return null if you lose the race condition just as the bundle is being uninstalled. – Chris Dolan Jul 26 '12 at 14:37
4
One possible way: use Bundle.getHeaders() to look for the Fragment-Host header. If it is present, it's a fragment.

Dan Gravell
- 7,855
- 7
- 41
- 64
-
Answering my own question for now with the best way I know of... if this is wrong or there are better ways I will award the answer elsewhere! – Dan Gravell Jul 25 '12 at 17:31
1
According to the OSGi Core Specification Release 4, Version 4.2, there is also the PackageAdmin
service, which provides access to the structural information about bundles, e.g. determine whether a given bundle is a fragment or not.
import org.osgi.framework.Bundle;
import org.osgi.service.packageadmin.PackageAdmin;
PackageAdmin packageAdmin = ...; // I assume you know this
Bundle hostBundle = ...; // I assume you know this
Bundle fragmentBundle = ...; // I assume you know this
assertFalse(PackageAdmin.BUNDLE_TYPE_FRAGMENT, packageAdmin.getBundleType(hostBundle);
assertEquals(PackageAdmin.BUNDLE_TYPE_FRAGMENT, packageAdmin.getBundleType(fragmentBundle);
Apparently, in OSGi 4.3, the PackageAdmin
service seems to be deprecated and should be replaced by the org.osgi.framework.wiring
package.

Daniel Pacak
- 1,388
- 2
- 13
- 12