下面列出了org.osgi.framework.hooks.bundle.EventHook#org.osgi.framework.wiring.BundleCapability 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static Bundle[] getBundles(String symbolicName, FrameworkWiring fwkWiring) {
BundleContext context = fwkWiring.getBundle().getBundleContext();
if (Constants.SYSTEM_BUNDLE_SYMBOLICNAME.equals(symbolicName)) {
symbolicName = context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).getSymbolicName();
}
StringBuilder filter = new StringBuilder();
filter.append('(')
.append(IdentityNamespace.IDENTITY_NAMESPACE)
.append('=')
.append(symbolicName)
.append(')');
Map<String, String> directives = Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString());
Collection<BundleCapability> matchingBundleCapabilities = fwkWiring.findProviders(ModuleContainer.createRequirement(IdentityNamespace.IDENTITY_NAMESPACE, directives, Collections.emptyMap()));
if (matchingBundleCapabilities.isEmpty()) {
return null;
}
Bundle[] results = matchingBundleCapabilities.stream().map(c -> c.getRevision().getBundle())
// Remove all the bundles that are uninstalled
.filter(bundle -> (bundle.getState() & (Bundle.UNINSTALLED)) == 0)
.sorted((b1, b2) -> b2.getVersion().compareTo(b1.getVersion())) // highest version first
.toArray(Bundle[]::new);
return results.length > 0 ? results : null;
}
private void getExportedPackages0(final Bundle bundle, final String name, final ArrayList<ExportedPackage> result) {
if (bundle == null) {
throw new IllegalArgumentException("bundle==null");
}
if (result == null) {
throw new IllegalArgumentException("result==null");
}
final List<BundleRevision> revs = bundle.adapt(BundleRevisions.class).getRevisions();
if (revs.isEmpty()) {
return;
}
for (final BundleRevision r : revs) {
final BundleWiring wiring = r.getWiring();
if (wiring != null && wiring.isInUse()) {
for (final Capability cap : wiring.getCapabilities(PackageNamespace.PACKAGE_NAMESPACE)) {
if (name == null || name.equals(cap.getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE))) {
result.add(new ExportedPackageImpl((BundleCapability) cap));
}
}
}
}
}
private MultiMap<String, BundleCapability> parseCapabilities(
final String str) throws BundleException {
final MultiMap<String, BundleCapability> result = new MultiMap<String, BundleCapability>();
if (str == null) {
return result;
}
final String[] reqStrs = Utils.splitString(str, ',');
for (int i = 0; i < reqStrs.length; i++) {
final BundleCapabilityImpl cap = new BundleCapabilityImpl(this,
reqStrs[i]);
final String namespace = cap.getNamespace();
if(namespace.equals(NativeNamespace.NATIVE_NAMESPACE)){
throw new BundleException("Only the system bundle can provide a native capability", BundleException.MANIFEST_ERROR);
}
result.insert(namespace, cap);
}
return result;
}
/**
* Test if startup of framework does work when java.specification.name is
* NOT null. This is the standard case for JavaSE 7/8 etc JVMs.
*/
@Test
public void testJavaSpecificationNameNotNull() throws Exception {
String propName = "java.specification.name";
String propValue = System.getProperty(propName);
Assert.assertNotNull(propValue);
try {
startFramework();
Assert.assertEquals(0, framework.getBundleId());
BundleWiring w = framework.adapt(BundleWiring.class);
List<BundleCapability> caps = w.getCapabilities("osgi.ee");
checkEECaps(caps);
} finally {
stopFramework();
}
}
/**
* Test if startup of framework does work when java.specification.name IS
* null. This will for example happen when running on CEE-J.
*/
@Test
public void testJavaSpecificationNameNull() throws Exception {
String propName = "java.specification.name";
String savedPropValue = System.getProperty(propName);
try {
System.clearProperty(propName);
String propValue = System.getProperty(propName);
Assert.assertNull(propValue);
startFramework();
Assert.assertEquals(0, framework.getBundleId());
BundleWiring w = framework.adapt(BundleWiring.class);
List<BundleCapability> caps = w.getCapabilities("osgi.ee");
checkEECaps(caps);
} finally {
stopFramework();
System.setProperty(propName, savedPropValue);
}
}
private void checkEECaps(List<BundleCapability> caps) throws Exception {
String propVersion = "java.specification.version";
String propVersionValue = System.getProperty(propVersion);
String propName = "java.specification.name";
String propNameValue = System.getProperty(propName);
// now check if we see the expected capabilities for "osgi.ee"
// this test does only work on for JavaSE 7/8 Full-JRE yet
// for other JVM to run test on we have to add expected values
if ("1.8".equals(propVersionValue)) {
checkEECapsForJava8(caps);
} else if ("1.7".equals(propVersionValue)) {
checkEECapsForJava7(caps);
} else {
Assert.fail("Test not yet supported on JavaVM " + propNameValue
+ " " + propVersionValue);
}
}
BundleRevisionDTO getDTO() {
BundleRevisionDTO res = new BundleRevisionDTO();
res.symbolicName = gen.symbolicName;
res.type = getTypes();
res.version = gen.version.toString();
res.bundle = gen.bundle.id;
res.id = dtoId;
res.capabilities = new ArrayList<CapabilityDTO>();
for (BundleCapability bc : getDeclaredCapabilities(null)) {
res.capabilities.add(BundleCapabilityImpl.getDTO(bc, this));
}
res.requirements = new ArrayList<RequirementDTO>();
for (BundleRequirement br : getDeclaredRequirements(null)) {
res.requirements.add(BundleRequirementImpl.getDTO(br, this));
}
return res;
}
void filterMatches(BundleRequirement requirement , Collection<? extends BundleCapability> candidates) throws BundleException {
if (hasHooks()) {
@SuppressWarnings("unchecked")
Collection<BundleCapability> c = new RemoveOnlyCollection<BundleCapability>((Collection<BundleCapability>) candidates);
blockResolveForHooks();
try {
for (TrackedResolverHookFactory rhf : active) {
final ResolverHook rh = checkActiveRemoved(rhf);
try {
rh.filterMatches(requirement, c);
} catch (RuntimeException re) {
throw new BundleException("Resolver hook throw an exception, bid="
+ rhf.bundle.getBundleId(),
BundleException.REJECTED_BY_HOOK, re);
}
}
} finally {
unblockResolveForHooks();
}
}
}
void filterSingletonCollisions(BundleCapability singleton , Collection<BundleCapability> candidates) throws BundleException {
if (hasHooks()) {
Collection<BundleCapability> c = new RemoveOnlyCollection<BundleCapability>(candidates);
blockResolveForHooks();
try {
for (TrackedResolverHookFactory rhf : active) {
final ResolverHook rh = checkActiveRemoved(rhf);
try {
rh.filterSingletonCollisions(singleton, c);
} catch (RuntimeException re) {
throw new BundleException("Resolver hook throw an exception, bid="
+ rhf.bundle.getBundleId(),
BundleException.REJECTED_BY_HOOK, re);
}
}
} finally {
unblockResolveForHooks();
}
}
}
public List<BundleCapability> getDeclaredCapabilities(String namespace)
{
List<BundleCapability> result = m_declaredCaps;
if (namespace != null)
{
result = new ArrayList<BundleCapability>();
for (BundleCapability cap : m_declaredCaps)
{
if (cap.getNamespace().equals(namespace))
{
result.add(cap);
}
}
}
return result;
}
public List<BundleCapability> getDeclaredCapabilities(String namespace)
{
List<BundleCapability> result = m_declaredCaps;
if (namespace != null)
{
result = new ArrayList<BundleCapability>();
for (BundleCapability cap : m_declaredCaps)
{
if (cap.getNamespace().equals(namespace))
{
result.add(cap);
}
}
}
return result;
}
/**
* Return the BundleCapability of a bundle exporting the package packageName.
*
* @param context The BundleContext
* @param packageName The package name
* @return the BundleCapability of a bundle exporting the package packageName
*/
private static BundleCapability getExportedPackage(BundleContext context, String packageName) {
List<BundleCapability> packages = new ArrayList<BundleCapability>();
for (Bundle bundle : context.getBundles()) {
BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);
for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {
String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);
if (pName.equalsIgnoreCase(packageName)) {
packages.add(packageCapability);
}
}
}
Version max = Version.emptyVersion;
BundleCapability maxVersion = null;
for (BundleCapability aPackage : packages) {
Version version = (Version) aPackage.getAttributes().get("version");
if (max.compareTo(version) <= 0) {
max = version;
maxVersion = aPackage;
}
}
return maxVersion;
}
public List<BundleCapability> getCapabilities(final String namespace) {
if (!isInUse()) {
return null;
}
return namespace == null ? capabilities.getAllValues()
: capabilities.lookup(namespace);
}
private HashSet<String> createExportIndex() {
final List<BundleCapability> packageReqs = capabilities
.get(PackageNamespace.PACKAGE_NAMESPACE);
final HashSet<String> index = new HashSet<String>();
if (packageReqs != null) {
for (final BundleCapability req : packageReqs) {
index.add((String) req.getAttributes()
.get(PackageNamespace.PACKAGE_NAMESPACE));
}
}
return index;
}
public int compare(final Capability c1, final Capability c2) {
if (!(c1 instanceof BundleCapability
&& c2 instanceof BundleCapability)) {
return 0;
}
final BundleCapability cap1 = (BundleCapability) c1;
final BundleCapability cap2 = (BundleCapability) c2;
final int cap1Resolved = cap1.getResource().getWiring() == null ? 0
: 1;
final int cap2Resolved = cap2.getResource().getWiring() == null ? 0
: 1;
int score = cap2Resolved - cap1Resolved;
if (score != 0) {
return score;
}
final Version cap1Version = (Version) cap1.getAttributes()
.get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE);
final Version cap2Version = (Version) cap2.getAttributes()
.get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE);
score = cap2Version.compareTo(cap1Version);
if (score != 0) {
return score;
}
final long cap1BundleId = cap1.getRevision().getBundle()
.getBundleId();
final long cap2BundleId = cap2.getRevision().getBundle()
.getBundleId();
return (int) (cap1BundleId - cap2BundleId);
}
/**
* @see org.osgi.framework.wiring.BundleRevision#getDeclaredCapabilities(java.lang.String)
* @category BundleRevision
*/
public List<BundleCapability> getDeclaredCapabilities(
final String namespace) {
final ArrayList<BundleCapability> filteredCapabilities = new ArrayList<BundleCapability>();
if (namespace != null) {
for (final BundleCapability c : systemBundleCapabilities) {
if (c.getNamespace().equals(namespace)) {
filteredCapabilities.add(c);
}
}
} else {
filteredCapabilities.addAll(systemBundleCapabilities);
}
return Collections.unmodifiableList(filteredCapabilities);
}
/**
* @see org.osgi.framework.wiring.FrameworkWiring#findProviders(Requirement requirement)
*/
public Collection<BundleCapability> findProviders(Requirement requirement) {
final List<Capability> providers = resolver.findProviders(requirement);
final List<BundleCapability> result = new ArrayList<BundleCapability>(providers.size());
for(int i=0;i<providers.size();i++){
Capability cap = providers.get(i);
if(cap instanceof BundleCapability){
result.add((BundleCapability) cap);
}
}
return result;
}
/**
* Test if startup of framework does work when java.specification.name is
* "J2ME Foundation Specification". This will run into a case where only
* CDC-Profiles does exist in JVM.
*/
@Test
public void testJavaSpecificationNameJ2ME() throws Exception {
String propName = "java.specification.name";
String savedPropNameValue = System.getProperty(propName);
String propVersion = "java.specification.version";
String savedPropVersionValue = System.getProperty(propVersion);
try {
// fixed value, see https://jcp.org/en/jsr/detail?id=36
String j2mePropValue = "J2ME Foundation Specification";
System.setProperty(propName, j2mePropValue);
String propValue = System.getProperty(propName);
Assert.assertEquals(j2mePropValue, propValue);
// we have to fake the spec version too, use here 1.1
System.setProperty(propVersion, "1.1");
startFramework();
Assert.assertEquals(0, framework.getBundleId());
BundleWiring w = framework.adapt(BundleWiring.class);
List<BundleCapability> caps = w.getCapabilities("osgi.ee");
// in case of J2ME, there is only CDC-profiles, no OSGi EE
// capabilities
// TODO Jan is that correct?
Assert.assertEquals(0, caps.size());
} finally {
stopFramework();
System.setProperty(propName, savedPropNameValue);
System.setProperty(propVersion, savedPropVersionValue);
}
}
private void checkEECapsForJava8(List<BundleCapability> caps)
throws Exception {
// we expect for "JavaSE 8" 5 capabilities:
// JavaSE,JavaSE/compact1,JavaSE/compact3,JavaSE/compact3,
// OSGi/Minimum
Assert.assertEquals(5, caps.size());
Iterator<BundleCapability> iter = caps.iterator();
while (iter.hasNext()) {
BundleCapability cap = iter.next();
// get the details for a capability
String ee = (String) cap.getAttributes().get("osgi.ee");
@SuppressWarnings("unchecked")
List<String> version = (List<String>) cap.getAttributes()
.get("version");
if (ee.equals("JavaSE")) {
// version=[1.8.0, 1.7.0, 1.6.0, 1.5.0, 1.4.0, 1.3.0,
// 1.2.0, 1.1.0]
Assert.assertEquals(8, version.size());
} else if (ee.equals("JavaSE/compact1")) {
// version=[1.8.0]
Assert.assertEquals(1, version.size());
} else if (ee.equals("JavaSE/compact2")) {
// version=[1.8.0]
Assert.assertEquals(1, version.size());
} else if (ee.equals("JavaSE/compact3")) {
// version=[1.8.0]
Assert.assertEquals(1, version.size());
} else if (ee.equals("OSGi/Minimum")) {
// version=[1.2.0, 1.1.0, 1.0.0]
Assert.assertEquals(3, version.size());
} else {
Assert.fail("Unknown capability namespace " + ee + " found");
}
}
}
private void checkEECapsForJava7(List<BundleCapability> caps)
throws Exception {
// we expect for "JavaSE 7" 2 capabilities:
// JavaSE, OSGi/Minimum
Assert.assertEquals(2, caps.size());
Iterator<BundleCapability> iter = caps.iterator();
while (iter.hasNext()) {
BundleCapability cap = iter.next();
// get the details for a capability
String ee = (String) cap.getAttributes().get("osgi.ee");
@SuppressWarnings("unchecked")
List<String> version = (List<String>) cap.getAttributes()
.get("version");
if (ee.equals("JavaSE")) {
// version=[1.7.0, 1.6.0, 1.5.0, 1.4.0, 1.3.0,
// 1.2.0, 1.1.0]
Assert.assertEquals(7, version.size());
} else if (ee.equals("OSGi/Minimum")) {
// version=[1.2.0, 1.1.0, 1.0.0]
Assert.assertEquals(3, version.size());
} else {
Assert.fail("Unknown capability namespace " + ee + " found");
}
}
}
/**
* Get a HTML-formated presentation string for the capability described by
* the given {@code capability}.
* @param capability capability to be named.
* @return
*/
String getCapName(final BundleCapability capability)
{
final StringBuffer sb = new StringBuffer(50);
sb.append(capability.getAttributes());
final BundleWiring capWiring = capability.getRevision().getWiring();
appendPendingRemovalOnRefresh(sb, capWiring);
return sb.toString();
}
@Override
String getCapName(final BundleCapability capability)
{
// Make a modifiable clone of the attributes.
final Map<String, Object> attrs
= new HashMap<String, Object>(capability.getAttributes());
final StringBuffer sb = new StringBuffer(50);
sb.append(attrs.remove(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE));
@SuppressWarnings("unchecked")
final List<Version> versions = (List<Version>) attrs
.remove(Constants.VERSION_ATTRIBUTE);
if (versions!=null) {
sb.append(" ");
sb.append(versions);
}
if (!attrs.isEmpty()) {
sb.append(" ");
sb.append(attrs);
}
final BundleWiring capWiring = capability.getRevision().getWiring();
appendPendingRemovalOnRefresh(sb, capWiring);
return sb.toString();
}
@Override
String getCapName(final BundleCapability capability)
{
// Make a modifiable clone of the attributes.
final Map<String, Object> attrs
= new HashMap<String, Object>(capability.getAttributes());
final StringBuffer sb = new StringBuffer(50);
sb.append(attrs.remove(BundleRevision.HOST_NAMESPACE));
final Version version =
(Version) attrs.remove(Constants.BUNDLE_VERSION_ATTRIBUTE);
if (version != null) {
sb.append(" ");
sb.append(version);
}
if (!attrs.isEmpty()) {
sb.append(" ");
sb.append(attrs);
}
final BundleWiring capWiring = capability.getRevision().getWiring();
appendPendingRemovalOnRefresh(sb, capWiring);
return sb.toString();
}
@Override
String getCapName(final BundleCapability capability)
{
// Make a modifiable clone of the attributes.
final Map<String, Object> attrs =
new HashMap<String, Object>(capability.getAttributes());
final StringBuffer sb = new StringBuffer(50);
sb.append(attrs.remove(BundleRevision.BUNDLE_NAMESPACE));
final Version version =
(Version) attrs.remove(Constants.BUNDLE_VERSION_ATTRIBUTE);
if (version != null) {
sb.append(" ");
sb.append(version);
}
if (!attrs.isEmpty()) {
sb.append(" ");
sb.append(attrs);
}
final BundleWiring capWiring = capability.getRevision().getWiring();
appendPendingRemovalOnRefresh(sb, capWiring);
return sb.toString();
}
@Override
String getCapName(final BundleCapability capability)
{
final StringBuffer sb = new StringBuffer(50);
// Make a modifiable clone of the capability attributes.
final Map<String, Object> attrs
= new HashMap<String, Object>(capability.getAttributes());
sb.append(attrs.remove(BundleRevision.PACKAGE_NAMESPACE));
final Version version = (Version) attrs
.remove(Constants.VERSION_ATTRIBUTE);
if (version!=null) {
sb.append(" ");
sb.append(version);
}
attrs.remove(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE);
attrs.remove(Constants.BUNDLE_VERSION_ATTRIBUTE);
if (!attrs.isEmpty()) {
sb.append(" ");
sb.append(attrs);
}
final BundleWiring capWiring = capability.getRevision().getWiring();
appendPendingRemovalOnRefresh(sb, capWiring);
return sb.toString();
}
List<CapabilityRefDTO> getCapabilityRefDTOs() {
List<CapabilityRefDTO> res = new ArrayList<CapabilityRefDTO>();
for (BundleCapability bc : getDeclaredCapabilities(null)) {
res.add(BundleCapabilityImpl.getRefDTO(bc, this));
}
return res;
}
@Override
public boolean matches(BundleCapability capability) {
if (namespace.equals(capability.getNamespace())) {
return null==filter ? true : filter.matches(capability.getAttributes());
}
return false;
}
@Override
public boolean matches(BundleCapability capability) {
if (BundleRevision.PACKAGE_NAMESPACE.equals(capability.getNamespace())) {
for (NativeCodeEntry e : entries) {
if (e.filter == null || e.filter.matches(capability.getAttributes())) {
return true;
}
}
}
return false;
}
@Override
public boolean matches(BundleCapability capability) {
if (BundleRevision.PACKAGE_NAMESPACE.equals(capability.getNamespace())) {
return toFilter().matches(capability.getAttributes());
}
return false;
}
BundleWireImpl(BundleCapability capability, BundleGeneration provider,
BundleRequirement requirement, BundleGeneration requirer) {
this.capability = capability;
this.providerGen = provider;
this.requirement = requirement;
this.requirerGen = requirer;
}