Java源码示例:org.osgi.framework.wiring.FrameworkWiring

示例1
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;
}
 
示例2
private static void refreshBundles(Set<Bundle> toRefresh, FrameworkWiring frameworkWiring) {
	if (!toRefresh.isEmpty()) {
		JavaLanguageServerPlugin.logInfo("Refresh the bundles");
		final CountDownLatch latch = new CountDownLatch(1);
		frameworkWiring.refreshBundles(toRefresh, new FrameworkListener() {
			@Override
			public void frameworkEvent(FrameworkEvent event) {
				if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
					latch.countDown();
				} else if (event.getType() == FrameworkEvent.ERROR) {
					JavaLanguageServerPlugin.logException("Error happens when refreshing the bundles", event.getThrowable());
					latch.countDown();
				}
			}
		});
		try {
			latch.await();
		} catch (InterruptedException e) {
			JavaLanguageServerPlugin.logException("InterruptedException happened when refreshing", e);
		}
		JavaLanguageServerPlugin.logInfo("Finished Refreshing bundles");
	}
}
 
示例3
/**
 * NOTE: This method is no longer used by the Jdisc container framework, but kept for completeness.
 */
@Override
public void refreshPackages() {
    FrameworkWiring wiring = felix.adapt(FrameworkWiring.class);
    final CountDownLatch latch = new CountDownLatch(1);
    wiring.refreshBundles(null,
                          event -> {
                              switch (event.getType()) {
                                  case FrameworkEvent.PACKAGES_REFRESHED:
                                      latch.countDown();
                                      break;
                                  case FrameworkEvent.ERROR:
                                      log.log(Level.SEVERE, "ERROR FrameworkEvent received.", event.getThrowable());
                                      break;
                              }
                          });
    try {
        long TIMEOUT_SECONDS = 60L;
        if (!latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
            log.warning("No PACKAGES_REFRESHED FrameworkEvent received within " + TIMEOUT_SECONDS +
                                " seconds of calling FrameworkWiring.refreshBundles()");
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
 
示例4
public int cmdRefresh(Dictionary<String,?> opts, Reader in, PrintWriter out,
                      Session session) {
  final Bundle systemBundle = bc.getBundle(0);
  final FrameworkWiring frameworkWiring =
    systemBundle.adapt(FrameworkWiring.class);

  final List<Bundle> bundles = new ArrayList<Bundle>();
  final String[] bs = (String[]) opts.get("bundle");
  if (bs != null) {
    final Bundle[] b = getBundles(bs, true);
    for (final Bundle element : b) {
      if (element != null) {
        bundles.add(element);
      }
    }
    if (bundles.isEmpty()) {
      out.println("ERROR! No matching bundle");
      return 1;
    }
    frameworkWiring.refreshBundles(bundles);
  } else {
    frameworkWiring.refreshBundles(null);
  }
  return 0;
}
 
示例5
public int cmdResolve(Dictionary<String,?> opts, Reader in, PrintWriter out,
                      Session session) {
  final Bundle systemBundle = bc.getBundle(0);
  final FrameworkWiring frameworkWiring =
    systemBundle.adapt(FrameworkWiring.class);

  final List<Bundle> bundles = new ArrayList<Bundle>();
  final String[] bs = (String[]) opts.get("bundle");
  Bundle[] b = null;
  if (bs != null) {
    b = getBundles(bs, true);
    for (final Bundle element : b) {
      if (element != null) {
        bundles.add(element);
      }
    }
    if (b.length == 0) {
      out.println("ERROR! No matching bundle");
      return 1;
    }
    frameworkWiring.resolveBundles(bundles);
  } else {
    frameworkWiring.resolveBundles(null);
  }
  return 0;
}
 
示例6
public void runTest() throws Throwable {
  buB = Util.installBundle(bc, "bundleB_test-1.0.0.jar");
  assertNotNull(buB);
  FrameworkWiring fw = bc.getBundle(0).adapt(FrameworkWiring.class);
  assertNotNull(fw);
  fw.resolveBundles(Collections.singleton(buB));
  BundleWiring wiring = buB.adapt(BundleWiring.class);
  assertNotNull(wiring);
  Collection resources = wiring.listResources("/", "*.class", 0);
  assertEquals("Class files in top of bundleB_test", 0, resources.size());
  resources = wiring.listResources("/org/knopflerfish/bundle", "*.class",
      BundleWiring.FINDENTRIES_RECURSE);
  assertEquals("Class files in bundleB_test", 2, resources.size());
  resources = wiring.listResources("/", "*.class",
      BundleWiring.FINDENTRIES_RECURSE + BundleWiring.LISTRESOURCES_LOCAL);
  assertEquals("Class files in bundleB_test", 3, resources.size());
  resources = wiring.listResources("org/", null,
      BundleWiring.FINDENTRIES_RECURSE + BundleWiring.LISTRESOURCES_LOCAL);
  assertEquals("All entires in bundleB_test org", 8, resources.size());
  out.println("### framework test bundle :FRAME700A:PASS");
}
 
示例7
@Override
@SuppressWarnings("unchecked")
public <A> A adapt(Class<A> type)
{
  secure.checkAdaptPerm(this, type);
  Object res = null;
  if (FrameworkWiring.class.equals(type)) {
    res = fwWiring;
  } else if (FrameworkStartLevel.class.equals(type)) {
    if (fwCtx.startLevelController != null) {
      res = fwCtx.startLevelController.frameworkStartLevel();
    }
  } else if (Framework.class.equals(type)) {
    res = this;
  } else if (FrameworkStartLevelDTO.class.equals(type)) {
    if (fwCtx.startLevelController != null) {
      res = fwCtx.startLevelController.frameworkStartLevel().getDTO();
    }
  } else if (FrameworkDTO.class.equals(type)) {
    res = getFrameworkDTO();
  } else {
    // TODO filter which adaptation we can do?!
    res = adaptSecure(type);
  }
  return (A) res;
}
 
示例8
/**
 * Do a refresh bundles operation on all bundles that has been updated since
 * the last call.
 */
void refreshUpdatedBundles()
{
  if (!refreshRunning && DeployedBundle.updatedBundles.size() > 0) {
    synchronized (DeployedBundle.updatedBundles) {
      log("Bundles has been updated; refreshing "
          + DeployedBundle.updatedBundles);
      refreshRunning = true;

      final FrameworkWiring fw =
        Activator.bc.getBundle(0).adapt(FrameworkWiring.class);
      fw.refreshBundles(DeployedBundle.updatedBundles, this);
      // Refresh request sent, clear before releasing monitor.
      DeployedBundle.updatedBundles.clear();
    }
  }
}
 
示例9
/**
 * Do a refresh bundles operation on all bundles that has been updated since
 * the last call.
 */
void refreshUpdatedBundles()
{
  if (!refreshRunning && DeployedBundle.updatedBundles.size() > 0) {
    synchronized (DeployedBundle.updatedBundles) {
      log("Bundles has been updated; refreshing "
          + DeployedBundle.updatedBundles);
      refreshRunning = true;

      final FrameworkWiring fw =
        Activator.bc.getBundle(0).adapt(FrameworkWiring.class);
      fw.refreshBundles(DeployedBundle.updatedBundles, this);
      // Refresh request sent, clear before releasing monitor.
      DeployedBundle.updatedBundles.clear();
    }
  }
}
 
示例10
void refreshBundles(final Bundle[] b)
{
  final Bundle systemBundle = Activator.getTargetBC().getBundle(0);
  final FrameworkWiring fw = systemBundle.adapt(FrameworkWiring.class);

  if (fw != null) {
    final ArrayList<Bundle> bundles = new ArrayList<Bundle>();
    final boolean refreshAll = b == null || 0 == b.length;
    final StringBuffer sb = new StringBuffer("Desktop-RefreshPackages ");
    if (refreshAll) {
      sb.append("all packages pending removal");
    } else {
      sb.append("bundle packages for ");
      for (int i = 0; i < b.length; i++) {
        if (i > 0) {
          sb.append(", ");
        }
        sb.append(b[i].getBundleId());
        bundles.add(b[i]);
      }
    }

    final FrameworkListener refreshListener = new FrameworkListener() {

      @Override
      public void frameworkEvent(FrameworkEvent event)
      {
        Activator.log.info(sb.toString() + " DONE.");
      }
    };

    try {
      fw.refreshBundles(bundles, refreshListener);
    } catch (final Exception e) {
      showErr(sb.toString() + " failed to refresh bundles: " + e, e);
    }
  }
}
 
示例11
public void runTest() throws Throwable {
  fw = bc.getBundle(0).adapt(FrameworkWiring.class);
  FrameworkListener fl = new FrameworkListener() {
    @Override
    public void frameworkEvent(FrameworkEvent event) {
      synchronized (this) {
        notifyAll();
      }
    }
  };
  try {
    synchronized (fl) {
      fw.refreshBundles(null, fl);
      fl.wait(3000);
    }
    buCUC1 = Util.installBundle(bc, "bundleCUC1_test-1.0.0.jar");
    assertNotNull(buCUC1);
    buCUC2 = Util.installBundle(bc, "bundleCUC2_test-2.0.0.jar");
    assertNotNull(buCUC2);
    buCUP1 = Util.installBundle(bc, "bundleCUP1_test-1.0.0.jar");
    assertNotNull(buCUP1);
    buCUP2 = Util.installBundle(bc, "bundleCUP2_test-2.0.0.jar");
    assertNotNull(buCUP2);
  } catch (Exception e) {
    fail("Failed to refresh packages: " + e);
  }
}
 
示例12
private FrameworkWiring getFrameworkWiring() {
	return context.getBundle(0).adapt(FrameworkWiring.class);
}
 
示例13
/**
 * @see org.osgi.service.packageadmin.PackageAdmin#refreshPackages(org.osgi.framework.Bundle[])
 */
public void refreshPackages(final Bundle[] bundles) {
	final FrameworkWiring wiring = getFrameworkWiring();

	wiring.refreshBundles(bundles == null ? null : Arrays.asList(bundles));
}
 
示例14
/**
 * @see org.osgi.service.packageadmin.PackageAdmin#resolveBundles(org.osgi.framework.Bundle[])
 */
public boolean resolveBundles(final Bundle[] bundles) {
	final FrameworkWiring wiring = getFrameworkWiring();

	return wiring.resolveBundles(bundles == null ? null : Arrays.asList(bundles));
}
 
示例15
public void run(final BundleContext context) throws BundleException,
		IOException {
	final Bundle[] bundles = new Bundle[NUM];

	long installationTime = 0;

	for (int i = 0; i < NUM; i++) {
		final BundleGenerator gen = new BundleGenerator("bundle" + i,
				new Version(1, 0, i));

		final int dirs = random.nextInt(MAX_IMPORTS_EXPORTS);

		final Set<String> imports = new HashSet<String>();
		final Set<String> exports = new HashSet<String>();

		for (int j = 0; j < dirs; j++) {
			if (random.nextBoolean()) {
				// IMPORT
				final int v1Major = MIN_VERSION_MAJOR
						+ random.nextInt(MAX_VERSION_MAJOR
								- MIN_VERSION_MAJOR + 1);
				final int v2Major = MIN_VERSION_MAJOR
						+ random.nextInt(MAX_VERSION_MAJOR
								- MIN_VERSION_MAJOR + 1);

				final Version v1 = new Version(v1Major, random.nextInt(10),
						random.nextInt(10));

				final Version v2 = new Version(v2Major, random.nextInt(10),
						random.nextInt(10));

				final Version lowerBound = v1.compareTo(v2) < 1 ? v1 : v2;
				final Version upperBound = v1.compareTo(v2) >= 1 ? v1 : v2;

				gen.addPackageImport(drawPackage(imports),
						new VersionRange('[', lowerBound, upperBound, ')'));
			} else {
				// EXPORT
				final Version version = new Version(
						random.nextInt(MAX_VERSION_MAJOR
								- MIN_VERSION_MAJOR + 1),
						random.nextInt(10), random.nextInt(10));

				gen.addPackageExport(drawPackage(exports), version);
			}
		}

		final long t = System.nanoTime();
		bundles[i] = gen.install(context);
		installationTime += (System.nanoTime() - t);
	}

	System.err.println("INSTALLATION TIME " + (installationTime / 1000000));

	final FrameworkWiring fw = context.getBundle(0).adapt(
			FrameworkWiring.class);

	System.err.println("RESOLVING");
	final long time = System.nanoTime();
	fw.resolveBundles(Arrays.asList(bundles));
	System.err.println("RESOLVE TIME " + (System.nanoTime() - time)
			/ 1000000);

}
 
示例16
/**
 * Enforce to call resolve bundle in Concierge framework for the specified
 * bundle.
 */
protected void enforceResolveBundle(final Bundle bundle) {
	// initiate resolver
	framework.adapt(FrameworkWiring.class)
			.resolveBundles(Collections.singleton(bundle));
}
 
示例17
public int cmdPending(Dictionary<String, ?> opts,
                      Reader in,
                      PrintWriter out,
                      Session session)
{
  final boolean doDetailed = opts.get("-l") != null;
  final Bundle systemBundle = bc.getBundle(0);
  final FrameworkWiring frameworkWiring =
      systemBundle.adapt(FrameworkWiring.class);

  Collection<Bundle> bundles = frameworkWiring.getRemovalPendingBundles();
  if (bundles.isEmpty()) {
    out.println("No removal pending.");
  } else {
    Bundle[] barr = bundles.toArray(new Bundle[bundles.size()]);
    if (opts.get("-i") != null) {
      Util.sortBundlesId(barr);
    }
    for (final Bundle element : barr) {
      out.println("Bundle: " + showBundle(element));
      if (doDetailed) {
        out.print("  Reason: ");
        final BundleRevisions brs = element.adapt(BundleRevisions.class);
        final List<BundleRevision> revs = brs.getRevisions();
        if (revs.isEmpty()) {
          out.println("Bundle became unused during command execution.");
        } else {
            switch (revs.get(0).getBundle().getState()) {
            case Bundle.INSTALLED:
              out.println("Bundle has been updated.");
              break;
            case Bundle.UNINSTALLED:
              out.println("Bundle has been uninstalled.");
              break;
            default:
              out.println("Bundle has been updated and resolved.");
          }
        }
      }
    }
  }
  return 0;
}
 
示例18
void resolveBundles(final Bundle[] b)
{
  final Bundle systemBundle = Activator.getTargetBC().getBundle(0);
  final FrameworkWiring fw = systemBundle.adapt(FrameworkWiring.class);

  if (fw != null) {
    final ArrayList<Bundle> bundles = new ArrayList<Bundle>();
    final boolean resolveAll = b == null || 0 == b.length;
    // Must not call resolve() from the EDT, since that will block
    // the EDT.

    final StringBuffer sb = new StringBuffer("Desktop-ResolveBundles: ");
    if (resolveAll) {
      sb.append("all bundles needing to be resolved ");
    } else {
      sb.append("selected bundle(s) ");
      for (int i = 0; i < b.length; i++) {
        if (i > 0) {
          sb.append(", ");
        }
        sb.append(b[i].getBundleId());
        bundles.add(b[i]);
      }
    }

    new Thread(sb.toString()) {
      @Override
      public void run()
      {
        try {
          if (!fw.resolveBundles(bundles)) {
            showErr(sb.toString() + "; could not resolve all of them.", null);
          }
        } catch (final Exception e) {
          showErr(sb.toString() + " failed to resolve bundles: " + e, e);
        }
      }
    }.start();

  }
}