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?
An OSGi fragment is a Java™ archive file with specific manifest headers that enable it to attach to a specified host bundle or specified host bundles to function. Fragments are treated as part of the host bundles.
The Bundle-ClassPath header defines a comma-separated list of JAR file path names or directories (inside the bundle) containing classes and resources. The full stop ( '. ' \u002E ) specifies the root directory of the bundle's JAR. The full stop is also the default.
In OSGi, a single component is called a bundle. Logically, a bundle is a piece of functionality that has an independent lifecycle – which means it can be started, stopped and removed independently. Technically, a bundle is just a jar file with a MANIFEST. MF file containing some OSGi-specific headers.
Best way:
(bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0
One possible way: use Bundle.getHeaders() to look for the Fragment-Host header. If it is present, it's a fragment.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With