Using the OSGi API, how do I find out if a given bundle is a fragment?
Asked Answered
A

3

5

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?

Anear answered 25/7, 2012 at 17:29 Comment(0)
P
9

Best way:

(bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0

Photocompose answered 25/7, 2012 at 21:47 Comment(2)
Yeah, that's much more explicit than my way. Thanks!Anear
Be 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.Flurry
A
4

One possible way: use Bundle.getHeaders() to look for the Fragment-Host header. If it is present, it's a fragment.

Anear answered 25/7, 2012 at 17:30 Comment(1)
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!Anear
T
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.

Trimetrogon answered 4/4, 2013 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.