Java Code Examples for org.osgi.framework.BundleContext#getBundles()

The following examples show how to use org.osgi.framework.BundleContext#getBundles() . 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: Activator.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void start(final BundleContext bundleContext) throws Exception {
    ProviderUtil.STARTUP_LOCK.lock();
    lockingProviderUtil = true;
    final BundleWiring self = bundleContext.getBundle().adapt(BundleWiring.class);
    final List<BundleWire> required = self.getRequiredWires(LoggerContextFactory.class.getName());
    for (final BundleWire wire : required) {
        loadProvider(bundleContext, wire.getProviderWiring());
    }
    bundleContext.addBundleListener(this);
    final Bundle[] bundles = bundleContext.getBundles();
    for (final Bundle bundle : bundles) {
        loadProvider(bundle);
    }
    unlockIfReady();
}
 
Example 2
Source File: WisdomBlackBoxTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
public static void installTestBundle() throws BundleException {
    BundleContext context = ChameleonInstanceHolder.get().context();
    // Check whether the test bundle is already installed
    Bundle probe = null;
    for (Bundle bundle : context.getBundles()) {
        if (bundle.getSymbolicName().equalsIgnoreCase(ProbeBundleMaker.BUNDLE_NAME)) {
            probe = bundle;
        }
    }

    if (probe != null) {
        LOGGER.info("Probe / Test bundle already deployed");
    } else {
        probe = ChameleonExecutor.deployProbe();
        LOGGER.info("Probe / Test bundle deployed ({})", probe.getBundleId());
        ChameleonInstanceHolder.get().waitForStability();
    }
}
 
Example 3
Source File: EventBrokerBuilderDS.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * initialize the cep service here.
 *
 * @param context
 */
@Activate
protected void activate(ComponentContext context) {

    this.eventBrokerHandler = new EventBrokerHandler(context);
    // need to differ the bundle deployment if the Qpid bundle is in the plugins directory and it is not
    // started
    boolean isQpidBundlePresent = false;
    final BundleContext bundleContext = context.getBundleContext();
    for (Bundle bundle : bundleContext.getBundles()) {
        if (bundle.getSymbolicName().equals("org.wso2.carbon.qpid")) {
            isQpidBundlePresent = true;
            break;
        }
    }
    if (isQpidBundlePresent) {
        // if the Qpid bundle is present we register an event broker handler
        // so that the qpid compoent will notify that.
        context.getBundleContext().registerService(EventBundleNotificationService.class.getName(), this
                .eventBrokerHandler, null);
    } else {
        this.eventBrokerHandler.startEventBroker();
    }
}
 
Example 4
Source File: EclipseUtil.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a map of all loaded bundle symbolic names mapped to bundles
 * 
 * @return
 */
public static Map<String, BundleContext> getCurrentBundleContexts()
{
	Map<String, BundleContext> contexts = new HashMap<String, BundleContext>();

	BundleContext context = CorePlugin.getDefault().getContext();
	contexts.put(context.getBundle().getSymbolicName(), context);

	Bundle[] bundles = context.getBundles();
	for (Bundle bundle : bundles)
	{
		BundleContext bContext = bundle.getBundleContext();
		if (bContext == null)
		{
			continue;
		}
		contexts.put(bundle.getSymbolicName(), bContext);
	}

	return contexts;
}
 
Example 5
Source File: TLCWorkerConsumer.java    From tlaplus with MIT License 5 votes vote down vote up
private Bundle getTlaToolsBundle() {
	BundleContext ctx = FrameworkUtil.getBundle(
			TLCWorkerConsumer.class).getBundleContext();
	final Bundle[] bundles = ctx.getBundles();
	for (Bundle bundle : bundles) {
		if ("org.lamport.tlatools".equals(bundle.getSymbolicName())) {
			return bundle;
		}
	}
	// Getting here is very bad and means my assumptions about the
	// environment are incorrect, sorry :-(
	return null;
}
 
Example 6
Source File: SyntheticBundleInstaller.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isBundleAvailable(BundleContext context, String bsn) {
    for (Bundle bundle : context.getBundles()) {
        if (bundle.getSymbolicName().equals(bsn) && bundle.getState() == Bundle.ACTIVE) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: SiddhiExtensionLoader.java    From siddhi with Apache License 2.0 5 votes vote down vote up
void loadAllExtensions(BundleContext bundleContext) {
    for (Bundle b : bundleContext.getBundles()) {
        if (b.getState() == Bundle.ACTIVE) {
            addExtensions(b);
        }
    }
}
 
Example 8
Source File: OSGIServiceLoader.java    From incubator-tamaya with Apache License 2.0 5 votes vote down vote up
public OSGIServiceLoader(BundleContext context) {
    this.context = Objects.requireNonNull(context);
    // Check for matching bundles already installed...
    for (Bundle bundle : context.getBundles()) {
        if (bundle.getState() == Bundle.ACTIVE) {
            checkAndLoadBundle(bundle);
        }
    }
}
 
Example 9
Source File: CatalogUpgradeScanner.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void scanAllBundles(
        final CatalogUpgrades.Builder catalogUpgradesBuilder,
        final BundleContext bundleContext
) {
    for (Bundle bundle : bundleContext.getBundles()) {
        final CatalogUpgrades catalogUpgrades = bundleUpgradeParser.apply(bundle, typeSupplier(bundle));
        catalogUpgradesBuilder.addAll(catalogUpgrades);
    }
}
 
Example 10
Source File: EmbeddedFelixFramework.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static Map<String, Bundle> getInstalledBundlesById(BundleContext bundleContext) {
    Map<String, Bundle> installedBundles = new HashMap<String, Bundle>();
    Bundle[] bundles = bundleContext.getBundles();
    for (Bundle b : bundles) {
        installedBundles.put(OsgiUtils.getVersionedId(b), b);
    }
    return installedBundles;
}
 
Example 11
Source File: SyntheticBundleInstaller.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Updates given bundle into the test runtime (the content is changed, but the symbolic name of the bundles remains
 * the same) with a new content, prepared in another resources directory.
 *
 * @param bundleContext the bundle context of the test runtime
 * @param bundleToUpdateName the symbolic name of the bundle to be updated
 * @param updateDirName the location of the new content, that the target bundle will be updated with
 * @param extensionsToInclude a list of extension to be included into the synthetic bundle
 * @return the Bundle representation of the updated bundle
 * @throws Exception thrown when error occurs while installing or starting the synthetic bundle
 */
public static Bundle update(BundleContext bundleContext, String bundleToUpdateName, String updateDirName,
        Set<String> extensionsToInclude) throws Exception {
    // Stop the bundle to update first
    Bundle[] bundles = bundleContext.getBundles();
    for (Bundle bundle : bundles) {
        if (bundleToUpdateName.equals(bundle.getSymbolicName())) {
            // we have to uninstall the bundle to update its contents
            bundle.uninstall();
            break;
        }
    }

    // New bytes are taken from the update path
    String updatePath = BUNDLE_POOL_PATH + "/" + updateDirName + "/";
    byte[] updatedBundleBytes = createSyntheticBundle(bundleContext.getBundle(), updatePath, bundleToUpdateName,
            extensionsToInclude);

    // The updated bytes are installed with the same name
    Bundle syntheticBundle = bundleContext.installBundle(bundleToUpdateName,
            new ByteArrayInputStream(updatedBundleBytes));

    // Starting the bundle
    syntheticBundle.start(Bundle.ACTIVE);
    waitUntilLoadingFinished(bundleContext, syntheticBundle);
    return syntheticBundle;
}
 
Example 12
Source File: CXFExtensionBundleListener.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void registerExistingBundles(BundleContext context) throws IOException {
    for (Bundle bundle : context.getBundles()) {
        if ((bundle.getState() == Bundle.RESOLVED
            || bundle.getState() == Bundle.STARTING
            || bundle.getState() == Bundle.ACTIVE
            || bundle.getState() == Bundle.STOPPING)
            && bundle.getBundleId() != context.getBundle().getBundleId()) {
            register(bundle);
        }
    }
}
 
Example 13
Source File: OSGiTestBase.java    From Java-Thread-Affinity with Apache License 2.0 5 votes vote down vote up
public static Bundle findBundle(BundleContext context, String symbolicName) {
    Bundle[] bundles = context.getBundles();
    for (Bundle bundle : bundles) {
        if (bundle != null) {
            if (bundle.getSymbolicName().equals(symbolicName)) {
                return bundle;
            }
        }
    }

    return null;
}
 
Example 14
Source File: BundleCheckActivator.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public void start(final BundleContext bundleContext) throws Exception {

		/*
         * Check for the services that should be deployed before this if there
		 * are any.
		 * if there are such services we wait for such bundles to deploy and
		 * gets the notification
		 * through a service listener.
		 */

        // first check whether there are such services and they have already
        // deployed.
        String pendingBundleName = null;
        final List<Bundle> pendingBundles = new ArrayList<Bundle>();
        for (Bundle bundle : bundleContext.getBundles()) {
            pendingBundleName = (String) bundle.getHeaders().get(DEPLOY_BEFORE);
            if ((pendingBundleName != null) && (pendingBundleName.equals(getName())) &&
                    (bundle.getState() != Bundle.ACTIVE)) {
                // i.e this bundle should be started before the user manager but
                // yet has not started
                pendingBundles.add(bundle);
            }
        }

        if (pendingBundles.isEmpty()) {
            startDeploy(bundleContext);
        } else {
            BundleListener bundleListener = new BundleListener() {
                public void bundleChanged(BundleEvent bundleEvent) {
                    synchronized (pendingBundles) {
                        if (bundleEvent.getType() == BundleEvent.STARTED) {

                            pendingBundles.remove(bundleEvent.getBundle());
                            if (pendingBundles.isEmpty()) {
                                // now start the user manager deployment
                                bundleContext.removeBundleListener(this);
                                try {
                                    startDeploy(bundleContext);
                                } catch (Exception e) {
                                    log.error("Can not start the bundle ", e);
                                }
                            }
                        }
                    }
                }
            };
            bundleContext.addBundleListener(bundleListener);
        }
    }
 
Example 15
Source File: BundleEntry.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
public BundleEntry(JarEntry entry, InputStream is, BundleContext bundleContext) throws IOException {
    super(entry, is);
    String[] segments = entry.getName().split("\\/");
    String startStr = segments[2];
    if (segments[1].contains(".")) {
        runmode = StringUtils.substringAfter(segments[1], ".");
    } else {
        runmode = null;
    }
    start = Integer.parseInt(startStr, 10);
    log.debug("Loaded start level {}", start);
    try (JarInputStream bundleIs = new JarInputStream(new ByteArrayInputStream(this.getContents()))) {

        Manifest manifest = bundleIs.getManifest();
        Attributes attributes = manifest.getMainAttributes();

        if (attributes.getValue(BUNDLE_SYMBOLIC_NAME).contains(";")) {
            symbolicName = StringUtils.substringBefore(attributes.getValue(BUNDLE_SYMBOLIC_NAME), ";");
        } else {
            symbolicName = attributes.getValue(BUNDLE_SYMBOLIC_NAME);
        }
        log.debug("Loaded symbolic name: {}", symbolicName);

        version = new Version(attributes.getValue("Bundle-Version"));
        log.debug("Loaded version: {}", version);
    }

    Bundle currentBundle = null;
    for (Bundle b : bundleContext.getBundles()) {
        if (b.getSymbolicName().equals(this.symbolicName)) {
            currentBundle = b;
        }
    }
    if (currentBundle != null) {
        installed = true;
        if (currentBundle.getVersion().compareTo(version) < 0) {
            updated = true;
        } else {
            updated = false;
        }
    } else {
        installed = false;
        updated = true;
    }
}
 
Example 16
Source File: AdminBundleChecker.java    From opencps-v2 with GNU Affero General Public License v3.0 4 votes vote down vote up
@Activate
public void start() {

	try {
		
		Bundle bundle = FrameworkUtil.getBundle(getClass());

		BundleContext ctx =  bundle.getBundleContext();
		
		Bundle[] bundles = ctx.getBundles();
		
		new AdminBundlesInstalled(ctx, bundles);
		

	}
	catch (Exception e) {
		_log.error(e);
	}
	
	System.out.println("START OPENCPS KERNEL ^_^");
}
 
Example 17
Source File: DefaultSwingBundleDisplayer.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static private Bundle[] getBundles()
{
  final BundleContext tbc = getTargetBundleContext();
  final Bundle[] bl = tbc == null ? null : tbc.getBundles();
  return bl;
}
 
Example 18
Source File: NetigsoActivationTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testActivation() throws Exception {
    ModuleSystem ms = Main.getModuleSystem();
    mgr = ms.getManager();
    mgr.mutexPrivileged().enterWriteAccess();
    int checks = 0;
    try {
        File simpleModule = new File(jars, "activate.jar");
        m1 = mgr.create(simpleModule, null, false, false, false);
        mgr.enable(m1);

        Class<?> main = m1.getClassLoader().loadClass("org.activate.Main");
        Object s = main.getField("start").get(null);
        assertNotNull("Bundle started, its context provided", s);

        BundleContext bc = (BundleContext)s;
        StringBuilder sb = new StringBuilder();
        for (Bundle b : bc.getBundles()) {
            URL root = b.getEntry("/");
            if (root == null) {
                sb.append("No root URL for ").append(b.getSymbolicName()).append("\n");
            }
            BundleFile bFile = null;
            if (b instanceof AbstractBundle) {
                BundleData bd = ((AbstractBundle) b).getBundleData();
                if (bd instanceof BaseData) {
                    bFile = ((BaseData) bd).getBundleFile();
                }
            }
            assertNotNull("All our bundles have BundleFile", bFile);
            
            Enumeration<URL> en = b.findEntries("/", null, true);
            if (en == null) {
                sb.append("No entries for ").append(b.getSymbolicName()).append("\n");
                continue;
            }
            while (en.hasMoreElements()) {
                URL u = en.nextElement();
                final String ef = u.toExternalForm();
                int pref = ef.indexOf("/org/");
                int last = ef.lastIndexOf("/");
                if (pref != -1 && last != -1) {
                    String entry = ef.substring(pref + 1, last + 1);
                    assertTrue("/ is at the end", entry.endsWith("/"));
                    checks++;
                    final URL found = b.getEntry(entry);
                    assertNotNull("Entry found " + entry + " in " + b.getSymbolicName(), found);
                    assertTrue("Directory found", bFile.containsDir(entry));
                    BundleEntry ee = bFile.getEntry(entry);
                    URL local = ee.getLocalURL();
                    assertEquals("JAR protocol used", "jar", local.getProtocol());
                    if (!local.toExternalForm().contains("!/")) {
                        fail("!/ shall be in the URL: " + local);
                    }
                    
                    final String nonExist = "non/existent/entry/";
                    URL notFound = b.getEntry(nonExist);
                    assertNull("Entries for non-existing entries are not found", notFound);
                    assertFalse("Non-existent not found", bFile.containsDir(nonExist));
                }
            }
        }
        if (sb.length() > 0) {
            fail(sb.toString());
        }
        if (checks == 0) {
            fail("There shall be some checks for entries");
        }

        assertNotNull("OSGi version available to contexts", bc.getProperty("osgi.framework.version"));
        
        String version = System.getProperty("osgi.framework.version");
        assertNull("Version is not available in system properties by default", version);
        
        mgr.disable(m1);

        Object e = main.getField("stop").get(null);
        assertNotNull("Bundle stopped, its context provided", e);
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }
}
 
Example 19
Source File: ExternalDirectoryTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testActivation() throws Exception {
    ModuleSystem ms = Main.getModuleSystem();
    mgr = ms.getManager();
    mgr.mutexPrivileged().enterWriteAccess();
    int checks = 0;
    
    System.setProperty("activated.checkentries", "/org/test/x.txt");
    try {
        m1 = mgr.create(simpleModule, null, false, false, false);
        mgr.enable(m1);

        Class<?> main = m1.getClassLoader().loadClass("org.activate.Main");
        Object s = main.getField("start").get(null);
        assertNotNull("Bundle started, its context provided", s);

        BundleContext bc = (BundleContext)s;
        StringBuilder sb = new StringBuilder();
        for (Bundle b : bc.getBundles()) {
            URL root = b.getEntry("/");
            if (root == null) {
                sb.append("No root URL for ").append(b.getSymbolicName()).append("\n");
            }
            
            Enumeration<URL> en = b.findEntries("/", null, true);
            if (en == null) {
                sb.append("No entries for ").append(b.getSymbolicName()).append("\n");
                continue;
            }
            while (en.hasMoreElements()) {
                URL u = en.nextElement();
                final String ef = u.toExternalForm();
                int pref = ef.indexOf("/org/");
                int last = ef.lastIndexOf("/");
                if (pref != -1 && last != -1) {
                    String entry = ef.substring(pref + 1, last + 1);
                    assertTrue("/ is at the end", entry.endsWith("/"));
                    checks++;
                    final URL found = b.getEntry(entry);
                    assertNotNull("Entry found " + entry + " in " + b.getSymbolicName(), found);
                    
                    URL notFound = b.getEntry("non/existent/entry/");
                    assertNull("Entries for non-existing entries are not found", notFound);
                }
            }
        }
        if (sb.length() > 0) {
            fail(sb.toString());
        }
        if (checks == 0) {
            fail("There shall be some checks for entries");
        }
        String text = System.getProperty("activated.entry");
        assertEquals("Ahoj", text);

        String localURL = System.getProperty("activated.entry.local");
        assertNotNull("bundleentry read OK", localURL);
        assertTrue("external file is referred as file:/.... = " + localURL, localURL.startsWith("file:/"));
        assertEquals("Ahoj", readLine(localURL));

        String fileURL = System.getProperty("activated.entry.file");
        assertNotNull("fileURL found", fileURL);
        assertTrue("file:/..... = " + fileURL, fileURL.startsWith("file:/"));
        assertEquals("Ahoj", readLine(fileURL));

        mgr.disable(m1);

        Object e = main.getField("stop").get(null);
        assertNotNull("Bundle stopped, its context provided", e);
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }
}
 
Example 20
Source File: SyntheticBundleInstaller.java    From openhab-core with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Uninstalls the synthetic bundle (or bundle fragment), denoted by its name, from the test runtime.
 *
 * <p>
 * This method should only be used if the bundle itself provides a symbolic name.
 * If possible you should use {@link #uninstall(Bundle)} and give the bundle that has been provided by one of the
 * install methods.
 *
 * @param bundleContext the bundle context of the test runtime
 * @param testBundleName the name of the test bundle to be uninstalled
 * @throws BundleException if error is met during the bundle uninstall
 */
public static void uninstall(BundleContext bundleContext, String testBundleName) throws BundleException {
    Bundle[] bundles = bundleContext.getBundles();
    for (Bundle bundle : bundles) {
        if (testBundleName.equals(bundle.getSymbolicName())) {
            bundle.uninstall();
        }
    }
}