Search in sources :

Example 86 with BundleWiring

use of org.osgi.framework.wiring.BundleWiring in project rt.equinox.framework by eclipse.

the class SystemBundleTests method testWeavingPersistence.

public void testWeavingPersistence() {
    // $NON-NLS-1$
    File config = OSGiTestsActivator.getContext().getDataFile(getName());
    Map<String, Object> configuration = new HashMap<String, Object>();
    configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath());
    Equinox equinox = new Equinox(configuration);
    try {
        equinox.start();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected exception in start()", e);
    }
    BundleContext systemContext = equinox.getBundleContext();
    // $NON-NLS-1$
    assertNotNull("System context is null", systemContext);
    Bundle test1 = null;
    try {
        test1 = systemContext.installBundle(installer.getBundleLocation("substitutes.a"));
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected error installing bundle", e);
    }
    long testID1 = test1.getBundleId();
    final Bundle testFinal1 = test1;
    ServiceRegistration reg = systemContext.registerService(WeavingHook.class, new WeavingHook() {

        public void weave(WovenClass wovenClass) {
            if (!testFinal1.equals(wovenClass.getBundleWiring().getBundle()))
                return;
            if (!"substitutes.x.Ax".equals(wovenClass.getClassName()))
                return;
            List dynamicImports = wovenClass.getDynamicImports();
            dynamicImports.add("*");
        }
    }, null);
    try {
        testFinal1.loadClass("substitutes.x.Ax");
        testFinal1.loadClass("org.osgi.framework.hooks.bundle.FindHook");
    } catch (Throwable t) {
        fail("Unexpected testing bundle", t);
    } finally {
        reg.unregister();
    }
    // put the framework back to the RESOLVED state
    try {
        equinox.stop();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected error stopping framework", e);
    }
    try {
        equinox.waitForStop(10000);
    } catch (InterruptedException e) {
        // $NON-NLS-1$
        fail("Unexpected interrupted exception", e);
    }
    try {
        equinox.start();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected exception in start()", e);
    }
    systemContext = equinox.getBundleContext();
    test1 = systemContext.getBundle(testID1);
    Bundle test2 = null;
    try {
        test2 = systemContext.installBundle(installer.getBundleLocation("exporter.importer1"));
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected error installing bundle", e);
    }
    long testID2 = test2.getBundleId();
    final Bundle testFinal2 = test2;
    reg = systemContext.registerService(WeavingHook.class, new WeavingHook() {

        public void weave(WovenClass wovenClass) {
            if (!testFinal2.equals(wovenClass.getBundleWiring().getBundle()))
                return;
            if (!"exporter.importer.test.Test1".equals(wovenClass.getClassName()))
                return;
            List dynamicImports = wovenClass.getDynamicImports();
            dynamicImports.add("*");
        }
    }, null);
    try {
        testFinal2.loadClass("exporter.importer.test.Test1");
        testFinal2.loadClass("org.osgi.framework.hooks.service.FindHook");
    } catch (Throwable t) {
        fail("Unexpected testing bundle", t);
    } finally {
        reg.unregister();
    }
    // put the framework back to the RESOLVED state
    try {
        equinox.stop();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected error stopping framework", e);
    }
    try {
        equinox.waitForStop(10000);
    } catch (InterruptedException e) {
        // $NON-NLS-1$
        fail("Unexpected interrupted exception", e);
    }
    try {
        equinox.start();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected exception in start()", e);
    }
    systemContext = equinox.getBundleContext();
    test1 = systemContext.getBundle(testID1);
    test2 = systemContext.getBundle(testID2);
    BundleRevision rev1 = test1.adapt(BundleRevision.class);
    BundleRevision rev2 = test2.adapt(BundleRevision.class);
    BundleWiring wiring1 = rev1.getWiring();
    BundleWiring wiring2 = rev2.getWiring();
    assertNotNull("wiring1 is null", wiring1);
    assertNotNull("wiring2 is null", wiring2);
    List packages1 = wiring1.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
    List packages2 = wiring2.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
    // could make this a more complete check, but with the bug the dynamic wires
    // are missing altogether because we fail to save the resolver state cache.
    assertEquals("Wrong number of wires for wiring1", 1, packages1.size());
    assertEquals("Wrong number of wires for wiring2", 1, packages2.size());
    try {
        equinox.stop();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected error stopping framework", e);
    }
    try {
        equinox.waitForStop(10000);
    } catch (InterruptedException e) {
        // $NON-NLS-1$
        fail("Unexpected interrupted exception", e);
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Bundle(org.osgi.framework.Bundle) BundleWiring(org.osgi.framework.wiring.BundleWiring) WovenClass(org.osgi.framework.hooks.weaving.WovenClass) Equinox(org.eclipse.osgi.launch.Equinox) BundleRevision(org.osgi.framework.wiring.BundleRevision) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) BundleException(org.osgi.framework.BundleException) File(java.io.File) WeavingHook(org.osgi.framework.hooks.weaving.WeavingHook) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 87 with BundleWiring

use of org.osgi.framework.wiring.BundleWiring in project rt.equinox.framework by eclipse.

the class ClassLoadingBundleTests method testLoaderUninstalledBundle.

public void testLoaderUninstalledBundle() throws BundleException, IOException {
    String testResourcePath = "testResource";
    // $NON-NLS-1$
    File config = OSGiTestsActivator.getContext().getDataFile(getName());
    Map<String, String> testHeaders = new HashMap<String, String>();
    testHeaders.put(Constants.BUNDLE_MANIFESTVERSION, "2");
    testHeaders.put(Constants.BUNDLE_SYMBOLICNAME, getName());
    config.mkdirs();
    File testBundleFile = SystemBundleTests.createBundle(config, getName(), testHeaders, Collections.singletonMap(testResourcePath, "testValue"));
    Bundle test = getContext().installBundle(getName(), new FileInputStream(testBundleFile));
    test.start();
    BundleWiring wiring = test.adapt(BundleWiring.class);
    assertNotNull("No wiring found.", wiring);
    ModuleClassLoader bundleClassLoader = (ModuleClassLoader) wiring.getClassLoader();
    URL testResource = bundleClassLoader.findLocalResource(testResourcePath);
    assertNotNull("No test resource found.", testResource);
    test.update(new FileInputStream(testBundleFile));
    testResource = bundleClassLoader.findLocalResource(testResourcePath);
    assertNull("Found resource.", testResource);
    Object[] expectedFrameworkEvents = new Object[] { new FrameworkEvent(FrameworkEvent.INFO, test, null) };
    Object[] actualFrameworkEvents = frameworkListenerResults.getResults(1);
    compareResults(expectedFrameworkEvents, actualFrameworkEvents);
    wiring = test.adapt(BundleWiring.class);
    assertNotNull("No wiring found.", wiring);
    bundleClassLoader = (ModuleClassLoader) wiring.getClassLoader();
    testResource = bundleClassLoader.findLocalResource(testResourcePath);
    assertNotNull("No test resource found.", testResource);
    test.uninstall();
    testResource = bundleClassLoader.findLocalResource(testResourcePath);
    assertNull("Found resource.", testResource);
    actualFrameworkEvents = frameworkListenerResults.getResults(1);
    compareResults(expectedFrameworkEvents, actualFrameworkEvents);
}
Also used : HashMap(java.util.HashMap) FrameworkEvent(org.osgi.framework.FrameworkEvent) Bundle(org.osgi.framework.Bundle) ModuleClassLoader(org.eclipse.osgi.internal.loader.ModuleClassLoader) BundleWiring(org.osgi.framework.wiring.BundleWiring) File(java.io.File) FileInputStream(java.io.FileInputStream) URL(java.net.URL)

Example 88 with BundleWiring

use of org.osgi.framework.wiring.BundleWiring in project rt.equinox.framework by eclipse.

the class MultiReleaseJarTests method readResources.

private String readResources(String name, Bundle mrBundle) throws IOException {
    BundleWiring wiring = mrBundle.adapt(BundleWiring.class);
    List<URL> urls = Collections.list(wiring.getClassLoader().getResources(name));
    if (urls.isEmpty()) {
        return RNF;
    }
    assertEquals("Wrong number of resources.", 1, urls.size());
    return readURL(urls.get(0));
}
Also used : BundleWiring(org.osgi.framework.wiring.BundleWiring) URL(java.net.URL)

Example 89 with BundleWiring

use of org.osgi.framework.wiring.BundleWiring in project rt.equinox.framework by eclipse.

the class MultiReleaseJarTests method readResource.

private String readResource(String name, Bundle mrBundle) throws Exception {
    BundleWiring wiring = mrBundle.adapt(BundleWiring.class);
    URL url = wiring.getClassLoader().getResource(name);
    String result = readURL(url);
    int lastSlash = name.lastIndexOf('/');
    Collection<String> resourcePaths = wiring.listResources(name.substring(0, lastSlash + 1), name.substring(lastSlash + 1), 0);
    if (result == RNF) {
        if (!resourcePaths.isEmpty()) {
            fail("listResources found path for '" + name + "'");
        }
    } else {
        assertEquals("Found too many resource paths for '" + name + "'", 1, resourcePaths.size());
        assertEquals("Wrong path listed.", name, resourcePaths.iterator().next());
        assertURLCopy(result, url, mrBundle);
    }
    return result;
}
Also used : BundleWiring(org.osgi.framework.wiring.BundleWiring) URL(java.net.URL)

Example 90 with BundleWiring

use of org.osgi.framework.wiring.BundleWiring in project karaf by apache.

the class GuardProxyCatalogTest method testHandleServiceModified.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testHandleServiceModified() throws Exception {
    Dictionary<String, Object> config = new Hashtable<>();
    config.put(Constants.SERVICE_PID, "test.1.2.3");
    config.put("service.guard", "(objectClass=" + TestServiceAPI.class.getName() + ")");
    config.put("doit", "role.1");
    Dictionary<String, Object> config2 = new Hashtable<>();
    config2.put(Constants.SERVICE_PID, "test.1.2.4");
    config2.put("service.guard", "(objectClass=" + TestServiceAPI2.class.getName() + ")");
    config2.put("doit", "role.2");
    BundleContext bc = mockConfigAdminBundleContext(config, config2);
    GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
    // The service being proxied has these properties
    long serviceID = 1L;
    final Hashtable<String, Object> serviceProps = new Hashtable<>();
    serviceProps.put(Constants.OBJECTCLASS, new String[] { TestServiceAPI.class.getName(), TestServiceAPI2.class.getName() });
    serviceProps.put(Constants.SERVICE_ID, serviceID);
    // will be overwritten
    serviceProps.put(GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY, Arrays.asList("someone"));
    Object myObject = new Object();
    serviceProps.put("foo.bar", myObject);
    BundleContext providerBC = EasyMock.createNiceMock(BundleContext.class);
    EasyMock.expect(providerBC.registerService(EasyMock.aryEq(new String[] { TestServiceAPI.class.getName(), TestServiceAPI2.class.getName() }), EasyMock.anyObject(), EasyMock.anyObject(Dictionary.class))).andAnswer((IAnswer) () -> {
        final Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2];
        assertEquals(Boolean.TRUE, props.get(GuardProxyCatalog.PROXY_SERVICE_KEY));
        ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
        ServiceReference sr = mockServiceReference(props);
        EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
        reg.setProperties(EasyMock.isA(Dictionary.class));
        EasyMock.expectLastCall().andAnswer(() -> {
            // Push the update into the service reference
            ArrayList<String> oldKeys = Collections.list(props.keys());
            for (String key : oldKeys) {
                props.remove(key);
            }
            Dictionary<String, Object> newProps = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[0];
            for (String key : Collections.list(newProps.keys())) {
                props.put(key, newProps.get(key));
            }
            return null;
        }).once();
        EasyMock.replay(reg);
        return reg;
    }).anyTimes();
    EasyMock.replay(providerBC);
    // In some cases the proxy-creating code is looking for a classloader (e.g. when run through
    // a coverage tool such as EclEmma). This will satisfy that.
    BundleWiring bw = EasyMock.createMock(BundleWiring.class);
    EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader()).anyTimes();
    EasyMock.replay(bw);
    // The mock bundle that provides the original service (and also the proxy is registered with this)
    Bundle providerBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(providerBundle.getBundleContext()).andReturn(providerBC).anyTimes();
    EasyMock.expect(providerBundle.adapt(BundleWiring.class)).andReturn(bw).anyTimes();
    EasyMock.replay(providerBundle);
    ServiceReference sr = mockServiceReference(providerBundle, serviceProps);
    gpc.proxyIfNotAlreadyProxied(sr);
    GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
    runnable.run(getProxyManager());
    ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
    ServiceRegistration<?> reg = holder.registration;
    for (String key : serviceProps.keySet()) {
        if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) {
            assertEquals(new HashSet(Arrays.asList("role.1", "role.2")), reg.getReference().getProperty(key));
        } else {
            assertEquals(serviceProps.get(key), reg.getReference().getProperty(key));
        }
    }
    assertEquals(Boolean.TRUE, reg.getReference().getProperty(GuardProxyCatalog.PROXY_SERVICE_KEY));
    // now change the original service and let the proxy react
    serviceProps.put("test", "property");
    assertEquals("Precondition, the mocked reference should have picked up this change", "property", sr.getProperty("test"));
    gpc.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, sr));
    assertEquals("Changing the service should not change the number of proxies", 1, gpc.proxyMap.size());
    for (String key : serviceProps.keySet()) {
        if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) {
            assertEquals(new HashSet(Arrays.asList("role.1", "role.2")), reg.getReference().getProperty(key));
        } else {
            assertEquals(serviceProps.get(key), reg.getReference().getProperty(key));
        }
    }
    assertEquals("property", reg.getReference().getProperty("test"));
    assertEquals(Boolean.TRUE, reg.getReference().getProperty(GuardProxyCatalog.PROXY_SERVICE_KEY));
}
Also used : Dictionary(java.util.Dictionary) CreateProxyRunnable(org.apache.karaf.service.guard.impl.GuardProxyCatalog.CreateProxyRunnable) Hashtable(java.util.Hashtable) Bundle(org.osgi.framework.Bundle) BundleWiring(org.osgi.framework.wiring.BundleWiring) ArrayList(java.util.ArrayList) ServiceRegistrationHolder(org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder) ServiceReference(org.osgi.framework.ServiceReference) IAnswer(org.easymock.IAnswer) ServiceEvent(org.osgi.framework.ServiceEvent) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

BundleWiring (org.osgi.framework.wiring.BundleWiring)110 Bundle (org.osgi.framework.Bundle)61 BundleWire (org.osgi.framework.wiring.BundleWire)39 ArrayList (java.util.ArrayList)23 BundleRevision (org.osgi.framework.wiring.BundleRevision)23 BundleCapability (org.osgi.framework.wiring.BundleCapability)19 Test (org.junit.Test)15 HashMap (java.util.HashMap)13 Hashtable (java.util.Hashtable)12 List (java.util.List)12 BundleContext (org.osgi.framework.BundleContext)12 URL (java.net.URL)10 Dictionary (java.util.Dictionary)10 HashSet (java.util.HashSet)9 LinkedHashMap (java.util.LinkedHashMap)8 Version (org.osgi.framework.Version)7 BundleRevisions (org.osgi.framework.wiring.BundleRevisions)7 AbstractIntegrationTest (org.apache.aries.jmx.AbstractIntegrationTest)6 IAnswer (org.easymock.IAnswer)6 ServiceReference (org.osgi.framework.ServiceReference)6