Java Code Examples for org.osgi.framework.Bundle#adapt()

The following examples show how to use org.osgi.framework.Bundle#adapt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PackageAdminImpl.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see org.osgi.service.packageadmin.PackageAdmin#getHosts(org.osgi.framework.Bundle)
 */
public Bundle[] getHosts(final Bundle bundle) {
	final BundleWiring wiring = bundle.adapt(BundleWiring.class);

	if (wiring == null) {
		return null;
	}

	final List<BundleWire> wires = wiring.getRequiredWires(HostNamespace.HOST_NAMESPACE);

	final ArrayList<Bundle> result = new ArrayList<Bundle>();

	for (final BundleWire wire : wires) {
		if (wire.getRequirer().getBundle() == bundle) {
			result.add(wire.getProvider().getBundle());
		}
	}

	return toArrayOrNull(result, Bundle.class);
}
 
Example 2
Source File: PackageAdminImpl.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see org.osgi.service.packageadmin.PackageAdmin#getRequiredBundles(java.lang.String)
 */
public RequiredBundle[] getRequiredBundles(final String symbolicName) {
	final Bundle[] bundles = context.getBundles();

	final ArrayList<RequiredBundle> result = new ArrayList<RequiredBundle>();

	for (final Bundle bundle : bundles) {
		if (bundle.getState() == Bundle.INSTALLED || bundle.getState() == Bundle.UNINSTALLED) {
			continue;
		}

		final BundleRevision rev = bundle.adapt(BundleRevision.class);
		if (isFragment(rev)) {
			continue;
		}

		if (symbolicName == null || symbolicName.equals(rev.getSymbolicName())) {
			result.add(new RequiredBundleImpl(rev));
		}
	}

	return toArrayOrNull(result, RequiredBundle.class);
}
 
Example 3
Source File: NexusBundleTracker.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void prepareDependencies(final Bundle bundle) {
  final BundleWiring wiring = bundle.adapt(BundleWiring.class);
  final List<BundleWire> wires = wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
  if (wires != null) {
    for (final BundleWire wire : wires) {
      try {
        final Bundle dependency = wire.getProviderWiring().getBundle();
        if (!visited.contains(dependency.getSymbolicName()) && hasComponents(dependency)) {
          if (!live(dependency)) {
            dependency.start();
          }
          if (live(dependency)) {
            // pseudo-event to trigger bundle activation
            addingBundle(dependency, null /* unused */);
          }
        }
      }
      catch (final Exception e) {
        log.warn("MISSING {}", wire, e);
      }
    }
  }
}
 
Example 4
Source File: FrameworkNodeImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
public void setBundleStartLevel(long id, int startLevel) {
	Bundle b = context.getBundle(id);
	if(b == null)
		return;
	
	BundleStartLevel bsl = b.adapt(BundleStartLevel.class);
	bsl.setStartLevel(startLevel);
}
 
Example 5
Source File: PackageAdminImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.service.packageadmin.PackageAdmin#getFragments(org.osgi.framework.Bundle)
 */
public Bundle[] getFragments(final Bundle bundle) {
	final BundleWiring wiring = bundle.adapt(BundleWiring.class);
	// this will happen if a bundle has no current revision, e.g.
	// is INSTALLED only
	if (wiring == null) {
		// System.err.println("o.e.c.service.packageadmin: getFragments has
		// no wiring for bundle "
		// + bundle.getSymbolicName());
		return null;
	}
	final List<BundleWire> wires = wiring.getProvidedWires(HostNamespace.HOST_NAMESPACE);

	if (wires == null || wires.isEmpty()) {
		return null;
	}

	final Bundle[] result = new Bundle[wires.size()];

	final Iterator<BundleWire> iter = wires.iterator();
	for (int i = 0; i < result.length; i++) {
		final BundleWire wire = iter.next();
		result[i] = wire.getRequirer().getBundle();
	}

	return result;
}
 
Example 6
Source File: BundleStartLevelResource.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Representation get(final Variant variant) {
	try {
		final Bundle bundle = getBundleFromKeys(RestService.BUNDLE_ID_KEY);
		if (bundle == null) {
			return ERROR(Status.CLIENT_ERROR_NOT_FOUND);
		}
		final BundleStartLevel bsl = bundle.adapt(BundleStartLevel.class);
		final BundleStartLevelPojo sl = new BundleStartLevelPojo(bsl);
		return getRepresentation(sl, variant);
	} catch (final Exception e) {
		return ERROR(e, variant);
	}
}
 
Example 7
Source File: ResolveContextImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public synchronized Map<Resource, Wiring> getWirings() { 
	if(wirings == null) {
		Map<Resource, Wiring> ws = new HashMap<Resource, Wiring>();
		Bundle[] bs = bc.getBundles();
		for(Bundle b : bs) {
			BundleRevision br = b.adapt(BundleRevision.class);
			ws.put(br, br.getWiring());
		}
		wirings = Collections.unmodifiableMap(ws);
	}
	return wirings;
}
 
Example 8
Source File: FrameworkNodeImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
public BundleDTO uninstallBundle(long id) throws BundleException {
	Bundle b  = context.getBundle(id);
	if(b == null)
		return null;
	
	b.uninstall();
	return b.adapt(BundleDTO.class);
}
 
Example 9
Source File: HostApplication.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
private void debugBundle(Bundle b) {
    BundleRevision br = b.adapt(BundleRevision.class);

    br.getCapabilities(null).forEach(System.out::println);

    b.adapt(BundleWiring.class).getProvidedWires(null).forEach(System.out::println);
    ;
}
 
Example 10
Source File: RascalManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private void collectClassPathForBundle(Bundle bundle, List<URL> classPath,
		List<String> compilerClassPath) {
	try {
		File file = FileLocator.getBundleFile(bundle);
		URL url = file.toURI().toURL();

		if (classPath.contains(url)) {
			return; // kill infinite loop
		}
		classPath.add(0, url);
		compilerClassPath.add(0, file.getAbsolutePath());
		
		BundleWiring wiring = bundle.adapt(BundleWiring.class);
		for (BundleWire dep : wiring.getRequiredWires(null)) {
			collectClassPathForBundle(dep.getProviderWiring().getBundle(),
					classPath, compilerClassPath);
		}

		List<String> requiredLibs = new RascalBundleManifest().getRequiredLibraries(bundle);
		if (requiredLibs != null) {
			for (String lib : requiredLibs) {
				classPath.add(bundle.getResource(lib));
			}
		}

	} 
	catch (IOException e) {
		Rasctivator.logException("error while tracing dependencies", e);
	} 
}
 
Example 11
Source File: ClassPatcherWrappers.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get bundle class loader at Class.getSystemClassLoader() calls.
 */
public static ClassLoader getSystemClassLoaderWrapper(long bid, Object context) {
  Bundle b = getBundle(bid);
  if (b == null) {
    throw new IllegalStateException("Undefined bid=" + bid);
  }
  BundleWiring bw = b.adapt(BundleWiring.class);
  if (bw == null) {
    throw new RuntimeException("Unable to adapt Bundle to a BundleWiring" + bid);
  }
  return bw.getClassLoader();
}
 
Example 12
Source File: JHTMLBundle.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get header text for selected bundle page.
 */
public static String getBundleSelectedHeader(Bundle b)
{
  final BundleRevision rev = b.adapt(BundleRevision.class);
  final boolean isFragment =
    rev != null
      ? (rev.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0
      : false;

  return "#" + b.getBundleId() + "  " + Util.getBundleName(b)
         + (isFragment ? "  (fragment)" : "");
}
 
Example 13
Source File: StartLevelImpl.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
private FrameworkStartLevel getFrameworkStartLevel0(){
	Bundle bundle = context.getBundle(0);
	return bundle.adapt(FrameworkStartLevel.class);
}
 
Example 14
Source File: Desktop.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
void updateLevelItems()
{
  final FrameworkStartLevel fsl = getFrameworkStartLevel();
  if (fsl == null) {
    // No start level service present.
    return;
  }
  levelMax = Math.max(levelMax, fsl.getStartLevel());
  levelItems = new String[levelMax - levelMin + 1];

  final Bundle[] bundles = Activator.getTargetBC().getBundles();
  final StringBuffer sb = new StringBuffer();
  for (final Bundle bundle : bundles) {
    final BundleStartLevel bsl = bundle.adapt(BundleStartLevel.class);
    if (bsl != null) {
      final int ix = bsl.getStartLevel() - levelMin;
      if (0 <= ix && ix < levelItems.length) {
        sb.setLength(0);
        if (levelItems[ix] != null) {
          sb.append(levelItems[ix]);
        }
        if (sb.length() > 0) {
          sb.append(", ");
        }
        final String name = Util.getBundleName(bundle);
        sb.append(name);
        levelItems[ix] = sb.toString();
      }
    }
  }

  final int maxItemLen = 70;
  for (int level = levelMin; level <= levelMax; level++) {
    sb.setLength(0);
    final String levelBundles = levelItems[level - levelMin];
    sb.append("<html><b>");
    sb.append(level);
    sb.append("</b><font size=\"-2\" color=\"#666666\">");
    if (levelBundles != null) {
      sb.append("<font size=\"-2\">&nbsp;[");
      if (levelBundles.length() > maxItemLen) {
        sb.append(levelBundles.subSequence(0, maxItemLen));
        sb.append("...");
      } else {
        sb.append(levelBundles);
      }
      sb.append("]</font>");
    }
    sb.append("</html>");
    levelItems[level - levelMin] = sb.toString();
  }

  if (levelBox != null) {
    final DefaultComboBoxModel model = new DefaultComboBoxModel(levelItems);
    levelBox.setModel(model);
    // Avoid a lot of whitespace to the right of any "..."
    levelBox.setMaximumSize(levelBox.getPreferredSize());
  }
}
 
Example 15
Source File: TableDisplayer.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Object getValueAt(int row, int column)
{
  final Bundle b = getBundle(row);

  switch (column) {
  case COL_LOCATION:
    return Util.shortLocation(b.getLocation());
  case COL_ID:
    // return Long.toString(b.getBundleId());
    return Long.valueOf(b.getBundleId());
  case COL_STATE:
    return Util.stateName(b.getState());
  case COL_STARTLEVEL: {
    final BundleStartLevel bsl = b.adapt(BundleStartLevel.class);

    if (null != bsl) {
      try {
        final int n = bsl.getStartLevel();
        return Integer.valueOf(n);
      } catch (final Exception e) {
        // not managed, indicate with -1
        return Integer.valueOf(-1);
      }
    } else {
      // No start level adaptation available, indicate with -2
      return Integer.valueOf(-2);
    }
  }
  case COL_DESC:
    return Util.getHeader(b, Constants.BUNDLE_DESCRIPTION);
  case COL_NAME:
    return Util.getHeader(b, Constants.BUNDLE_NAME);
  case COL_VENDOR:
    return Util.getHeader(b, Constants.BUNDLE_VENDOR);
  case COL_SYMBOLIC_NAME:
    return b.getSymbolicName();
  case COL_VERSION:
    return b.getVersion();
  default:
    return null;
  }
}
 
Example 16
Source File: FrameworkCommandGroup.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public int cmdCapability(Dictionary<String, ?> opts,
                         Reader in,
                         PrintWriter out,
                         Session session)
{
  final Bundle[] b = getBundles((String[]) opts.get("bundle"),
                          opts.get("-i") != null);
  final boolean doRequirements = opts.get("-r")!=null;
  final boolean doProvides = opts.get("-p")!=null;
  final boolean doDetailed = opts.get("-l")!=null;
  final boolean doDeclared = opts.get("-d")!=null;

  boolean found = false;
  for (final Bundle element : b) {
    if (element != null) {
      out.println("Bundle: " + showBundle(element));
      found = true;
      final BundleRevision rev = element.adapt(BundleRevision.class);
      final BundleWiring wiring = rev.getWiring();
      if (!doDeclared && wiring == null) {
        out.println("  Bundle is unresolved, only declared capabilites are available.");
      } else {
        final String prefix = doDeclared ? "  Declared " : "  ";

        if (doRequirements || !doProvides) {
          out.print(prefix);
          out.println("Requirements: ");
          final List<BundleRequirement> reqs = doDeclared
            ? rev.getDeclaredRequirements(null)
            : rev.getWiring().getRequirements(null);
          for (final BundleRequirement req : reqs) {
            out.print("    ");
            out.print(req.getNamespace());
            out.print("  ");
            if (!doDetailed) {
              final String f = req.getDirectives().get(Constants.FILTER_DIRECTIVE);
              out.println(f != null ? f : "NO FILTER");
            } else {
              out.println(req.getDirectives());
            }
          }
        }

        if (doProvides || !doRequirements) {
          out.print(prefix);
          out.println("Capabilites: ");
          final List<BundleCapability> caps = doDeclared
            ? rev.getDeclaredCapabilities(null)
            : rev.getWiring().getCapabilities(null);
          for (final BundleCapability bc : caps) {
            out.print("    ");
            out.print(bc.getNamespace());
            out.print("  ");
            out.print(bc.getAttributes());
            if (doDetailed) {
              out.print(" ");
              out.print(bc.getDirectives());
            }
            out.println();
          }
        }
      }
    }
  }
  if (!found) {
    out.println("ERROR! No matching bundle");
    return 1;
  }
  return 0;
}
 
Example 17
Source File: StartLevelImpl.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
private BundleStartLevel getBundleStartLevel0(Bundle bundle){
	return bundle.adapt(BundleStartLevel.class);
}
 
Example 18
Source File: Desktop.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
void stopBundle(final Bundle b)
{
  // Fragments can not be stopped
  final BundleRevision br = b.adapt(BundleRevision.class);
  if ((br.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) {
    return;
  }

  // Special handling needed when stopping the desktop itself.
  final boolean stoppingSelf =
    b.getBundleId() == 0
        || b.getBundleId() == Activator.getTargetBC().getBundle()
            .getBundleId();

  int n = 0;
  if (stoppingSelf) {
    final Object[] options = { Strings.get("yes"), Strings.get("no") };
    n =
      JOptionPane.showOptionDialog(frame,
                                   Strings.fmt("fmt_q_stopdesktop",
                                               Util.getBundleName(b)),
                                   Strings.get("yes"),
                                   JOptionPane.YES_NO_OPTION,
                                   JOptionPane.QUESTION_MESSAGE, null,
                                   options, options[1]);
  }

  if (n == 0) {
    // Must not call stop() from the EDT, since that will block the
    // EDT untill the stop()-call completes.
    new Thread("Desktop-StopBundle " + b.getBundleId()) {
      @Override
      public void run()
      {
        try {
          b.stop(getStopOptions());
          updateBundleViewSelections();
        } catch (final Exception e) {
          showErr("Failed to stop bundle " + Util.getBundleName(b) + ": " + e,
                  e);
        }
      }
    }.start();
  }
}
 
Example 19
Source File: AuthHttpContext.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
private Set<Bundle> getBundlesInClassSpace(BundleContext context,
                                                  Bundle bundle, Set<Bundle> bundleSet) {
    Set<Bundle> bundles = new HashSet<>(); // The set containing the
    // bundles either being
    // imported or required
    if (bundle == null) {
        log.error("Incoming bundle is null");
        return bundles;
    }
    if (context == null) {
        log.error("Incoming context is null");
        return bundles;
    }

    BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
    if (bundleWiring == null) {
        log.error("BundleWiring is null for: " + bundle);
        return bundles;
    }

    // This will give us all required Wires (including require-bundle)
    List<BundleWire> requiredWires = bundleWiring.getRequiredWires(null);
    for (BundleWire bundleWire : requiredWires) {
        Bundle exportingBundle = bundleWire.getCapability().getRevision()
                .getBundle();

        if (exportingBundle.getBundleId() == 0) {
            continue; // system bundle is skipped this one isn't needed
        }
        if (!bundles.contains(exportingBundle)) {
            bundles.add(exportingBundle);
        }
    }

    if (!bundleSet.containsAll(bundles)) { // now let's scan transitively
        bundles.removeAll(bundleSet);
        bundleSet.addAll(bundles);
    }

    // Sanity checkpoint to remove uninstalled bundles
    bundleSet.removeIf(auxBundle -> auxBundle.getState() == Bundle.UNINSTALLED);

    return bundleSet;
}
 
Example 20
Source File: FrameworkCommandGroup.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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;
}