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?

Dan Gravell
  • 7,855
  • 7
  • 41
  • 64

3 Answers3

9

Best way:

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

BJ Hargrave
  • 9,324
  • 1
  • 19
  • 27
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