org.osgi.framework.Bundle

Here are the examples of the java api class org.osgi.framework.Bundle taken from open source projects.

1. BlueprintPropertiesTest#testProperties()

Project: camel
Source File: BlueprintPropertiesTest.java
View license
@Test
public void testProperties() throws Exception {
    Bundle camelCore = getBundleBySymbolicName("org.apache.camel.camel-core");
    Bundle test = getBundleBySymbolicName(getClass().getSimpleName());
    camelCore.stop();
    test.stop();
    Thread.sleep(500);
    test.start();
    try {
        getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=" + getClass().getSimpleName() + ")", 500);
        fail("Expected a timeout");
    } catch (RuntimeException e) {
    }
    camelCore.start();
    CamelBlueprintHelper.waitForBlueprintContainer(null, test.getBundleContext(), getClass().getSimpleName(), BlueprintEvent.CREATED, null);
    getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=" + getClass().getSimpleName() + ")", 500);
}

2. AbstractLoadBundleTest#testLoadStartStop()

View license
/**
     * Loads, starts, and stops a bundle.
     *
     * @throws BundleException
     */
@Test
public void testLoadStartStop() throws BundleException {
    final BundleContext bundleContext = osgi.getFramework().getBundleContext();
    final Bundle bundle = bundleContext.installBundle("file:" + getBundlePath());
    Assert.assertNotNull("Error loading bundle: null returned", bundle);
    Assert.assertEquals("Error loading bundle: symbolic name mismatch", getExpectedBundleSymbolicName(), bundle.getSymbolicName());
    Assert.assertEquals("Bundle is not in INSTALLED state", Bundle.INSTALLED, bundle.getState());
    // sanity check: start and stop bundle
    bundle.start();
    Assert.assertEquals("Bundle is not in ACTIVE state", Bundle.ACTIVE, bundle.getState());
    bundle.stop();
    Assert.assertEquals("Bundle is not in RESOLVED state", Bundle.RESOLVED, bundle.getState());
    bundle.start();
    Assert.assertEquals("Bundle is not in ACTIVE state", Bundle.ACTIVE, bundle.getState());
    bundle.stop();
    Assert.assertEquals("Bundle is not in RESOLVED state", Bundle.RESOLVED, bundle.getState());
    bundle.uninstall();
    Assert.assertEquals("Bundle is not in UNINSTALLED state", Bundle.UNINSTALLED, bundle.getState());
}

3. BlueprintContainer2BTCustomizerTest#test()

View license
@Test
// This test crashes the vm when run from maven. It works fine when run from eclipse
@Ignore
public void test() throws Exception {
    CompositeBundle cb = createCompositeBundle();
    BundleContext compositeBundleContext = cb.getCompositeFramework().getBundleContext();
    Bundle testBundle = installBundle(compositeBundleContext, sampleBundleOption().getURL());
    Bundle configAdminBundle = installBundle(compositeBundleContext, configAdminOption().getURL());
    // start the composite bundle, config admin then the blueprint sample
    cb.start();
    configAdminBundle.start();
    // create a config to check the property placeholder
    applyCommonConfiguration(compositeBundleContext);
    testBundle.start();
    startBlueprintBundles();
    // do the test
    Helper.testBlueprintContainer(new RichBundleContext(compositeBundleContext), testBundle);
}

4. BlueprintContainerBTCustomizerTest#test()

View license
@Test
public void test() throws Exception {
    CompositeBundle cb = createCompositeBundle();
    BundleContext compositeBundleContext = cb.getCompositeFramework().getBundleContext();
    Bundle testBundle = installBundle(compositeBundleContext, sampleBundleOption().getURL());
    Bundle configAdminBundle = installBundle(compositeBundleContext, configAdminOption().getURL());
    // start the composite bundle, config admin then the blueprint sample
    cb.start();
    configAdminBundle.start();
    // create a config to check the property placeholder
    applyCommonConfiguration(compositeBundleContext);
    testBundle.start();
    // do the test
    Helper.testBlueprintContainer(new RichBundleContext(compositeBundleContext), testBundle);
}

5. SubsystemDependency_4CTest#verifyNoUnexpectedBundlesProvisioned()

View license
@Test
public void verifyNoUnexpectedBundlesProvisioned() throws Exception {
    Bundle[] rootBundlesBefore = bundleContext.getBundles();
    s1 = installSubsystemFromFile(SUBSYSTEM_S1);
    startSubsystem(s1);
    Bundle[] s1BundlesBefore = bundleContext.getBundles();
    s2 = installSubsystemFromFile(s1, SUBSYSTEM_S2);
    startSubsystem(s2);
    Bundle[] rootBundlesAfter = bundleContext.getBundles();
    Bundle[] s1BundlesAfter = bundleContext.getBundles();
    checkNoNewBundles("rootBundles", rootBundlesBefore, rootBundlesAfter);
    checkNoNewBundles("s1Bundles", s1BundlesBefore, s1BundlesAfter);
    stopSubsystems();
}

6. BlueprintContainer2BTCustomizerTest#test()

View license
@Test
// This test crashes the vm when run from maven. It works fine when run from eclipse
@Ignore
public void test() throws Exception {
    CompositeBundle cb = createCompositeBundle();
    BundleContext compositeBundleContext = cb.getCompositeFramework().getBundleContext();
    Bundle testBundle = installBundle(compositeBundleContext, sampleBundleOption().getURL());
    Bundle configAdminBundle = installBundle(compositeBundleContext, configAdminOption().getURL());
    // start the composite bundle, config admin then the blueprint sample
    cb.start();
    configAdminBundle.start();
    // create a config to check the property placeholder
    applyCommonConfiguration(compositeBundleContext);
    testBundle.start();
    startBlueprintBundles();
    // do the test
    Helper.testBlueprintContainer(new RichBundleContext(compositeBundleContext), testBundle);
}

7. BlueprintContainerBTCustomizerTest#test()

View license
@Test
public void test() throws Exception {
    CompositeBundle cb = createCompositeBundle();
    BundleContext compositeBundleContext = cb.getCompositeFramework().getBundleContext();
    Bundle testBundle = installBundle(compositeBundleContext, sampleBundleOption().getURL());
    Bundle configAdminBundle = installBundle(compositeBundleContext, configAdminOption().getURL());
    // start the composite bundle, config admin then the blueprint sample
    cb.start();
    configAdminBundle.start();
    // create a config to check the property placeholder
    applyCommonConfiguration(compositeBundleContext);
    testBundle.start();
    // do the test
    Helper.testBlueprintContainer(new RichBundleContext(compositeBundleContext), testBundle);
}

8. SubsystemDependency_4CTest#verifyNoUnexpectedBundlesProvisioned()

View license
@Test
public void verifyNoUnexpectedBundlesProvisioned() throws Exception {
    Bundle[] rootBundlesBefore = bundleContext.getBundles();
    s1 = installSubsystemFromFile(SUBSYSTEM_S1);
    startSubsystem(s1);
    Bundle[] s1BundlesBefore = bundleContext.getBundles();
    s2 = installSubsystemFromFile(s1, SUBSYSTEM_S2);
    startSubsystem(s2);
    Bundle[] rootBundlesAfter = bundleContext.getBundles();
    Bundle[] s1BundlesAfter = bundleContext.getBundles();
    checkNoNewBundles("rootBundles", rootBundlesBefore, rootBundlesAfter);
    checkNoNewBundles("s1Bundles", s1BundlesBefore, s1BundlesAfter);
    stopSubsystems();
}

9. BundleWiringStateMBeanTest#testCurrentWiringClosure()

View license
@Test
public void testCurrentWiringClosure() throws Exception {
    TabularData jmxWiringClosure = brsMBean.getCurrentWiringClosure(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
    CompositeData jmxWiringA = jmxWiringClosure.get(new Object[] { bundleA.getBundleId(), 0 });
    assertBundleWiring((BundleWiring) bundleA.adapt(BundleWiring.class), jmxWiringA);
    Bundle b = context().getBundleByName("org.apache.aries.jmx.test.bundleb");
    int bRevID = findRevisionID(jmxWiringA, b);
    CompositeData jmxWiringB = jmxWiringClosure.get(new Object[] { b.getBundleId(), bRevID });
    assertBundleWiring((BundleWiring) b.adapt(BundleWiring.class), jmxWiringB);
    Bundle cm = context().getBundleByName("org.apache.felix.configadmin");
    int cmRevID = findRevisionID(jmxWiringA, cm);
    CompositeData jmxWiringCM = jmxWiringClosure.get(new Object[] { cm.getBundleId(), cmRevID });
    assertBundleWiring((BundleWiring) cm.adapt(BundleWiring.class), jmxWiringCM);
    Bundle sb = context().getBundle(0);
    int sbRevID = findRevisionID(jmxWiringA, sb);
    CompositeData jmxWiringSB = jmxWiringClosure.get(new Object[] { sb.getBundleId(), sbRevID });
    assertBundleWiring((BundleWiring) sb.adapt(BundleWiring.class), jmxWiringSB);
}

10. BundleWiringStateMBeanTest#testRevisionsWiringClosure()

View license
@Test
public void testRevisionsWiringClosure() throws Exception {
    TabularData jmxWiringClosure = brsMBean.getRevisionsWiringClosure(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
    CompositeData jmxWiringA = jmxWiringClosure.get(new Object[] { bundleA.getBundleId(), 0 });
    assertBundleWiring((BundleWiring) bundleA.adapt(BundleWiring.class), jmxWiringA);
    Bundle b = context().getBundleByName("org.apache.aries.jmx.test.bundleb");
    int bRevID = findRevisionID(jmxWiringA, b);
    CompositeData jmxWiringB = jmxWiringClosure.get(new Object[] { b.getBundleId(), bRevID });
    assertBundleWiring((BundleWiring) b.adapt(BundleWiring.class), jmxWiringB);
    Bundle cm = context().getBundleByName("org.apache.felix.configadmin");
    int cmRevID = findRevisionID(jmxWiringA, cm);
    CompositeData jmxWiringCM = jmxWiringClosure.get(new Object[] { cm.getBundleId(), cmRevID });
    assertBundleWiring((BundleWiring) cm.adapt(BundleWiring.class), jmxWiringCM);
    Bundle sb = context().getBundle(0);
    int sbRevID = findRevisionID(jmxWiringA, sb);
    CompositeData jmxWiringSB = jmxWiringClosure.get(new Object[] { sb.getBundleId(), sbRevID });
    assertBundleWiring((BundleWiring) sb.adapt(BundleWiring.class), jmxWiringSB);
}

11. HelloworldSampleTest#testBundlesStart()

View license
@Test
public void testBundlesStart() throws Exception {
    /* Check that the HelloWorld Sample bundles are present an started */
    Bundle bapi = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.api");
    assertNotNull(bapi);
    failInBundleNotActiveInFiveSeconds(bapi);
    assertEquals(Bundle.ACTIVE, bapi.getState());
    Bundle bcli = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.client");
    assertNotNull(bcli);
    failInBundleNotActiveInFiveSeconds(bcli);
    Bundle bser = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.server");
    assertNotNull(bser);
    failInBundleNotActiveInFiveSeconds(bser);
}

12. ClientWeavingHookTest#testJAXPClientWantsAltImplementation1()

View license
// If there is an alternate implementation it should always be favoured over the JRE one
@Test
public void testJAXPClientWantsAltImplementation1() throws Exception {
    Bundle systembundle = mockSystemBundle();
    Bundle providerBundle = mockProviderBundle("impl3", 1);
    activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()");
    Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
    URL clsUrl = getClass().getResource("JaxpClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
    wh.weave(wc);
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] {});
    Class<?> result = (Class<?>) method.invoke(cls.newInstance());
    Assert.assertEquals("JAXP implementation from JRE", "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory", result.getName());
}

13. ClientWeavingHookTest#testJAXPClientWantsJREImplementation2()

View license
@Test
public void testJAXPClientWantsJREImplementation2() throws Exception {
    Bundle systembundle = mockSystemBundle();
    Bundle providerBundle = mockProviderBundle("impl3", 1);
    activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundleId=0");
    Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
    URL clsUrl = getClass().getResource("JaxpClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
    wh.weave(wc);
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] {});
    Class<?> result = (Class<?>) method.invoke(cls.newInstance());
    Assert.assertEquals("JAXP implementation from JRE", thisJVMsDBF, result.getName());
}

14. ClientWeavingHookTest#testJAXPClientWantsAltImplementation2()

View license
@Test
public void testJAXPClientWantsAltImplementation2() throws Exception {
    Bundle systembundle = mockSystemBundle();
    Bundle providerBundle = mockProviderBundle("impl3", 1);
    activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=impl3");
    Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
    URL clsUrl = getClass().getResource("JaxpClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
    wh.weave(wc);
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] {});
    Class<?> result = (Class<?>) method.invoke(cls.newInstance());
    Assert.assertEquals("JAXP implementation from alternative bundle", "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory", result.getName());
}

15. SubsystemDependency_4ATest#verifyNoUnexpectedBundlesProvisioned()

View license
/*
	 * Verify no new bundles are installed into the Root subsystem 
	 * (particularly bundles F and G)
     * 
	 */
@Test
public void verifyNoUnexpectedBundlesProvisioned() throws Exception {
    Bundle[] rootBundlesBefore = bundleContext.getBundles();
    Subsystem s = installSubsystemFromFile(APPLICATION_A);
    startSubsystem(s);
    Bundle[] rootBundlesAfter = bundleContext.getBundles();
    for (Bundle b : rootBundlesAfter) {
        assertTrue("Bundle F should not have been provisioned!", !b.getSymbolicName().equals(BUNDLE_F));
        assertTrue("Bundle G should not have been provisioned!", !b.getSymbolicName().equals(BUNDLE_G));
    }
    checkNoNewBundles("SubsystemDependency_4ATest", rootBundlesBefore, rootBundlesAfter);
    stopSubsystem(s);
    uninstallSubsystem(s);
}

16. BundleVisibilityTest#test1()

View license
/**
	 * Install a bundle into the same scope as this one. Both bundles should be
	 * able to see each other.
	 * @throws Exception
	 */
@Test
public void test1() throws Exception {
    Scope scope = getScope();
    assertTrue(scope.getBundles().contains(bundleContext.getBundle()));
    ScopeUpdate scopeUpdate = scope.newScopeUpdate();
    String location = getBundleLocation("tb-4.jar");
    assertNull(bundleContext.getBundle(location));
    URL url = new URL(location);
    InstallInfo installInfo = new InstallInfo(location, url.openStream());
    scopeUpdate.getBundlesToInstall().add(installInfo);
    scopeUpdate.commit();
    Bundle bundle = bundleContext.getBundle(location);
    assertTrue(scope.getBundles().contains(bundle));
    bundle.start();
    ServiceReference<BundleProvider> bundleProviderRef = bundleContext.getServiceReference(BundleProvider.class);
    BundleProvider bundleProvider = bundleContext.getService(bundleProviderRef);
    assertTrue(bundleProvider.getBundles().contains(bundleContext.getBundle()));
    assertTrue(Arrays.asList(bundleContext.getBundles()).contains(bundle));
    assertNotNull(bundleContext.getBundle(bundle.getBundleId()));
    assertNotNull(bundleProvider.getBundle(bundle.getBundleId()));
    bundleContext.ungetService(bundleProviderRef);
    bundle.uninstall();
}

17. GetScopeServiceTest#test2()

View license
/**
	 * The tb3 bundle should also be in and receive the root scope by default.
	 * @throws Exception
	 */
@Test
public void test2() throws Exception {
    Bundle bundle = installBundle("tb-3.jar");
    bundle.start();
    ServiceReference<ScopeProvider> scopeProviderRef = bundleContext.getServiceReference(ScopeProvider.class);
    ScopeProvider scopeProvider = bundleContext.getService(scopeProviderRef);
    Scope scope = scopeProvider.getScope();
    assertEquals(getScope(), scope);
    assertTrue(scope.getBundles().contains(bundle));
    bundleContext.ungetService(scopeProviderRef);
    bundle.uninstall();
}

18. GetScopeServiceTest#test4()

View license
/**
	 * A new scope is created as a child of the root scope and the tb3 bundle
	 * is added to it. The tb3 bundle should receive and be in the new scope.
	 * The bundle is added directly as opposed to via an InstallInfo.
	 * @throws Exception
	 */
@Test
public void test4() throws Exception {
    Scope scope = getScope();
    Bundle bundle = installBundle("tb-3.jar");
    ScopeUpdate scopeUpdate = scope.newScopeUpdate();
    scopeUpdate.getBundles().remove(bundle);
    ScopeUpdate child = scopeUpdate.newChild("tb3");
    scopeUpdate.getChildren().add(child);
    child.getBundles().add(bundle);
    addPackageImportPolicy("org.osgi.framework", child);
    addPackageImportPolicy("org.apache.aries.subsystem.scope", child);
    addPackageImportPolicy("org.apache.aries.subsystem.scope.itests", child);
    addServiceImportPolicy(Scope.class, child);
    addServiceExportPolicy(ScopeProvider.class, child);
    scopeUpdate.commit();
    bundle.start();
    ServiceReference<ScopeProvider> scopeProviderRef = bundleContext.getServiceReference(ScopeProvider.class);
    ScopeProvider scopeProvider = bundleContext.getService(scopeProviderRef);
    scope = scopeProvider.getScope();
    assertEquals("tb3", scope.getName());
    assertTrue(scope.getBundles().contains(bundle));
    bundleContext.ungetService(scopeProviderRef);
    bundle.uninstall();
}

19. PersistenceTest#test2()

Project: apache-aries
Source File: PersistenceTest.java
View license
/**
	 * Stopping and starting the Scope Admin bundle should cause it to pull
	 * from the persistent storage. If nothing changed after the original
	 * bundle start, the persisted root bundle should look exactly the same
	 * as before.
	 * 
	 * @throws Exception
	 */
@Test
public void test2() throws Exception {
    Scope scope = getScope();
    Bundle bundle = findBundle("org.apache.aries.subsystem.scope.impl");
    assertNotNull(bundle);
    bundle.stop();
    bundle.start();
    assertEquals(0, scope.getId());
    assertEquals("root", scope.getName());
    assertEquals(null, scope.getLocation());
    assertEquals(null, scope.getParent());
    assertEquals(0, scope.getChildren().size());
    assertCollectionEquals(Arrays.asList(bundleContext.getBundles()), scope.getBundles());
    assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_EXPORT).size());
    assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_IMPORT).size());
}

20. ServiceVisibilityTest#test1()

View license
/**
	 * Install a bundle registering a service into the same scope as this one. 
	 * This bundle should be able to see the service.
	 * @throws Exception
	 */
@Test
public void test1() throws Exception {
    assertTrue(getScope().getBundles().contains(bundleContext.getBundle()));
    ScopeUpdate scopeUpdate = getScope().newScopeUpdate();
    String location = getBundleLocation("tb-7.jar");
    assertNull(bundleContext.getBundle(location));
    URL url = new URL(location);
    InstallInfo installInfo = new InstallInfo(location, url.openStream());
    scopeUpdate.getBundlesToInstall().add(installInfo);
    scopeUpdate.commit();
    Bundle bundle = bundleContext.getBundle(location);
    assertNotNull(bundle);
    assertTrue(getScope().getBundles().contains(bundle));
    bundle.start();
    ServiceReference<Service> serviceRef = bundleContext.getServiceReference(Service.class);
    assertNotNull(serviceRef);
    Service service = bundleContext.getService(serviceRef);
    assertNotNull(service);
    bundleContext.ungetService(serviceRef);
    bundle.uninstall();
}

21. ServiceVisibilityTest#test2()

View license
/**
	 * Install a bundle registering a service into a different scope than this 
	 * one. This bundle should not be able to see the service.
	 * @throws Exception
	 */
@Test
public void test2() throws Exception {
    assertTrue(getScope().getBundles().contains(bundleContext.getBundle()));
    String location = getBundleLocation("tb-7.jar");
    assertNull(bundleContext.getBundle(location));
    URL url = new URL(location);
    InstallInfo installInfo = new InstallInfo(location, url.openStream());
    ScopeUpdate scopeUpdate = getScope().newScopeUpdate();
    ScopeUpdate child = scopeUpdate.newChild("tb7");
    scopeUpdate.getChildren().add(child);
    child.getBundlesToInstall().add(installInfo);
    addPackageImportPolicy("org.osgi.framework", child);
    addPackageImportPolicy("org.apache.aries.subsystem.scope.itests", child);
    scopeUpdate.commit();
    Bundle bundle = bundleContext.getBundle(location);
    assertNotNull(bundle);
    assertTrue(child.getScope().getBundles().contains(bundle));
    bundle.start();
    ServiceReference<Service> serviceRef = bundleContext.getServiceReference(Service.class);
    assertNull(serviceRef);
    bundle.uninstall();
}

22. BundleWiringStateMBeanTest#testCurrentWiringClosure()

View license
@Test
public void testCurrentWiringClosure() throws Exception {
    TabularData jmxWiringClosure = brsMBean.getCurrentWiringClosure(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
    CompositeData jmxWiringA = jmxWiringClosure.get(new Object[] { bundleA.getBundleId(), 0 });
    assertBundleWiring((BundleWiring) bundleA.adapt(BundleWiring.class), jmxWiringA);
    Bundle b = context().getBundleByName("org.apache.aries.jmx.test.bundleb");
    int bRevID = findRevisionID(jmxWiringA, b);
    CompositeData jmxWiringB = jmxWiringClosure.get(new Object[] { b.getBundleId(), bRevID });
    assertBundleWiring((BundleWiring) b.adapt(BundleWiring.class), jmxWiringB);
    Bundle cm = context().getBundleByName("org.apache.felix.configadmin");
    int cmRevID = findRevisionID(jmxWiringA, cm);
    CompositeData jmxWiringCM = jmxWiringClosure.get(new Object[] { cm.getBundleId(), cmRevID });
    assertBundleWiring((BundleWiring) cm.adapt(BundleWiring.class), jmxWiringCM);
    Bundle sb = context().getBundle(0);
    int sbRevID = findRevisionID(jmxWiringA, sb);
    CompositeData jmxWiringSB = jmxWiringClosure.get(new Object[] { sb.getBundleId(), sbRevID });
    assertBundleWiring((BundleWiring) sb.adapt(BundleWiring.class), jmxWiringSB);
}

23. BundleWiringStateMBeanTest#testRevisionsWiringClosure()

View license
@Test
public void testRevisionsWiringClosure() throws Exception {
    TabularData jmxWiringClosure = brsMBean.getRevisionsWiringClosure(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
    CompositeData jmxWiringA = jmxWiringClosure.get(new Object[] { bundleA.getBundleId(), 0 });
    assertBundleWiring((BundleWiring) bundleA.adapt(BundleWiring.class), jmxWiringA);
    Bundle b = context().getBundleByName("org.apache.aries.jmx.test.bundleb");
    int bRevID = findRevisionID(jmxWiringA, b);
    CompositeData jmxWiringB = jmxWiringClosure.get(new Object[] { b.getBundleId(), bRevID });
    assertBundleWiring((BundleWiring) b.adapt(BundleWiring.class), jmxWiringB);
    Bundle cm = context().getBundleByName("org.apache.felix.configadmin");
    int cmRevID = findRevisionID(jmxWiringA, cm);
    CompositeData jmxWiringCM = jmxWiringClosure.get(new Object[] { cm.getBundleId(), cmRevID });
    assertBundleWiring((BundleWiring) cm.adapt(BundleWiring.class), jmxWiringCM);
    Bundle sb = context().getBundle(0);
    int sbRevID = findRevisionID(jmxWiringA, sb);
    CompositeData jmxWiringSB = jmxWiringClosure.get(new Object[] { sb.getBundleId(), sbRevID });
    assertBundleWiring((BundleWiring) sb.adapt(BundleWiring.class), jmxWiringSB);
}

24. HelloworldSampleTest#testBundlesStart()

Project: aries
Source File: HelloworldSampleTest.java
View license
@Test
public void testBundlesStart() throws Exception {
    /* Check that the HelloWorld Sample bundles are present an started */
    Bundle bapi = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.api");
    assertNotNull(bapi);
    failInBundleNotActiveInFiveSeconds(bapi);
    assertEquals(Bundle.ACTIVE, bapi.getState());
    Bundle bcli = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.client");
    assertNotNull(bcli);
    failInBundleNotActiveInFiveSeconds(bcli);
    Bundle bser = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.server");
    assertNotNull(bser);
    failInBundleNotActiveInFiveSeconds(bser);
}

25. ClientWeavingHookTest#testJAXPClientWantsAltImplementation1()

Project: aries
Source File: ClientWeavingHookTest.java
View license
// If there is an alternate implementation it should always be favoured over the JRE one
@Test
public void testJAXPClientWantsAltImplementation1() throws Exception {
    Bundle systembundle = mockSystemBundle();
    Bundle providerBundle = mockProviderBundle("impl3", 1);
    activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()");
    Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
    URL clsUrl = getClass().getResource("JaxpClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
    wh.weave(wc);
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] {});
    Class<?> result = (Class<?>) method.invoke(cls.newInstance());
    Assert.assertEquals("JAXP implementation from JRE", "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory", result.getName());
}

26. ClientWeavingHookTest#testJAXPClientWantsJREImplementation2()

Project: aries
Source File: ClientWeavingHookTest.java
View license
@Test
public void testJAXPClientWantsJREImplementation2() throws Exception {
    Bundle systembundle = mockSystemBundle();
    Bundle providerBundle = mockProviderBundle("impl3", 1);
    activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundleId=0");
    Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
    URL clsUrl = getClass().getResource("JaxpClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
    wh.weave(wc);
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] {});
    Class<?> result = (Class<?>) method.invoke(cls.newInstance());
    Assert.assertEquals("JAXP implementation from JRE", thisJVMsDBF, result.getName());
}

27. ClientWeavingHookTest#testJAXPClientWantsAltImplementation2()

Project: aries
Source File: ClientWeavingHookTest.java
View license
@Test
public void testJAXPClientWantsAltImplementation2() throws Exception {
    Bundle systembundle = mockSystemBundle();
    Bundle providerBundle = mockProviderBundle("impl3", 1);
    activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=impl3");
    Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
    URL clsUrl = getClass().getResource("JaxpClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
    wh.weave(wc);
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] {});
    Class<?> result = (Class<?>) method.invoke(cls.newInstance());
    Assert.assertEquals("JAXP implementation from alternative bundle", "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory", result.getName());
}

28. SubsystemDependency_4ATest#verifyNoUnexpectedBundlesProvisioned()

View license
/*
	 * Verify no new bundles are installed into the Root subsystem 
	 * (particularly bundles F and G)
     * 
	 */
@Test
public void verifyNoUnexpectedBundlesProvisioned() throws Exception {
    Bundle[] rootBundlesBefore = bundleContext.getBundles();
    Subsystem s = installSubsystemFromFile(APPLICATION_A);
    startSubsystem(s);
    Bundle[] rootBundlesAfter = bundleContext.getBundles();
    for (Bundle b : rootBundlesAfter) {
        assertTrue("Bundle F should not have been provisioned!", !b.getSymbolicName().equals(BUNDLE_F));
        assertTrue("Bundle G should not have been provisioned!", !b.getSymbolicName().equals(BUNDLE_G));
    }
    checkNoNewBundles("SubsystemDependency_4ATest", rootBundlesBefore, rootBundlesAfter);
    stopSubsystem(s);
    uninstallSubsystem(s);
}

29. BundleVisibilityTest#test1()

Project: aries
Source File: BundleVisibilityTest.java
View license
/**
	 * Install a bundle into the same scope as this one. Both bundles should be
	 * able to see each other.
	 * @throws Exception
	 */
@Test
public void test1() throws Exception {
    Scope scope = getScope();
    assertTrue(scope.getBundles().contains(bundleContext.getBundle()));
    ScopeUpdate scopeUpdate = scope.newScopeUpdate();
    String location = getBundleLocation("tb-4.jar");
    assertNull(bundleContext.getBundle(location));
    URL url = new URL(location);
    InstallInfo installInfo = new InstallInfo(location, url.openStream());
    scopeUpdate.getBundlesToInstall().add(installInfo);
    scopeUpdate.commit();
    Bundle bundle = bundleContext.getBundle(location);
    assertTrue(scope.getBundles().contains(bundle));
    bundle.start();
    ServiceReference<BundleProvider> bundleProviderRef = bundleContext.getServiceReference(BundleProvider.class);
    BundleProvider bundleProvider = bundleContext.getService(bundleProviderRef);
    assertTrue(bundleProvider.getBundles().contains(bundleContext.getBundle()));
    assertTrue(Arrays.asList(bundleContext.getBundles()).contains(bundle));
    assertNotNull(bundleContext.getBundle(bundle.getBundleId()));
    assertNotNull(bundleProvider.getBundle(bundle.getBundleId()));
    bundleContext.ungetService(bundleProviderRef);
    bundle.uninstall();
}

30. GetScopeServiceTest#test2()

Project: aries
Source File: GetScopeServiceTest.java
View license
/**
	 * The tb3 bundle should also be in and receive the root scope by default.
	 * @throws Exception
	 */
@Test
public void test2() throws Exception {
    Bundle bundle = installBundle("tb-3.jar");
    bundle.start();
    ServiceReference<ScopeProvider> scopeProviderRef = bundleContext.getServiceReference(ScopeProvider.class);
    ScopeProvider scopeProvider = bundleContext.getService(scopeProviderRef);
    Scope scope = scopeProvider.getScope();
    assertEquals(getScope(), scope);
    assertTrue(scope.getBundles().contains(bundle));
    bundleContext.ungetService(scopeProviderRef);
    bundle.uninstall();
}

31. GetScopeServiceTest#test4()

Project: aries
Source File: GetScopeServiceTest.java
View license
/**
	 * A new scope is created as a child of the root scope and the tb3 bundle
	 * is added to it. The tb3 bundle should receive and be in the new scope.
	 * The bundle is added directly as opposed to via an InstallInfo.
	 * @throws Exception
	 */
@Test
public void test4() throws Exception {
    Scope scope = getScope();
    Bundle bundle = installBundle("tb-3.jar");
    ScopeUpdate scopeUpdate = scope.newScopeUpdate();
    scopeUpdate.getBundles().remove(bundle);
    ScopeUpdate child = scopeUpdate.newChild("tb3");
    scopeUpdate.getChildren().add(child);
    child.getBundles().add(bundle);
    addPackageImportPolicy("org.osgi.framework", child);
    addPackageImportPolicy("org.apache.aries.subsystem.scope", child);
    addPackageImportPolicy("org.apache.aries.subsystem.scope.itests", child);
    addServiceImportPolicy(Scope.class, child);
    addServiceExportPolicy(ScopeProvider.class, child);
    scopeUpdate.commit();
    bundle.start();
    ServiceReference<ScopeProvider> scopeProviderRef = bundleContext.getServiceReference(ScopeProvider.class);
    ScopeProvider scopeProvider = bundleContext.getService(scopeProviderRef);
    scope = scopeProvider.getScope();
    assertEquals("tb3", scope.getName());
    assertTrue(scope.getBundles().contains(bundle));
    bundleContext.ungetService(scopeProviderRef);
    bundle.uninstall();
}

32. PersistenceTest#test2()

Project: aries
Source File: PersistenceTest.java
View license
/**
	 * Stopping and starting the Scope Admin bundle should cause it to pull
	 * from the persistent storage. If nothing changed after the original
	 * bundle start, the persisted root bundle should look exactly the same
	 * as before.
	 * 
	 * @throws Exception
	 */
@Test
public void test2() throws Exception {
    Scope scope = getScope();
    Bundle bundle = findBundle("org.apache.aries.subsystem.scope.impl");
    assertNotNull(bundle);
    bundle.stop();
    bundle.start();
    assertEquals(0, scope.getId());
    assertEquals("root", scope.getName());
    assertEquals(null, scope.getLocation());
    assertEquals(null, scope.getParent());
    assertEquals(0, scope.getChildren().size());
    assertCollectionEquals(Arrays.asList(bundleContext.getBundles()), scope.getBundles());
    assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_EXPORT).size());
    assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_IMPORT).size());
}

33. ServiceVisibilityTest#test1()

Project: aries
Source File: ServiceVisibilityTest.java
View license
/**
	 * Install a bundle registering a service into the same scope as this one. 
	 * This bundle should be able to see the service.
	 * @throws Exception
	 */
@Test
public void test1() throws Exception {
    assertTrue(getScope().getBundles().contains(bundleContext.getBundle()));
    ScopeUpdate scopeUpdate = getScope().newScopeUpdate();
    String location = getBundleLocation("tb-7.jar");
    assertNull(bundleContext.getBundle(location));
    URL url = new URL(location);
    InstallInfo installInfo = new InstallInfo(location, url.openStream());
    scopeUpdate.getBundlesToInstall().add(installInfo);
    scopeUpdate.commit();
    Bundle bundle = bundleContext.getBundle(location);
    assertNotNull(bundle);
    assertTrue(getScope().getBundles().contains(bundle));
    bundle.start();
    ServiceReference<Service> serviceRef = bundleContext.getServiceReference(Service.class);
    assertNotNull(serviceRef);
    Service service = bundleContext.getService(serviceRef);
    assertNotNull(service);
    bundleContext.ungetService(serviceRef);
    bundle.uninstall();
}

34. ServiceVisibilityTest#test2()

Project: aries
Source File: ServiceVisibilityTest.java
View license
/**
	 * Install a bundle registering a service into a different scope than this 
	 * one. This bundle should not be able to see the service.
	 * @throws Exception
	 */
@Test
public void test2() throws Exception {
    assertTrue(getScope().getBundles().contains(bundleContext.getBundle()));
    String location = getBundleLocation("tb-7.jar");
    assertNull(bundleContext.getBundle(location));
    URL url = new URL(location);
    InstallInfo installInfo = new InstallInfo(location, url.openStream());
    ScopeUpdate scopeUpdate = getScope().newScopeUpdate();
    ScopeUpdate child = scopeUpdate.newChild("tb7");
    scopeUpdate.getChildren().add(child);
    child.getBundlesToInstall().add(installInfo);
    addPackageImportPolicy("org.osgi.framework", child);
    addPackageImportPolicy("org.apache.aries.subsystem.scope.itests", child);
    scopeUpdate.commit();
    Bundle bundle = bundleContext.getBundle(location);
    assertNotNull(bundle);
    assertTrue(child.getScope().getBundles().contains(bundle));
    bundle.start();
    ServiceReference<Service> serviceRef = bundleContext.getServiceReference(Service.class);
    assertNull(serviceRef);
    bundle.uninstall();
}

35. BundleUtils#findBundle()

Project: bndtools
Source File: BundleUtils.java
View license
public static final Bundle findBundle(BundleContext context, String symbolicName, VersionRange range) {
    if (context == null)
        return null;
    Bundle matched = null;
    Version matchedVersion = null;
    Bundle[] bundles = context.getBundles();
    for (Bundle bundle : bundles) {
        try {
            String name = bundle.getSymbolicName();
            String versionStr = bundle.getHeaders().get(Constants.BUNDLE_VERSION);
            Version version = versionStr != null ? new Version(versionStr) : new Version();
            if (range == null || range.includes(version)) {
                if (symbolicName.equals(name)) {
                    if (matched == null || version.compareTo(matchedVersion) > 0) {
                        matched = bundle;
                        matchedVersion = version;
                    }
                }
            }
        } catch (Exception e) {
        }
    }
    return matched;
}

36. QuiesceBlueprintTest#getBundle()

View license
protected Bundle getBundle(String bundleSymbolicName, String version) {
    Bundle result = null;
    for (Bundle b : bundleContext.getBundles()) {
        if (b.getSymbolicName().equals(bundleSymbolicName)) {
            if (version == null || b.getVersion().equals(Version.parseVersion(version))) {
                result = b;
                break;
            }
        }
    }
    return result;
}

37. SpringExtenderTest#testSpringBundle()

View license
@Test
public void testSpringBundle() throws Exception {
    try {
        context().getService(BeanCItf.class, 1);
        fail("The service should not be registered");
    } catch (RuntimeException e) {
    }
    Bundle bundles = context().getBundleByName("org.apache.aries.blueprint.testbundlee");
    assertNotNull(bundles);
    bundles.start();
    BlueprintContainer container = startBundleBlueprint("org.apache.aries.blueprint.testbundlee");
    assertNotNull(container);
    BeanCItf beanC1 = context().getService(BeanCItf.class, "(name=BeanC-1)");
    assertEquals(1, beanC1.getInitialized());
    BeanCItf beanC2 = context().getService(BeanCItf.class, "(name=BeanC-2)");
    assertEquals(1, beanC2.getInitialized());
}

38. SpringTest#testSpringBundle()

Project: apache-aries
Source File: SpringTest.java
View license
@Test
public void testSpringBundle() throws Exception {
    Bundle bundles = context().getBundleByName("org.apache.aries.blueprint.testbundles");
    assertNotNull(bundles);
    bundles.start();
    BlueprintContainer container = startBundleBlueprint("org.apache.aries.blueprint.testbundles");
    List list = (List) container.getComponentInstance("springList");
    System.out.println(list);
    BeanCItf beanC = (BeanCItf) list.get(4);
    assertEquals(1, beanC.getInitialized());
    try {
        beanC.doSomething();
        fail("Should have thrown an exception because the transaction manager is not defined");
    } catch (NoSuchBeanDefinitionException e) {
    }
}

39. TestReferences#testReferencesCallableInDestroy()

Project: apache-aries
Source File: TestReferences.java
View license
@Test
public void testReferencesCallableInDestroy() throws Exception {
    bundleContext.registerService(Runnable.class.getName(), new Thread(), null);
    BlueprintContainer blueprintContainer = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
    assertNotNull(blueprintContainer);
    DestroyTest dt = (DestroyTest) blueprintContainer.getComponentInstance("destroyCallingReference");
    Bundle b = findBundle("org.apache.aries.blueprint.sample");
    assertNotNull(b);
    b.stop();
    assertTrue("The destroy method was called", dt.waitForDestruction(1000));
    Exception e = dt.getDestroyFailure();
    if (e != null)
        throw e;
}

40. PackageStateTest#testGetExportingBundles()

Project: apache-aries
Source File: PackageStateTest.java
View license
@Test
public void testGetExportingBundles() throws IOException {
    ExportedPackage exported = Mockito.mock(ExportedPackage.class);
    Bundle bundle = Mockito.mock(Bundle.class);
    Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
    Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(5));
    ExportedPackage exported2 = Mockito.mock(ExportedPackage.class);
    Bundle bundle2 = Mockito.mock(Bundle.class);
    Mockito.when(exported2.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported2.getExportingBundle()).thenReturn(bundle2);
    Mockito.when(bundle2.getBundleId()).thenReturn(Long.valueOf(6));
    Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[] { exported, exported2 });
    long[] ids = mbean.getExportingBundles("test", "1.0.0");
    Assert.assertNotNull(ids);
    Assert.assertArrayEquals(new long[] { 5, 6 }, ids);
}

41. PackageStateTest#testGetImportingBundles()

Project: apache-aries
Source File: PackageStateTest.java
View license
@Test
public void testGetImportingBundles() throws IOException {
    ExportedPackage exported = Mockito.mock(ExportedPackage.class);
    Bundle bundle = Mockito.mock(Bundle.class);
    Bundle exportingBundle = Mockito.mock(Bundle.class);
    Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported.getExportingBundle()).thenReturn(exportingBundle);
    Mockito.when(exportingBundle.getBundleId()).thenReturn(Long.valueOf(2));
    Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[] { bundle });
    Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
    Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[] { exported });
    long[] ids = mbean.getImportingBundles("test", "1.0.0", 2);
    Assert.assertArrayEquals(new long[] { 4 }, ids);
}

42. PackageStateTest#testListPackages()

Project: apache-aries
Source File: PackageStateTest.java
View license
@Test
public void testListPackages() throws IOException {
    Bundle bundle = Mockito.mock(Bundle.class);
    Bundle impBundle = Mockito.mock(Bundle.class);
    Mockito.when(context.getBundles()).thenReturn(new Bundle[] { bundle });
    ExportedPackage exported = Mockito.mock(ExportedPackage.class);
    Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[] { impBundle });
    Mockito.when(exported.getName()).thenReturn("test");
    Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
    Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
    Mockito.when(impBundle.getBundleId()).thenReturn(Long.valueOf(5));
    Mockito.when(admin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[] { exported });
    TabularData table = mbean.listPackages();
    Assert.assertEquals(PackageStateMBean.PACKAGES_TYPE, table.getTabularType());
    Collection values = table.values();
    Assert.assertEquals(1, values.size());
    CompositeData data = (CompositeData) values.iterator().next();
    Long[] exportingBundles = (Long[]) data.get(PackageStateMBean.EXPORTING_BUNDLES);
    Assert.assertArrayEquals(new Long[] { Long.valueOf(4) }, exportingBundles);
    String name = (String) data.get(PackageStateMBean.NAME);
    Assert.assertEquals("test", name);
    String version = (String) data.get(PackageStateMBean.VERSION);
    Assert.assertEquals("1.0.0", version);
}

43. FrameworkUtilsTest#testGetBundleIds()

View license
@Test
public void testGetBundleIds() throws Exception {
    assertEquals(0, getBundleIds((Bundle[]) null).length);
    assertEquals(0, getBundleIds(new Bundle[0]).length);
    Bundle b1 = mock(Bundle.class);
    when(b1.getBundleId()).thenReturn(new Long(47));
    Bundle b2 = mock(Bundle.class);
    when(b2.getBundleId()).thenReturn(new Long(23));
    assertArrayEquals(new long[] { 47, 23 }, getBundleIds(new Bundle[] { b1, b2 }));
}

44. FrameworkUtilsTest#testIsBundleRequiredByOthers()

View license
@Test
public void testIsBundleRequiredByOthers() throws Exception {
    Bundle bundle = mock(Bundle.class);
    when(bundle.getSymbolicName()).thenReturn("org.apache.testb");
    RequiredBundle reqBundle = mock(RequiredBundle.class);
    when(reqBundle.getBundle()).thenReturn(bundle);
    when(reqBundle.getRequiringBundles()).thenReturn(new Bundle[0]);
    PackageAdmin admin = mock(PackageAdmin.class);
    when(admin.getRequiredBundles("org.apache.testb")).thenReturn(new RequiredBundle[] { reqBundle });
    assertFalse(isBundleRequiredByOthers(bundle, admin));
    Bundle user = mock(Bundle.class);
    when(reqBundle.getRequiringBundles()).thenReturn(new Bundle[] { user });
    assertTrue(isBundleRequiredByOthers(bundle, admin));
}

45. JndiUrlIntegrationTest#testBlueprintCompNamespaceWorks()

View license
/**
   * This test exercises the blueprint:comp/ jndi namespace by driving
   * a Servlet which then looks up some blueprint components from its own
   * bundle, including a reference which it uses to call a service from a 
   * second bundle.  
   * @throws Exception
   */
@Test
public void testBlueprintCompNamespaceWorks() throws Exception {
    Bundle bBiz = context().getBundleByName("org.apache.aries.jndi.url.itest.biz");
    assertNotNull(bBiz);
    Bundle bweb = context().getBundleByName("org.apache.aries.jndi.url.itest.web");
    assertNotNull(bweb);
    context().getBundleByName("org.ops4j.pax.web.pax-web-extender-war").start();
    printBundleStatus("Before making web request");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException ix) {
    }
    System.out.println("In test and trying to get connection....");
    String response = getTestServletResponse();
    System.out.println("Got response `" + response + "`");
    assertEquals("ITest servlet response wrong", "Mark.2.0.three", response);
}

46. ProviderBundleTrackerCustomizerGenericCapabilityTest#testNoServiceRegistration()

View license
@Test
public void testNoServiceRegistration() throws Exception {
    Bundle mediatorBundle = EasyMock.createMock(Bundle.class);
    EasyMock.expect(mediatorBundle.getBundleId()).andReturn(42l).anyTimes();
    EasyMock.replay(mediatorBundle);
    BaseActivator activator = new BaseActivator() {

        @Override
        public void start(BundleContext context) throws Exception {
        }
    };
    ProviderBundleTrackerCustomizer customizer = new ProviderBundleTrackerCustomizer(activator, mediatorBundle);
    ServiceRegistration sreg = EasyMock.createMock(ServiceRegistration.class);
    EasyMock.replay(sreg);
    BundleContext implBC = mockSPIBundleContext(sreg);
    Bundle implBundle = mockSPIBundle(implBC, SpiFlyConstants.PROVIDER_REQUIREMENT);
    List<ServiceRegistration> registrations = customizer.addingBundle(implBundle, null);
    assertEquals(0, registrations.size());
    Collection<Bundle> bundles = activator.findProviderBundles("org.apache.aries.mytest.MySPI");
    assertEquals(1, bundles.size());
    assertSame(implBundle, bundles.iterator().next());
}

47. ClientWeavingHookTest#testJAXPClientWantsJREImplementation1()

View license
@Test
public void testJAXPClientWantsJREImplementation1() throws Exception {
    Bundle systembundle = mockSystemBundle();
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()");
    Bundle consumerBundle = mockConsumerBundle(headers, systembundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, systembundle).getBundleContext(), activator);
    URL clsUrl = getClass().getResource("JaxpClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
    wh.weave(wc);
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] {});
    Class<?> result = (Class<?>) method.invoke(cls.newInstance());
    Assert.assertEquals("JAXP implementation from JRE", thisJVMsDBF, result.getName());
}

48. RegionContextBundleHelper#installRegionContextBundle()

View license
public static void installRegionContextBundle(final BasicSubsystem subsystem, Coordination coordination) throws Exception {
    String symbolicName = SYMBOLICNAME_PREFIX + subsystem.getSubsystemId();
    String location = subsystem.getLocation() + '/' + subsystem.getSubsystemId();
    Bundle b = subsystem.getRegion().getBundle(symbolicName, VERSION);
    if (b == null) {
        b = subsystem.getRegion().installBundleAtLocation(location, createRegionContextBundle(symbolicName));
        // The start level of all managed bundles, including the region
        // context bundle, should be 1.
        b.adapt(BundleStartLevel.class).setStartLevel(1);
    }
    ResourceInstaller.newInstance(coordination, b.adapt(BundleRevision.class), subsystem).install();
    // The region context bundle must be started persistently.
    b.start();
    subsystem.setRegionContextBundle(b);
}

49. SubsystemDependencyTestBase#checkNoNewBundles()

View license
/**
	 * Check that no new bundles have been provisioned by [x]
	 * @param failText where the failure occurred
	 * @param rootBundlesBefore Bundles before [x]
	 * @param rootBundlesAfter Bundles after [x]
	 */
protected void checkNoNewBundles(String failText, Bundle[] rootBundlesBefore, Bundle[] rootBundlesAfter) {
    Set<String> bundlesBefore = new HashSet<String>();
    for (Bundle b : rootBundlesBefore) {
        bundlesBefore.add(b.getSymbolicName() + "_" + b.getVersion().toString());
    }
    Set<String> bundlesAfter = new HashSet<String>();
    for (Bundle b : rootBundlesAfter) {
        bundlesAfter.add(b.getSymbolicName() + "_" + b.getVersion().toString());
    }
    boolean unchanged = bundlesBefore.containsAll(bundlesAfter) && bundlesAfter.containsAll(bundlesBefore);
    if (!unchanged) {
        bundlesAfter.removeAll(bundlesBefore);
        fail("Extra bundles provisioned in " + failText + " : " + bundlesAfter);
    }
}

50. SubsystemDependency_4BTest#verifyBundlesAandBinstalledIntoRootRegion()

View license
// - Verify that bundles A and B got installed into the Root Subsystem
@Test
public void verifyBundlesAandBinstalledIntoRootRegion() throws Exception {
    System.out.println("Into verifyBundlesAandBinstalledIntoRootRegion");
    Subsystem s = installSubsystemFromFile(APPLICATION_B);
    startSubsystem(s);
    Bundle[] bundles = bundleContext.getBundles();
    Collection<String> bundleNames = new ArrayList<String>();
    for (Bundle b : bundles) {
        bundleNames.add(b.getSymbolicName());
    }
    assertTrue("Bundle A should have been provisioned to the root region", bundleNames.contains(BUNDLE_A));
    assertTrue("Bundle B should have been provisioned to the root region", bundleNames.contains(BUNDLE_B));
    stopSubsystem(s);
}

51. Aries1435Test#testDynamicImport()

Project: apache-aries
Source File: Aries1435Test.java
View license
private void testDynamicImport(Subsystem subsystem, String clazz) throws Exception {
    assertConstituent(subsystem, BUNDLE_A);
    Bundle bundleA = getConstituentAsBundle(subsystem, BUNDLE_A, null, null);
    bundleA.loadClass("a.A");
    assertTrue("Weaving hook not called", weavingHookCalled.get());
    try {
        bundleA.loadClass(clazz);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Dynamic import not visible");
    }
}

52. UnmanagedBundleTest#testInstallWhileImplBundleStopped()

View license
/*
	 * Test that an unmanaged bundle is detected as a constituent in the root
	 * subsystem when the subsystems core bundle is stopped. This ensures that
	 * persistence isn't interfering with detection.
	 */
@Test
public void testInstallWhileImplBundleStopped() throws Exception {
    Bundle core = getSubsystemCoreBundle();
    core.stop();
    try {
        Bundle a = bundleContext.installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
        try {
            core.start();
            assertConstituent(getRootSubsystem(), BUNDLE_A);
        } finally {
            uninstallSilently(a);
        }
    } finally {
        core.start();
    }
}

53. UnmanagedBundleTest#testInstallWhileImplBundleUninstalled()

View license
/*
	 * Test that an unmanaged bundle is detected as a constituent in the root
	 * subsystem when the subsystems core bundle is uninstalled.
	 */
@Test
public void testInstallWhileImplBundleUninstalled() throws Exception {
    Bundle core = getSubsystemCoreBundle();
    core.uninstall();
    try {
        Bundle a = bundleContext.installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
        try {
            core = bundleContext.installBundle(normalizeBundleLocation(core));
            core.start();
            assertConstituent(getRootSubsystem(), BUNDLE_A);
        } finally {
            uninstallSilently(a);
        }
    } finally {
        if (core.getState() == Bundle.UNINSTALLED) {
            core = bundleContext.installBundle(normalizeBundleLocation(core));
            core.start();
        }
    }
}

54. QuiesceBlueprintTest#getBundle()

Project: aries
Source File: QuiesceBlueprintTest.java
View license
protected Bundle getBundle(String bundleSymbolicName, String version) {
    Bundle result = null;
    for (Bundle b : bundleContext.getBundles()) {
        if (b.getSymbolicName().equals(bundleSymbolicName)) {
            if (version == null || b.getVersion().equals(Version.parseVersion(version))) {
                result = b;
                break;
            }
        }
    }
    return result;
}

55. SpringExtenderTest#testSpringBundle()

Project: aries
Source File: SpringExtenderTest.java
View license
@Test
public void testSpringBundle() throws Exception {
    try {
        context().getService(BeanCItf.class, 1);
        fail("The service should not be registered");
    } catch (RuntimeException e) {
    }
    Bundle bundles = context().getBundleByName("org.apache.aries.blueprint.testbundlee");
    assertNotNull(bundles);
    bundles.start();
    BlueprintContainer container = startBundleBlueprint("org.apache.aries.blueprint.testbundlee");
    assertNotNull(container);
    BeanCItf beanC1 = context().getService(BeanCItf.class, "(name=BeanC-1)");
    assertEquals(1, beanC1.getInitialized());
    BeanCItf beanC2 = context().getService(BeanCItf.class, "(name=BeanC-2)");
    assertEquals(1, beanC2.getInitialized());
}

56. SpringTest#testSpringBundle()

Project: aries
Source File: SpringTest.java
View license
@Test
public void testSpringBundle() throws Exception {
    Bundle bundles = context().getBundleByName("org.apache.aries.blueprint.testbundles");
    assertNotNull(bundles);
    bundles.start();
    BlueprintContainer container = startBundleBlueprint("org.apache.aries.blueprint.testbundles");
    List list = (List) container.getComponentInstance("springList");
    System.out.println(list);
    BeanCItf beanC = (BeanCItf) list.get(4);
    assertEquals(1, beanC.getInitialized());
    try {
        beanC.doSomething();
        fail("Should have thrown an exception because the transaction manager is not defined");
    } catch (NoSuchBeanDefinitionException e) {
    }
}

57. TestReferences#testReferencesCallableInDestroy()

Project: aries
Source File: TestReferences.java
View license
@Test
public void testReferencesCallableInDestroy() throws Exception {
    bundleContext.registerService(Runnable.class.getName(), new Thread(), null);
    BlueprintContainer blueprintContainer = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
    assertNotNull(blueprintContainer);
    DestroyTest dt = (DestroyTest) blueprintContainer.getComponentInstance("destroyCallingReference");
    Bundle b = findBundle("org.apache.aries.blueprint.sample");
    assertNotNull(b);
    b.stop();
    assertTrue("The destroy method was called", dt.waitForDestruction(1000));
    Exception e = dt.getDestroyFailure();
    if (e != null)
        throw e;
}

58. PackageStateTest#testGetExportingBundles()

Project: aries
Source File: PackageStateTest.java
View license
@Test
public void testGetExportingBundles() throws IOException {
    ExportedPackage exported = Mockito.mock(ExportedPackage.class);
    Bundle bundle = Mockito.mock(Bundle.class);
    Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
    Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(5));
    ExportedPackage exported2 = Mockito.mock(ExportedPackage.class);
    Bundle bundle2 = Mockito.mock(Bundle.class);
    Mockito.when(exported2.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported2.getExportingBundle()).thenReturn(bundle2);
    Mockito.when(bundle2.getBundleId()).thenReturn(Long.valueOf(6));
    Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[] { exported, exported2 });
    long[] ids = mbean.getExportingBundles("test", "1.0.0");
    Assert.assertNotNull(ids);
    Assert.assertArrayEquals(new long[] { 5, 6 }, ids);
}

59. PackageStateTest#testGetImportingBundles()

Project: aries
Source File: PackageStateTest.java
View license
@Test
public void testGetImportingBundles() throws IOException {
    ExportedPackage exported = Mockito.mock(ExportedPackage.class);
    Bundle bundle = Mockito.mock(Bundle.class);
    Bundle exportingBundle = Mockito.mock(Bundle.class);
    Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported.getExportingBundle()).thenReturn(exportingBundle);
    Mockito.when(exportingBundle.getBundleId()).thenReturn(Long.valueOf(2));
    Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[] { bundle });
    Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
    Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[] { exported });
    long[] ids = mbean.getImportingBundles("test", "1.0.0", 2);
    Assert.assertArrayEquals(new long[] { 4 }, ids);
}

60. PackageStateTest#testListPackages()

Project: aries
Source File: PackageStateTest.java
View license
@Test
public void testListPackages() throws IOException {
    Bundle bundle = Mockito.mock(Bundle.class);
    Bundle impBundle = Mockito.mock(Bundle.class);
    Mockito.when(context.getBundles()).thenReturn(new Bundle[] { bundle });
    ExportedPackage exported = Mockito.mock(ExportedPackage.class);
    Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[] { impBundle });
    Mockito.when(exported.getName()).thenReturn("test");
    Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
    Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
    Mockito.when(impBundle.getBundleId()).thenReturn(Long.valueOf(5));
    Mockito.when(admin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[] { exported });
    TabularData table = mbean.listPackages();
    Assert.assertEquals(PackageStateMBean.PACKAGES_TYPE, table.getTabularType());
    Collection values = table.values();
    Assert.assertEquals(1, values.size());
    CompositeData data = (CompositeData) values.iterator().next();
    Long[] exportingBundles = (Long[]) data.get(PackageStateMBean.EXPORTING_BUNDLES);
    Assert.assertArrayEquals(new Long[] { Long.valueOf(4) }, exportingBundles);
    String name = (String) data.get(PackageStateMBean.NAME);
    Assert.assertEquals("test", name);
    String version = (String) data.get(PackageStateMBean.VERSION);
    Assert.assertEquals("1.0.0", version);
}

61. FrameworkUtilsTest#testGetBundleIds()

Project: aries
Source File: FrameworkUtilsTest.java
View license
@Test
public void testGetBundleIds() throws Exception {
    assertEquals(0, getBundleIds((Bundle[]) null).length);
    assertEquals(0, getBundleIds(new Bundle[0]).length);
    Bundle b1 = mock(Bundle.class);
    when(b1.getBundleId()).thenReturn(new Long(47));
    Bundle b2 = mock(Bundle.class);
    when(b2.getBundleId()).thenReturn(new Long(23));
    assertArrayEquals(new long[] { 47, 23 }, getBundleIds(new Bundle[] { b1, b2 }));
}

62. FrameworkUtilsTest#testIsBundleRequiredByOthers()

Project: aries
Source File: FrameworkUtilsTest.java
View license
@Test
public void testIsBundleRequiredByOthers() throws Exception {
    Bundle bundle = mock(Bundle.class);
    when(bundle.getSymbolicName()).thenReturn("org.apache.testb");
    RequiredBundle reqBundle = mock(RequiredBundle.class);
    when(reqBundle.getBundle()).thenReturn(bundle);
    when(reqBundle.getRequiringBundles()).thenReturn(new Bundle[0]);
    PackageAdmin admin = mock(PackageAdmin.class);
    when(admin.getRequiredBundles("org.apache.testb")).thenReturn(new RequiredBundle[] { reqBundle });
    assertFalse(isBundleRequiredByOthers(bundle, admin));
    Bundle user = mock(Bundle.class);
    when(reqBundle.getRequiringBundles()).thenReturn(new Bundle[] { user });
    assertTrue(isBundleRequiredByOthers(bundle, admin));
}

63. JndiUrlIntegrationTest#testBlueprintCompNamespaceWorks()

Project: aries
Source File: JndiUrlIntegrationTest.java
View license
/**
   * This test exercises the blueprint:comp/ jndi namespace by driving
   * a Servlet which then looks up some blueprint components from its own
   * bundle, including a reference which it uses to call a service from a 
   * second bundle.  
   * @throws Exception
   */
@Test
public void testBlueprintCompNamespaceWorks() throws Exception {
    Bundle bBiz = context().getBundleByName("org.apache.aries.jndi.url.itest.biz");
    assertNotNull(bBiz);
    Bundle bweb = context().getBundleByName("org.apache.aries.jndi.url.itest.web");
    assertNotNull(bweb);
    context().getBundleByName("org.ops4j.pax.web.pax-web-extender-war").start();
    printBundleStatus("Before making web request");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException ix) {
    }
    System.out.println("In test and trying to get connection....");
    String response = getTestServletResponse();
    System.out.println("Got response `" + response + "`");
    assertEquals("ITest servlet response wrong", "Mark.2.0.three", response);
}

64. ProviderBundleTrackerCustomizerGenericCapabilityTest#testNoServiceRegistration()

View license
@Test
public void testNoServiceRegistration() throws Exception {
    Bundle mediatorBundle = EasyMock.createMock(Bundle.class);
    EasyMock.expect(mediatorBundle.getBundleId()).andReturn(42l).anyTimes();
    EasyMock.replay(mediatorBundle);
    BaseActivator activator = new BaseActivator() {

        @Override
        public void start(BundleContext context) throws Exception {
        }
    };
    ProviderBundleTrackerCustomizer customizer = new ProviderBundleTrackerCustomizer(activator, mediatorBundle);
    ServiceRegistration sreg = EasyMock.createMock(ServiceRegistration.class);
    EasyMock.replay(sreg);
    BundleContext implBC = mockSPIBundleContext(sreg);
    Bundle implBundle = mockSPIBundle(implBC, SpiFlyConstants.PROVIDER_REQUIREMENT);
    List<ServiceRegistration> registrations = customizer.addingBundle(implBundle, null);
    assertEquals(0, registrations.size());
    Collection<Bundle> bundles = activator.findProviderBundles("org.apache.aries.mytest.MySPI");
    assertEquals(1, bundles.size());
    assertSame(implBundle, bundles.iterator().next());
}

65. ClientWeavingHookTest#testJAXPClientWantsJREImplementation1()

Project: aries
Source File: ClientWeavingHookTest.java
View license
@Test
public void testJAXPClientWantsJREImplementation1() throws Exception {
    Bundle systembundle = mockSystemBundle();
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()");
    Bundle consumerBundle = mockConsumerBundle(headers, systembundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, systembundle).getBundleContext(), activator);
    URL clsUrl = getClass().getResource("JaxpClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
    wh.weave(wc);
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] {});
    Class<?> result = (Class<?>) method.invoke(cls.newInstance());
    Assert.assertEquals("JAXP implementation from JRE", thisJVMsDBF, result.getName());
}

66. RegionContextBundleHelper#installRegionContextBundle()

View license
public static void installRegionContextBundle(final BasicSubsystem subsystem, Coordination coordination) throws Exception {
    String symbolicName = SYMBOLICNAME_PREFIX + subsystem.getSubsystemId();
    String location = subsystem.getLocation() + '/' + subsystem.getSubsystemId();
    Bundle b = subsystem.getRegion().getBundle(symbolicName, VERSION);
    if (b == null) {
        b = subsystem.getRegion().installBundleAtLocation(location, createRegionContextBundle(symbolicName));
        // The start level of all managed bundles, including the region
        // context bundle, should be 1.
        b.adapt(BundleStartLevel.class).setStartLevel(1);
    }
    ResourceInstaller.newInstance(coordination, b.adapt(BundleRevision.class), subsystem).install();
    // The region context bundle must be started persistently.
    b.start();
    subsystem.setRegionContextBundle(b);
}

67. SubsystemDependencyTestBase#checkNoNewBundles()

View license
/**
	 * Check that no new bundles have been provisioned by [x]
	 * @param failText where the failure occurred
	 * @param rootBundlesBefore Bundles before [x]
	 * @param rootBundlesAfter Bundles after [x]
	 */
protected void checkNoNewBundles(String failText, Bundle[] rootBundlesBefore, Bundle[] rootBundlesAfter) {
    Set<String> bundlesBefore = new HashSet<String>();
    for (Bundle b : rootBundlesBefore) {
        bundlesBefore.add(b.getSymbolicName() + "_" + b.getVersion().toString());
    }
    Set<String> bundlesAfter = new HashSet<String>();
    for (Bundle b : rootBundlesAfter) {
        bundlesAfter.add(b.getSymbolicName() + "_" + b.getVersion().toString());
    }
    boolean unchanged = bundlesBefore.containsAll(bundlesAfter) && bundlesAfter.containsAll(bundlesBefore);
    if (!unchanged) {
        bundlesAfter.removeAll(bundlesBefore);
        fail("Extra bundles provisioned in " + failText + " : " + bundlesAfter);
    }
}

68. SubsystemDependency_4BTest#verifyBundlesAandBinstalledIntoRootRegion()

View license
// - Verify that bundles A and B got installed into the Root Subsystem
@Test
public void verifyBundlesAandBinstalledIntoRootRegion() throws Exception {
    System.out.println("Into verifyBundlesAandBinstalledIntoRootRegion");
    Subsystem s = installSubsystemFromFile(APPLICATION_B);
    startSubsystem(s);
    Bundle[] bundles = bundleContext.getBundles();
    Collection<String> bundleNames = new ArrayList<String>();
    for (Bundle b : bundles) {
        bundleNames.add(b.getSymbolicName());
    }
    assertTrue("Bundle A should have been provisioned to the root region", bundleNames.contains(BUNDLE_A));
    assertTrue("Bundle B should have been provisioned to the root region", bundleNames.contains(BUNDLE_B));
    stopSubsystem(s);
}

69. Aries1435Test#testDynamicImport()

Project: aries
Source File: Aries1435Test.java
View license
private void testDynamicImport(Subsystem subsystem, String clazz) throws Exception {
    assertConstituent(subsystem, BUNDLE_A);
    Bundle bundleA = getConstituentAsBundle(subsystem, BUNDLE_A, null, null);
    bundleA.loadClass("a.A");
    assertTrue("Weaving hook not called", weavingHookCalled.get());
    try {
        bundleA.loadClass(clazz);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Dynamic import not visible");
    }
}

70. UnmanagedBundleTest#testInstallWhileImplBundleStopped()

Project: aries
Source File: UnmanagedBundleTest.java
View license
/*
	 * Test that an unmanaged bundle is detected as a constituent in the root
	 * subsystem when the subsystems core bundle is stopped. This ensures that
	 * persistence isn't interfering with detection.
	 */
@Test
public void testInstallWhileImplBundleStopped() throws Exception {
    Bundle core = getSubsystemCoreBundle();
    core.stop();
    try {
        Bundle a = bundleContext.installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
        try {
            core.start();
            assertConstituent(getRootSubsystem(), BUNDLE_A);
        } finally {
            uninstallSilently(a);
        }
    } finally {
        core.start();
    }
}

71. UnmanagedBundleTest#testInstallWhileImplBundleUninstalled()

Project: aries
Source File: UnmanagedBundleTest.java
View license
/*
	 * Test that an unmanaged bundle is detected as a constituent in the root
	 * subsystem when the subsystems core bundle is uninstalled.
	 */
@Test
public void testInstallWhileImplBundleUninstalled() throws Exception {
    Bundle core = getSubsystemCoreBundle();
    core.uninstall();
    try {
        Bundle a = bundleContext.installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
        try {
            core = bundleContext.installBundle(normalizeBundleLocation(core));
            core.start();
            assertConstituent(getRootSubsystem(), BUNDLE_A);
        } finally {
            uninstallSilently(a);
        }
    } finally {
        if (core.getState() == Bundle.UNINSTALLED) {
            core = bundleContext.installBundle(normalizeBundleLocation(core));
            core.start();
        }
    }
}

72. ClasspathContainerPage#getSelVersion()

View license
/**
     * Returns the version of selected entry in combo box.
     *
     * @return version.
     */
private String getSelVersion() {
    Bundle[] bundles = Platform.getBundles(Messages.sdkID, null);
    Bundle bundle = null;
    String version = "";
    if (bundles != null) {
        bundle = bundles[combo.getSelectionIndex()];
        version = String.format("%s.%s.%s", Integer.toString(bundle.getVersion().getMajor()), Integer.toString(bundle.getVersion().getMinor()), Integer.toString(bundle.getVersion().getMicro()));
    }
    return version;
}

73. ClasspathContainerPage#getSelVersion()

View license
/**
     * Returns the version of selected entry in combo box.
     *
     * @return version.
     */
private String getSelVersion() {
    Bundle[] bundles = Platform.getBundles(Messages.sdkID, null);
    Bundle bundle = null;
    String version = "";
    if (bundles != null) {
        bundle = bundles[combo.getSelectionIndex()];
        version = String.format("%s.%s.%s", Integer.toString(bundle.getVersion().getMajor()), Integer.toString(bundle.getVersion().getMinor()), Integer.toString(bundle.getVersion().getMicro()));
    }
    return version;
}

74. ClasspathContainerPage#getSelVersion()

View license
/**
     * Returns the version of selected entry in combo box.
     *
     * @return version.
     */
private String getSelVersion() {
    Bundle[] bundles = Platform.getBundles(Messages.sdkID, null);
    Bundle bundle = null;
    String version = "";
    if (bundles != null) {
        bundle = bundles[combo.getSelectionIndex()];
        version = String.format("%s.%s.%s", Integer.toString(bundle.getVersion().getMajor()), Integer.toString(bundle.getVersion().getMinor()), Integer.toString(bundle.getVersion().getMicro()));
    }
    return version;
}

75. ClasspathContainerPage#getSelVersion()

View license
/**
	 * Returns the version of selected entry in combo box.
	 *
	 * @return version.
	 */
private String getSelVersion() {
    Bundle[] bundles = Platform.getBundles(Messages.qpidID, null);
    Bundle bundle = null;
    String version = "";
    if (bundles != null) {
        bundle = bundles[combo.getSelectionIndex()];
        version = String.format("%s.%s.%s", Integer.toString(bundle.getVersion().getMajor()), Integer.toString(bundle.getVersion().getMinor()), Integer.toString(bundle.getVersion().getMicro()));
    }
    return version;
}

76. MiniFrameworkTest#testSimple()

Project: bnd
Source File: MiniFrameworkTest.java
View license
public static void testSimple() throws Exception {
    Properties properties = new Properties();
    MiniFramework framework = new MiniFramework(properties);
    URL url = new File("test/demo.jar").toURI().toURL();
    url.openStream().close();
    framework.init();
    Bundle b = framework.installBundle("reference:" + url.toExternalForm());
    assertNotNull(b);
    Bundle[] bundles = framework.getBundles();
    assertNotNull(bundles);
    assertEquals(2, bundles.length);
    Class<?> c = b.loadClass("test.TestActivator");
    assertNotNull(c);
}

77. AgentServer#getBundles()

Project: bnd
Source File: AgentServer.java
View license
@Override
public List<BundleDTO> getBundles(long... bundleId) throws Exception {
    Bundle[] bundles;
    if (bundleId.length == 0) {
        bundles = context.getBundles();
    } else {
        bundles = new Bundle[bundleId.length];
        for (int i = 0; i < bundleId.length; i++) {
            bundles[i] = context.getBundle(bundleId[i]);
        }
    }
    List<BundleDTO> bundleDTOs = new ArrayList<BundleDTO>(bundles.length);
    for (Bundle b : bundles) {
        BundleDTO dto = toDTO(b);
        bundleDTOs.add(dto);
    }
    return bundleDTOs;
}

78. AgentServer#getBundleRevisons()

Project: bnd
Source File: AgentServer.java
View license
/**
	 * Return the bundle revisions
	 */
@Override
public List<BundleRevisionDTO> getBundleRevisons(long... bundleId) throws Exception {
    Bundle[] bundles;
    if (bundleId.length == 0) {
        bundles = context.getBundles();
    } else {
        bundles = new Bundle[bundleId.length];
        for (int i = 0; i < bundleId.length; i++) {
            bundles[i] = context.getBundle(bundleId[i]);
        }
    }
    List<BundleRevisionDTO> revisions = new ArrayList<BundleRevisionDTO>(bundles.length);
    for (Bundle b : bundles) {
        BundleRevision resource = b.adapt(BundleRevision.class);
        BundleRevisionDTO bwd = toDTO(resource);
        revisions.add(bwd);
    }
    return revisions;
}

79. OsgiFactoryFinder#getResource()

Project: camel
Source File: OsgiFactoryFinder.java
View license
// The clazz can make sure we get right version of class that we need
public BundleEntry getResource(String name, Class<?> clazz) {
    BundleEntry entry = null;
    Bundle[] bundles = null;
    bundles = bundleContext.getBundles();
    URL url;
    for (Bundle bundle : bundles) {
        url = bundle.getEntry(getResourcePath() + name);
        if (url != null && checkCompat(bundle, clazz)) {
            entry = new BundleEntry();
            entry.url = url;
            entry.bundle = bundle;
            break;
        }
    }
    return entry;
}

80. BundleContextUtils#findComponents()

Project: camel
Source File: BundleContextUtils.java
View license
/**
     * Finds the components available on the bundle context and camel context
     */
public static Map<String, Properties> findComponents(BundleContext bundleContext, CamelContext camelContext) throws IOException, LoadPropertiesException {
    SortedMap<String, Properties> answer = new TreeMap<String, Properties>();
    Bundle[] bundles = bundleContext.getBundles();
    for (Bundle bundle : bundles) {
        Enumeration<URL> iter = bundle.getResources(CamelContextHelper.COMPONENT_DESCRIPTOR);
        SortedMap<String, Properties> map = CamelContextHelper.findComponents(camelContext, iter);
        answer.putAll(map);
    }
    return answer;
}

81. BundleContextUtils#getComponentDocumentation()

Project: camel
Source File: BundleContextUtils.java
View license
public static String getComponentDocumentation(BundleContext bundleContext, CamelContext camelContext, String componentName) throws IOException {
    String path = CamelContextHelper.COMPONENT_DOCUMENTATION_PREFIX + componentName + ".html";
    Bundle[] bundles = bundleContext.getBundles();
    for (Bundle bundle : bundles) {
        URL resource = bundle.getResource(path);
        if (resource != null) {
            InputStream inputStream = resource.openStream();
            if (inputStream != null) {
                return IOHelper.loadText(inputStream);
            }
        }
    }
    return null;
}

82. ThumbnailService#getStyleBundle()

Project: clerezza
Source File: ThumbnailService.java
View license
private synchronized Bundle getStyleBundle() {
    if (cachedStyleBundle != null) {
        return cachedStyleBundle;
    }
    Bundle[] bundles = bundleContext.getBundles();
    for (Bundle bundle : bundles) {
        URL staticWebPathURL = bundle.getEntry(STATICWEB_PATH);
        if (staticWebPathURL != null) {
            cachedStyleBundle = bundle;
            return bundle;
        }
    }
    return null;
}

83. ScriptEngineFactoryManager#registerExistingEngineFactories()

View license
private void registerExistingEngineFactories() {
    if (componentContext == null) {
        logger.warn("componentContext is null while trying to register" + "script engine factories in started bundles");
        return;
    }
    Bundle[] bundles = componentContext.getBundleContext().getBundles();
    for (Bundle bundle : bundles) {
        if (bundle.getState() == Bundle.ACTIVE) {
            List<String> engineFactoryNames = getEngineFactoryNames(bundle);
            registerEngineFactories(bundle, engineFactoryNames);
        }
    }
}

84. ServerOsgiTestBase#testBundleActivation()

View license
@Test
public void testBundleActivation() {
    String bundleName = getBundleName();
    boolean bundleFound = false;
    boolean bundleActive = false;
    Bundle[] bundles = context.getBundles();
    for (Bundle bundle : bundles) {
        //System.out.println( "### bundle=" + bundle + " " + bundle.getState() );
        if (bundle != null && bundle.getSymbolicName() != null && bundle.getSymbolicName().equals(bundleName)) {
            bundleFound = true;
            if (bundle.getState() == Bundle.ACTIVE) {
                bundleActive = true;
            }
        }
    }
    assertTrue("Bundle " + bundleName + " not found.", bundleFound);
    assertTrue("Bundle " + bundleName + " is not active.", bundleActive);
}

85. ApiOsgiTestBase#testBundleActivation()

View license
@Test
public void testBundleActivation() {
    String bundleName = getBundleName();
    boolean bundleFound = false;
    boolean bundleActive = false;
    Bundle[] bundles = context.getBundles();
    for (Bundle bundle : bundles) {
        //System.out.println( "### bundle=" + bundle + " " + bundle.getState() );
        if (bundle != null && bundle.getSymbolicName() != null && bundle.getSymbolicName().equals(bundleName)) {
            bundleFound = true;
            if (bundle.getState() == Bundle.ACTIVE) {
                bundleActive = true;
            }
        }
    }
    assertTrue("Bundle " + bundleName + " not found.", bundleFound);
    assertTrue("Bundle " + bundleName + " is not active.", bundleActive);
}

86. OSGiBundleTest#checkBundle()

Project: HikariCP
Source File: OSGiBundleTest.java
View license
@Test
public void checkBundle() {
    Boolean bundleFound = false;
    Boolean bundleActive = false;
    Bundle[] bundles = context.getBundles();
    for (Bundle bundle : bundles) {
        if (bundle != null) {
            if (bundle.getSymbolicName().equals("com.zaxxer.HikariCP")) {
                bundleFound = true;
                if (bundle.getState() == Bundle.ACTIVE) {
                    bundleActive = true;
                }
            }
        }
    }
    assertTrue(bundleFound);
    assertTrue(bundleActive);
}

87. OSGiBundleTest#checkBundle()

Project: Java-Lang
Source File: OSGiBundleTest.java
View license
@Test
public void checkBundle() {
    Boolean bundleFound = false;
    Bundle[] bundles = context.getBundles();
    for (Bundle bundle : bundles) {
        if (bundle != null) {
            if (bundle.getSymbolicName().equals("net.openhft.lang")) {
                bundleFound = true;
                assertEquals(bundle.getState(), Bundle.ACTIVE);
            }
        }
    }
    assertTrue(bundleFound);
}

88. OSGiTestBase#findBundle()

View license
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;
}

89. SinglePackagePage#populate()

View license
private void populate(ExportedPackage exportPkg) {
    Bundle exporter = exportPkg.getExportingBundle();
    Bundle[] importers = exportPkg.getImportingBundles();
    add(new BundlePanel("exporter", new BundleModel(exporter)));
    add(new Label("packageDet", exportPkg.getName()));
    add(new ListView<Bundle>("importers", Arrays.asList(importers)) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<Bundle> item) {
            BundlePanel panel = new BundlePanel("importer", item.getModel(), true);
            item.add(panel);
        }
    });
}

90. Activator#start()

Project: logging-log4j2
Source File: Activator.java
View license
@Override
public void start(final BundleContext context) throws Exception {
    ProviderUtil.STARTUP_LOCK.lock();
    lockingProviderUtil = true;
    final BundleWiring self = context.getBundle().adapt(BundleWiring.class);
    final List<BundleWire> required = self.getRequiredWires(LoggerContextFactory.class.getName());
    for (final BundleWire wire : required) {
        loadProvider(wire.getProviderWiring());
    }
    context.addBundleListener(this);
    final Bundle[] bundles = context.getBundles();
    for (final Bundle bundle : bundles) {
        loadProvider(bundle);
    }
    unlockIfReady();
}

91. BasicDistroTest#testCorrectStatus()

Project: servicemix
Source File: BasicDistroTest.java
View license
@Test
public void testCorrectStatus() throws Exception {
    Bundle[] bundles = context.getBundles();
    for (Bundle bundle : bundles) {
        if (!isActive(bundle) && !isFragment(bundle)) {
            // Starting bundle to cause error
            bundle.start();
        }
        if (!isResolved(bundle) && isFragment(bundle)) {
            throw new IllegalStateException("Bundle " + bundle.getSymbolicName() + " is not resolved");
        }
    }
}

92. FileMonitor#refreshPackagesAndStartOrUpdateBundles()

Project: servicemix4-kernel
Source File: FileMonitor.java
View license
protected void refreshPackagesAndStartOrUpdateBundles() {
    for (Bundle bundle : bundlesToUpdate) {
        try {
            bundle.update();
            LOGGER.info("Updated: " + bundle);
        } catch (BundleException e) {
            LOGGER.warn("Failed to update bundle: " + bundle + ". Reason: " + e, e);
        }
    }
    for (Bundle bundle : bundlesToStart) {
        try {
            bundle.start();
            LOGGER.info("Started: " + bundle);
        } catch (BundleException e) {
            LOGGER.warn("Failed to start bundle: " + bundle + ". Reason: " + e, e);
            rescheduleStart(bundle);
        }
    }
    PackageAdmin packageAdmin = getPackageAdmin();
    if (packageAdmin != null) {
        packageAdmin.refreshPackages(null);
    }
}

93. CoreTest#testInstallCommand()

Project: servicemix4-kernel
Source File: CoreTest.java
View license
public void testInstallCommand() throws Exception {
    Shell shell = getOsgiService(Shell.class);
    try {
        shell.execute("log/display");
        fail("command should not exist");
    } catch (CommandLineExecutionFailed e) {
        assertNotNull(e.getCause());
        assertTrue(e.getCause() instanceof NoSuchCommandException);
    }
    Bundle b = installBundle("org.apache.servicemix.kernel.gshell", "org.apache.servicemix.kernel.gshell.log", null, "jar");
    shell.execute("log/display");
    b.uninstall();
    try {
        shell.execute("log/display");
        fail("command should not exist");
    } catch (CommandLineExecutionFailed e) {
        assertNotNull(e.getCause());
        assertTrue(e.getCause() instanceof NoSuchCommandException);
    }
}

94. BundleTestsProvider#createTestClass()

Project: sling
Source File: BundleTestsProvider.java
View license
/** @inheritDoc */
public Class<?> createTestClass(String testName) throws ClassNotFoundException {
    // Find the bundle to which the class belongs
    Bundle b = null;
    for (Map.Entry<String, List<String>> e : testClassesMap.entrySet()) {
        if (e.getValue().contains(testName)) {
            b = findBundle(e.getKey());
            break;
        }
    }
    if (b == null) {
        throw new IllegalArgumentException("No Bundle found that supplies test class " + testName);
    }
    return b.loadClass(testName);
}

95. ResolvedBundleTracker#initialize()

View license
private synchronized void initialize() {
    Bundle[] bundles = this.bundleContext.getBundles();
    for (Bundle bundle : bundles) {
        int state = bundle.getState();
        boolean shouldNotBeTracked = (state & (Bundle.INSTALLED | Bundle.UNINSTALLED)) > 0;
        if (shouldNotBeTracked) {
            remove(bundle);
        } else {
            add(bundle);
        }
    }
}

96. OptDexProcess#runOptDexNonDelay()

Project: ACDD
Source File: OptDexProcess.java
View license
private void runOptDexNonDelay() {
    for (Bundle bundle : ACDD.getInstance().getBundles()) {
        if (!(bundle == null || contains(ACDDConfig.STORE, bundle.getLocation()))) {
            try {
                ((BundleImpl) bundle).optDexFile();
            } catch (Throwable e) {
                if (e instanceof DexLoadException) {
                    throw ((RuntimeException) e);
                }
                Log.e("OptDexProcess", "Error while dexopt >>>", e);
            }
        }
    }
}

97. ACDD#updateBundle()

Project: ACDD
Source File: ACDD.java
View license
/**
     * update bundle,when app  restart,update will change
     *
     * @param pkgName     bundle's package name
     * @param mBundleFile bundle archive file
     * @throws BundleException
     */
public void updateBundle(String pkgName, File mBundleFile) throws BundleException {
    if (!mBundleFile.exists()) {
        throw new BundleException("file not  found" + mBundleFile.getAbsolutePath());
    }
    Bundle bundle = Framework.getBundle(pkgName);
    if (bundle != null) {
        bundle.update(mBundleFile);
        return;
    }
    throw new BundleException("Could not update bundle " + pkgName + ", because could not find it");
}

98. ACDD#uninstallBundle()

Project: ACDD
Source File: ACDD.java
View license
/**
     * uninstall specific bundle
     *
     * @param pkgName bundle package name you wanna uninstall
     * @throws BundleException
     */
public void uninstallBundle(String pkgName) throws BundleException {
    Bundle bundle = Framework.getBundle(pkgName);
    if (bundle != null) {
        BundleImpl bundleImpl = (BundleImpl) bundle;
        try {
            File archiveFile = bundleImpl.getArchive().getArchiveFile();
            if (archiveFile.canWrite()) {
                archiveFile.delete();
            }
            bundleImpl.getArchive().purge();
            File revisionDir = bundleImpl.getArchive().getCurrentRevision().getRevisionDir();
            bundle.uninstall();
            if (revisionDir != null) {
                Framework.deleteDirectory(revisionDir);
                return;
            }
            return;
        } catch (Exception e) {
            log.error("uninstall bundle error: " + pkgName + e.getMessage());
            return;
        }
    }
    throw new BundleException("Could not uninstall bundle " + pkgName + ", because could not find it");
}

99. BundleDisabler#disableBundles()

Project: acs-aem-commons
Source File: BundleDisabler.java
View license
private void disableBundles() {
    if (disabledBundles.isEmpty()) {
        log.info("No bundles specified. Consider specifying bundles or removing this service config");
        return;
    }
    log.trace("Disabling bundles {}", disabledBundles);
    for (Bundle bundle : bundleContext.getBundles()) {
        if (isOnBundleStopList(bundle)) {
            try {
                disableBundle(bundle);
            } catch (BundleException be) {
                log.error("Unable to stop bundle {}", bundle.getSymbolicName(), be);
            }
        }
    }
}

100. BundleDisablerTest#shouldStopBundle()

View license
@Test
public void shouldStopBundle() {
    Bundle targetBundle = mock(Bundle.class);
    bundles.add(targetBundle);
    when(targetBundle.getSymbolicName()).thenReturn("to.stop.bundle");
    disabler.activate(componentContext, bundleProperties("to.stop.bundle"));
    try {
        verify(targetBundle).stop();
    } catch (BundleException be) {
    }
}