Search in sources :

Example 26 with IAnswer

use of org.easymock.IAnswer in project aries by apache.

the class ClientWeavingHookOSGi43Test method mockProviderBundle.

private Bundle mockProviderBundle(String subdir, long id, Version version) throws Exception {
    URL url = getClass().getResource("/" + getClass().getName().replace('.', '/') + ".class");
    File classFile = new File(url.getFile());
    File baseDir = new File(classFile.getParentFile(), subdir);
    File directory = new File(baseDir, "/META-INF/services");
    final List<String> classNames = new ArrayList<String>();
    // Do a directory listing of the applicable META-INF/services directory
    List<String> resources = new ArrayList<String>();
    for (File f : directory.listFiles()) {
        String fileName = f.getName();
        if (fileName.startsWith(".") || fileName.endsWith("."))
            continue;
        classNames.addAll(getClassNames(f));
        // Needs to be something like: META-INF/services/org.apache.aries.mytest.MySPI
        String path = f.getAbsolutePath().substring(baseDir.getAbsolutePath().length());
        path = path.replace('\\', '/');
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        resources.add(path);
    }
    // Set up the classloader that will be used by the ASM-generated code as the TCCL.
    // It can load a META-INF/services file
    final ClassLoader cl = new TestProviderBundleClassLoader(subdir, resources.toArray(new String[] {}));
    final List<String> classResources = new ArrayList<String>();
    for (String className : classNames) {
        classResources.add("/" + className.replace('.', '/') + ".class");
    }
    Bundle systemBundle = EasyMock.createMock(Bundle.class);
    EasyMock.<Class<?>>expect(systemBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() {

        @Override
        public Class<?> answer() throws Throwable {
            String name = (String) EasyMock.getCurrentArguments()[0];
            return ClientWeavingHookOSGi43Test.class.getClassLoader().loadClass(name);
        }
    }).anyTimes();
    EasyMock.replay(systemBundle);
    BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
    EasyMock.expect(bc.getBundle(0)).andReturn(systemBundle).anyTimes();
    EasyMock.replay(bc);
    BundleWiring bundleWiring = EasyMock.createMock(BundleWiring.class);
    EasyMock.expect(bundleWiring.getClassLoader()).andReturn(cl).anyTimes();
    EasyMock.replay(bundleWiring);
    BundleRevision bundleRevision = EasyMock.createMock(BundleRevision.class);
    EasyMock.expect(bundleRevision.getWiring()).andReturn(bundleWiring).anyTimes();
    EasyMock.replay(bundleRevision);
    Bundle providerBundle = EasyMock.createMock(Bundle.class);
    String bsn = subdir;
    int idx = bsn.indexOf('_');
    if (idx > 0) {
        bsn = bsn.substring(0, idx);
    }
    EasyMock.expect(providerBundle.getSymbolicName()).andReturn(bsn).anyTimes();
    EasyMock.expect(providerBundle.getBundleId()).andReturn(id).anyTimes();
    EasyMock.expect(providerBundle.getBundleContext()).andReturn(bc).anyTimes();
    EasyMock.expect(providerBundle.getVersion()).andReturn(version).anyTimes();
    EasyMock.expect(providerBundle.adapt(BundleRevision.class)).andReturn(bundleRevision).anyTimes();
    EasyMock.<Class<?>>expect(providerBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() {

        @Override
        public Class<?> answer() throws Throwable {
            String name = (String) EasyMock.getCurrentArguments()[0];
            if (!classNames.contains(name)) {
                throw new ClassCastException(name);
            }
            return cl.loadClass(name);
        }
    }).anyTimes();
    EasyMock.replay(providerBundle);
    return providerBundle;
}
Also used : Bundle(org.osgi.framework.Bundle) BundleWiring(org.osgi.framework.wiring.BundleWiring) ArrayList(java.util.ArrayList) URL(java.net.URL) IAnswer(org.easymock.IAnswer) BundleRevision(org.osgi.framework.wiring.BundleRevision) URLClassLoader(java.net.URLClassLoader) WovenClass(org.osgi.framework.hooks.weaving.WovenClass) File(java.io.File) BundleContext(org.osgi.framework.BundleContext)

Example 27 with IAnswer

use of org.easymock.IAnswer in project karaf by apache.

the class GuardProxyCatalogTest method testCreateProxy.

@SuppressWarnings({ "unchecked", "rawtypes" })
public Object testCreateProxy(BundleContext bc, Class[] objectClasses, final Class[] proxyRegClasses, Object testService, final Map<ServiceReference, Object> serviceMap) throws Exception {
    // A linked hash map to keep iteration order over the keys predictable
    final LinkedHashMap<String, Class> objClsMap = new LinkedHashMap<>();
    for (Class cls : objectClasses) {
        objClsMap.put(cls.getName(), cls);
    }
    // A linked hash map to keep iteration order over the keys predictable
    final LinkedHashMap<String, Class> proxyRegClsMap = new LinkedHashMap<>();
    for (Class cls : proxyRegClasses) {
        proxyRegClsMap.put(cls.getName(), cls);
    }
    // Create the object that is actually being tested here
    GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
    // The service being proxied has these properties
    long serviceID = Long.MAX_VALUE;
    final Hashtable<String, Object> serviceProps = new Hashtable<>();
    serviceProps.put(Constants.OBJECTCLASS, objClsMap.keySet().toArray(new String[] {}));
    serviceProps.put(Constants.SERVICE_ID, serviceID);
    // will be overwritten
    serviceProps.put(GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY, Arrays.asList("everyone"));
    serviceProps.put("bar", "foo");
    // The mock bundle context for the bundle providing the service is set up here
    BundleContext providerBC = EasyMock.createMock(BundleContext.class);
    // These are the expected service properties of the proxy registration. Note the proxy marker...
    final Hashtable<String, Object> expectedProxyProps = new Hashtable<>(serviceProps);
    expectedProxyProps.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE);
    // This will check that the right proxy is being registered.
    EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
        if (!runningUnderCoverage) {
            assertArrayEquals(proxyRegClsMap.keySet().toArray(new String[] {}), (String[]) EasyMock.getCurrentArguments()[0]);
            Object svc = EasyMock.getCurrentArguments()[1];
            assertTrue(svc instanceof ServiceFactory);
        }
        Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
        for (String key : expectedProxyProps.keySet()) {
            if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) {
                assertTrue("The roles property should have been overwritten", !Arrays.asList("everyone").equals(props.get(key)));
            } else {
                assertEquals(expectedProxyProps.get(key), props.get(key));
            }
        }
        ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
        ServiceReference sr = mockServiceReference(props);
        EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
        reg.unregister();
        EasyMock.expectLastCall().once();
        EasyMock.replay(reg);
        serviceMap.put(sr, EasyMock.getCurrentArguments()[1]);
        return reg;
    }).once();
    EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(() -> serviceMap.get(EasyMock.getCurrentArguments()[0])).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);
    // The mock bundle context for the client bundle
    BundleContext clientBC = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(clientBC.getService(sr)).andReturn(testService).anyTimes();
    EasyMock.replay(clientBC);
    // The mock bundle that consumes the service
    Bundle clientBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(clientBundle.getBundleId()).andReturn(2999L).anyTimes();
    EasyMock.expect(clientBundle.getBundleContext()).andReturn(clientBC).anyTimes();
    EasyMock.expect(clientBundle.loadClass(EasyMock.isA(String.class))).andAnswer((IAnswer) () -> objClsMap.get(EasyMock.getCurrentArguments()[0])).anyTimes();
    EasyMock.replay(clientBundle);
    assertEquals("Precondition", 0, gpc.proxyMap.size());
    assertEquals("Precondition", 0, gpc.createProxyQueue.size());
    // Create the proxy for the service
    gpc.proxyIfNotAlreadyProxied(sr);
    assertEquals(1, gpc.proxyMap.size());
    // The actual proxy creation is done asynchronously.
    GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
    assertNull("The registration shouldn't have happened yet", holder.registration);
    assertEquals(1, gpc.createProxyQueue.size());
    // Mimic the thread that works the queue to create the proxy
    GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
    ProxyManager pm = getProxyManager();
    runnable.run(pm);
    // The runnable should have put the actual registration in the holder
    ServiceReference<?> proxySR = holder.registration.getReference();
    for (String key : expectedProxyProps.keySet()) {
        if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) {
            assertTrue("The roles property should have been overwritten", !Arrays.asList("everyone").equals(proxySR.getProperty(key)));
        } else {
            assertEquals(expectedProxyProps.get(key), proxySR.getProperty(key));
        }
    }
    // Check that the proxy registration was done on the original provider bundle's context
    EasyMock.verify(providerBC);
    // Test that the actual proxy invokes the original service...
    ServiceFactory proxyServiceSF = (ServiceFactory) serviceMap.get(proxySR);
    Object proxyService = proxyServiceSF.getService(clientBundle, null);
    assertNotSame("The proxy should not be the same object as the original service", testService, proxyService);
    return proxyService;
}
Also used : Dictionary(java.util.Dictionary) ServiceFactory(org.osgi.framework.ServiceFactory) CreateProxyRunnable(org.apache.karaf.service.guard.impl.GuardProxyCatalog.CreateProxyRunnable) Hashtable(java.util.Hashtable) Bundle(org.osgi.framework.Bundle) ServiceRegistrationHolder(org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder) BundleWiring(org.osgi.framework.wiring.BundleWiring) ProxyManager(org.apache.aries.proxy.ProxyManager) AsmProxyManager(org.apache.aries.proxy.impl.AsmProxyManager) LinkedHashMap(java.util.LinkedHashMap) ServiceReference(org.osgi.framework.ServiceReference) IAnswer(org.easymock.IAnswer) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 28 with IAnswer

use of org.easymock.IAnswer 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(() -> {
            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)

Example 29 with IAnswer

use of org.easymock.IAnswer in project karaf by apache.

the class GuardProxyCatalogTest method testProxyCreationThread.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testProxyCreationThread() throws Exception {
    ProxyManager proxyManager = getProxyManager();
    ConfigurationAdmin ca = EasyMock.createMock(ConfigurationAdmin.class);
    EasyMock.expect(ca.listConfigurations(EasyMock.anyObject(String.class))).andReturn(null).anyTimes();
    EasyMock.replay(ca);
    ServiceReference pmSref = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(pmSref);
    ServiceReference pmSref2 = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(pmSref2);
    ServiceReference cmSref = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(cmSref);
    Bundle b = EasyMock.createMock(Bundle.class);
    EasyMock.expect(b.getBundleId()).andReturn(23992734L).anyTimes();
    EasyMock.replay(b);
    BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
    EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes();
    EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(() -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes();
    final ServiceListener[] pmListenerHolder = new ServiceListener[1];
    String pmFilter = "(&(objectClass=" + ProxyManager.class.getName() + ")" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))";
    bc.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.eq(pmFilter));
    EasyMock.expectLastCall().andAnswer(() -> {
        pmListenerHolder[0] = (ServiceListener) EasyMock.getCurrentArguments()[0];
        return null;
    }).anyTimes();
    EasyMock.expect(bc.getServiceReferences(EasyMock.anyObject(String.class), EasyMock.contains(ConfigurationAdmin.class.getName()))).andReturn(new ServiceReference[] { cmSref }).anyTimes();
    EasyMock.expect(bc.getService(pmSref)).andReturn(proxyManager).anyTimes();
    EasyMock.expect(bc.getService(pmSref2)).andReturn(proxyManager).anyTimes();
    EasyMock.expect(bc.getService(cmSref)).andReturn(ca).anyTimes();
    EasyMock.replay(bc);
    // This should put a ServiceListener in the pmListenerHolder, the ServiceTracker does that
    GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
    // The service being proxied has these properties
    final Hashtable<String, Object> serviceProps = new Hashtable<>();
    serviceProps.put(Constants.OBJECTCLASS, new String[] { TestServiceAPI.class.getName() });
    serviceProps.put(Constants.SERVICE_ID, 162L);
    final Map<ServiceReference<?>, Object> serviceMap = new HashMap<>();
    // The mock bundle context for the bundle providing the service is set up here
    BundleContext providerBC = EasyMock.createMock(BundleContext.class);
    // These are the expected service properties of the proxy registration. Note the proxy marker...
    final Hashtable<String, Object> expectedProxyProps = new Hashtable<>(serviceProps);
    expectedProxyProps.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE);
    EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
        Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
        ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
        ServiceReference sr = mockServiceReference(props);
        EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
        reg.unregister();
        EasyMock.expectLastCall().once();
        EasyMock.replay(reg);
        serviceMap.put(sr, EasyMock.getCurrentArguments()[1]);
        return reg;
    }).once();
    EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(() -> serviceMap.get(EasyMock.getCurrentArguments()[0])).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);
    assertEquals("Precondition", 0, gpc.proxyMap.size());
    assertEquals("Precondition", 0, gpc.createProxyQueue.size());
    // Create the proxy for the service
    gpc.proxyIfNotAlreadyProxied(sr);
    assertEquals(1, gpc.proxyMap.size());
    assertEquals(1, gpc.createProxyQueue.size());
    // The actual proxy creation is done asynchronously.
    GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(162L);
    assertNull("The registration shouldn't have happened yet", holder.registration);
    assertEquals(1, gpc.createProxyQueue.size());
    Thread[] tarray = new Thread[Thread.activeCount()];
    Thread.enumerate(tarray);
    for (Thread t : tarray) {
        if (t != null) {
            assertTrue(!GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME.equals(t.getName()));
        }
    }
    // make the proxy manager appear
    pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, pmSref));
    // give the system some time to send the events...
    Thread.sleep(400);
    Thread ourThread = null;
    Thread[] tarray2 = new Thread[Thread.activeCount()];
    Thread.enumerate(tarray2);
    for (Thread t : tarray2) {
        if (t != null) {
            if (t.getName().equals(GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME)) {
                ourThread = t;
            }
        }
    }
    assertNotNull(ourThread);
    assertTrue(ourThread.isDaemon());
    assertTrue(ourThread.isAlive());
    assertNotNull(holder.registration);
    assertEquals(0, gpc.createProxyQueue.size());
    int numProxyThreads = 0;
    pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, pmSref2));
    // give the system some time to send the events...
    Thread.sleep(300);
    Thread[] tarray3 = new Thread[Thread.activeCount()];
    Thread.enumerate(tarray3);
    for (Thread t : tarray3) {
        if (t != null) {
            if (t.getName().equals(GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME)) {
                numProxyThreads++;
            }
        }
    }
    assertEquals("Maximum 1 proxy thread, even if there is more than 1 proxy service", 1, numProxyThreads);
    // Clean up thread
    pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, pmSref));
    // Give the system some time to stop the threads...
    Thread.sleep(300);
    Thread[] tarray4 = new Thread[Thread.activeCount()];
    Thread.enumerate(tarray4);
    for (Thread t : tarray4) {
        if (t != null) {
            assertTrue(!GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME.equals(t.getName()));
        }
    }
}
Also used : Dictionary(java.util.Dictionary) ServiceListener(org.osgi.framework.ServiceListener) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ProxyManager(org.apache.aries.proxy.ProxyManager) AsmProxyManager(org.apache.aries.proxy.impl.AsmProxyManager) ServiceEvent(org.osgi.framework.ServiceEvent) ServiceRegistration(org.osgi.framework.ServiceRegistration) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ServiceRegistrationHolder(org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder) BundleWiring(org.osgi.framework.wiring.BundleWiring) ServiceReference(org.osgi.framework.ServiceReference) IAnswer(org.easymock.IAnswer) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 30 with IAnswer

use of org.easymock.IAnswer in project karaf by apache.

the class GuardProxyCatalogTest method testServiceFactoryBehaviour.

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testServiceFactoryBehaviour() throws Exception {
    final Map<ServiceReference, Object> serviceMap = new HashMap<>();
    TestServiceAPI testService = new TestService();
    BundleContext bc = mockConfigAdminBundleContext();
    GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
    // The service being proxied has these properties
    long serviceID = 117L;
    final Hashtable<String, Object> serviceProps = new Hashtable<>();
    serviceProps.put(Constants.OBJECTCLASS, new String[] { TestServiceAPI.class.getName() });
    serviceProps.put(Constants.SERVICE_ID, serviceID);
    serviceProps.put("bar", 42L);
    BundleContext providerBC = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
        Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
        ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
        ServiceReference sr = mockServiceReference(props);
        EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
        EasyMock.replay(reg);
        serviceMap.put(sr, EasyMock.getCurrentArguments()[1]);
        return reg;
    }).once();
    EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(() -> serviceMap.get(EasyMock.getCurrentArguments()[0])).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);
    // The mock bundle context for the client bundle
    BundleContext clientBC = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(clientBC.getService(sr)).andReturn(testService).anyTimes();
    EasyMock.replay(clientBC);
    // The mock bundle that consumes the service
    Bundle clientBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(clientBundle.getBundleContext()).andReturn(clientBC).anyTimes();
    EasyMock.replay(clientBundle);
    gpc.proxyIfNotAlreadyProxied(sr);
    // The actual proxy creation is done asynchronously.
    GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
    // Mimic the thread that works the queue to create the proxy
    GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
    assertEquals(117L, runnable.getOriginalServiceID());
    ProxyManager pm = getProxyManager();
    runnable.run(pm);
    // The runnable should have put the actual registration in the holder
    ServiceReference<?> proxySR = holder.registration.getReference();
    // Check that the proxy registration was done on the original provider bundle's context
    EasyMock.verify(providerBC);
    // Test that the actual proxy invokes the original service...
    ServiceFactory proxyServiceSF = (ServiceFactory) serviceMap.get(proxySR);
    TestServiceAPI proxyService = (TestServiceAPI) proxyServiceSF.getService(clientBundle, null);
    assertNotSame("The proxy should not be the same object as the original service", testService, proxyService);
    assertEquals("Doing it", proxyService.doit());
    EasyMock.reset(clientBC);
    EasyMock.expect(clientBC.ungetService(sr)).andReturn(true).once();
    EasyMock.replay(clientBC);
    proxyServiceSF.ungetService(clientBundle, null, proxyService);
    EasyMock.verify(clientBC);
}
Also used : Dictionary(java.util.Dictionary) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CreateProxyRunnable(org.apache.karaf.service.guard.impl.GuardProxyCatalog.CreateProxyRunnable) ServiceFactory(org.osgi.framework.ServiceFactory) Hashtable(java.util.Hashtable) Bundle(org.osgi.framework.Bundle) ServiceRegistrationHolder(org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder) BundleWiring(org.osgi.framework.wiring.BundleWiring) ProxyManager(org.apache.aries.proxy.ProxyManager) AsmProxyManager(org.apache.aries.proxy.impl.AsmProxyManager) ServiceReference(org.osgi.framework.ServiceReference) IAnswer(org.easymock.IAnswer) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Aggregations

IAnswer (org.easymock.IAnswer)31 Test (org.junit.Test)17 Bundle (org.osgi.framework.Bundle)11 BundleContext (org.osgi.framework.BundleContext)11 Hashtable (java.util.Hashtable)8 ArrayList (java.util.ArrayList)6 Dictionary (java.util.Dictionary)6 ServiceReference (org.osgi.framework.ServiceReference)6 BundleWiring (org.osgi.framework.wiring.BundleWiring)6 Firehose (io.druid.data.input.Firehose)5 InputRow (io.druid.data.input.InputRow)5 MapBasedInputRow (io.druid.data.input.MapBasedInputRow)5 URL (java.net.URL)5 URLClassLoader (java.net.URLClassLoader)5 HashMap (java.util.HashMap)5 ServiceRegistrationHolder (org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder)5 ServiceRegistration (org.osgi.framework.ServiceRegistration)5 CreateProxyRunnable (org.apache.karaf.service.guard.impl.GuardProxyCatalog.CreateProxyRunnable)4 LinkedHashMap (java.util.LinkedHashMap)3 ProxyManager (org.apache.aries.proxy.ProxyManager)3