Search in sources :

Example 26 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project aries by apache.

the class ComponentTest method testComponent.

@Test
public void testComponent() throws IOException {
    OSGi<?> program = configurations("org.components.MyComponent").flatMap(props -> services(Service.class).flatMap(ms -> just(new Component(props, ms)).flatMap(component -> register(Component.class, component, new HashMap<>()).distribute(ign -> dynamic(highestService(ServiceOptional.class), component::setOptional, c -> component.setOptional(null)), ign -> dynamic(services(ServiceForList.class), component::addService, component::removeService)))));
    ServiceTracker<Component, Component> serviceTracker = new ServiceTracker<>(_bundleContext, Component.class, null);
    serviceTracker.open();
    CountDownLatch countDownLatch = new CountDownLatch(1);
    _bundleContext.registerService(ManagedService.class, dictionary -> countDownLatch.countDown(), new Hashtable<String, Object>() {

        {
            put("service.pid", "org.components.MyComponent");
        }
    });
    Configuration factoryConfiguration = null;
    try (OSGiResult<?> run = program.run(_bundleContext)) {
        factoryConfiguration = _configurationAdmin.createFactoryConfiguration("org.components.MyComponent");
        factoryConfiguration.update(new Hashtable<>());
        countDownLatch.await(10, TimeUnit.SECONDS);
        assertNull(serviceTracker.getService());
        ServiceRegistration<Service> serviceRegistration = _bundleContext.registerService(Service.class, new Service(), new Hashtable<>());
        Component component = serviceTracker.waitForService(10 * 1000);
        assertNotNull(component);
        assertNull(component.getOptional());
        ServiceRegistration<ServiceOptional> serviceRegistration2 = _bundleContext.registerService(ServiceOptional.class, new ServiceOptional(), new Hashtable<>());
        Thread.sleep(1000L);
        assertNotNull(component.getOptional());
        ServiceOptional serviceOptional = new ServiceOptional();
        ServiceRegistration<ServiceOptional> serviceRegistration3 = _bundleContext.registerService(ServiceOptional.class, serviceOptional, new Hashtable<String, Object>() {

            {
                put("service.ranking", 1);
            }
        });
        assertEquals(serviceOptional, component.getOptional());
        serviceRegistration3.unregister();
        assertNotNull(component.getOptional());
        serviceRegistration2.unregister();
        assertNull(component.getOptional());
        ServiceRegistration<ServiceForList> serviceRegistration4 = _bundleContext.registerService(ServiceForList.class, new ServiceForList(), new Hashtable<>());
        ServiceRegistration<ServiceForList> serviceRegistration5 = _bundleContext.registerService(ServiceForList.class, new ServiceForList(), new Hashtable<>());
        assertEquals(2, component.getServiceForLists().size());
        serviceRegistration4.unregister();
        assertEquals(1, component.getServiceForLists().size());
        serviceRegistration5.unregister();
        assertEquals(0, component.getServiceForLists().size());
        serviceRegistration.unregister();
        assertNull(serviceTracker.getService());
    } catch (IOException ioe) {
    } catch (InterruptedException e) {
        Assert.fail("Timeout waiting for configuration");
    } finally {
        serviceTracker.close();
        if (factoryConfiguration != null) {
            factoryConfiguration.delete();
        }
    }
}
Also used : OSGi.configurations(org.apache.aries.osgi.functional.OSGi.configurations) BeforeClass(org.junit.BeforeClass) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) OSGi.onClose(org.apache.aries.osgi.functional.OSGi.onClose) ArrayList(java.util.ArrayList) OSGi.register(org.apache.aries.osgi.functional.OSGi.register) HighestRankingRouter.highest(org.apache.aries.osgi.functional.test.HighestRankingRouter.highest) Configuration(org.osgi.service.cm.Configuration) OSGi.apply(org.apache.aries.osgi.functional.OSGi.apply) ServiceReference(org.osgi.framework.ServiceReference) Hashtable(java.util.Hashtable) ServiceRegistration(org.osgi.framework.ServiceRegistration) AfterClass(org.junit.AfterClass) Assert.assertNotNull(org.junit.Assert.assertNotNull) Test(org.junit.Test) IOException(java.io.IOException) BundleContext(org.osgi.framework.BundleContext) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) OSGi.just(org.apache.aries.osgi.functional.OSGi.just) Assert.assertNull(org.junit.Assert.assertNull) OSGi.services(org.apache.aries.osgi.functional.OSGi.services) ServiceTracker(org.osgi.util.tracker.ServiceTracker) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) OSGi(org.apache.aries.osgi.functional.OSGi) ManagedService(org.osgi.service.cm.ManagedService) Assert(org.junit.Assert) OSGi.bundleContext(org.apache.aries.osgi.functional.OSGi.bundleContext) FrameworkUtil(org.osgi.framework.FrameworkUtil) OSGiResult(org.apache.aries.osgi.functional.OSGiResult) Dictionary(java.util.Dictionary) Assert.assertEquals(org.junit.Assert.assertEquals) Configuration(org.osgi.service.cm.Configuration) ServiceTracker(org.osgi.util.tracker.ServiceTracker) ManagedService(org.osgi.service.cm.ManagedService) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 27 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project aries by apache.

the class DSLTest method testConfigurationsAndRegistrations.

@Test
public void testConfigurationsAndRegistrations() throws InvalidSyntaxException, IOException, InterruptedException {
    ServiceReference<ConfigurationAdmin> serviceReference = bundleContext.getServiceReference(ConfigurationAdmin.class);
    ConfigurationAdmin configurationAdmin = bundleContext.getService(serviceReference);
    /*  For each factory configuration register a service with the property
            key set to the value of the property key that comes with the
            configuration */
    OSGi<ServiceRegistration<Service>> program = configurations("test.configuration").map(d -> d.get("key")).flatMap(key -> register(Service.class, new Service(), new HashMap<String, Object>() {

        {
            put("key", key);
        }
    }));
    OSGiResult<ServiceRegistration<Service>> result = program.run(bundleContext);
    assertEquals(0, bundleContext.getServiceReferences(Service.class, "(test.configuration=*)").size());
    CountDownLatch addedLatch = new CountDownLatch(3);
    ServiceRegistration<?> addedServiceRegistration = bundleContext.registerService(ManagedServiceFactory.class, new ManagedServiceFactory() {

        @Override
        public String getName() {
            return "";
        }

        @Override
        public void updated(String s, Dictionary<String, ?> dictionary) throws ConfigurationException {
            addedLatch.countDown();
        }

        @Override
        public void deleted(String s) {
        }
    }, new Hashtable<String, Object>() {

        {
            put("service.pid", "test.configuration");
        }
    });
    CountDownLatch deletedLatch = new CountDownLatch(3);
    ServiceRegistration<?> deletedServiceRegistration = bundleContext.registerService(ManagedServiceFactory.class, new ManagedServiceFactory() {

        @Override
        public String getName() {
            return "";
        }

        @Override
        public void updated(String s, Dictionary<String, ?> dictionary) throws ConfigurationException {
        }

        @Override
        public void deleted(String s) {
            deletedLatch.countDown();
        }
    }, new Hashtable<String, Object>() {

        {
            put("service.pid", "test.configuration");
        }
    });
    Configuration configuration = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration.update(new Hashtable<String, Object>() {

        {
            put("key", "service one");
        }
    });
    Configuration configuration2 = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration2.update(new Hashtable<String, Object>() {

        {
            put("key", "service two");
        }
    });
    Configuration configuration3 = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration3.update(new Hashtable<String, Object>() {

        {
            put("key", "service three");
        }
    });
    assertTrue(addedLatch.await(10, TimeUnit.SECONDS));
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service one)").size());
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service two)").size());
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service three)").size());
    configuration3.delete();
    configuration2.delete();
    configuration.delete();
    assertTrue(deletedLatch.await(10, TimeUnit.SECONDS));
    assertEquals(0, bundleContext.getServiceReferences(Service.class, "(test.configuration=*)").size());
    addedServiceRegistration.unregister();
    deletedServiceRegistration.unregister();
    result.close();
    bundleContext.ungetService(serviceReference);
}
Also used : OSGi.configurations(org.apache.aries.osgi.functional.OSGi.configurations) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) OSGi.onClose(org.apache.aries.osgi.functional.OSGi.onClose) OSGi.register(org.apache.aries.osgi.functional.OSGi.register) HighestRankingRouter.highest(org.apache.aries.osgi.functional.test.HighestRankingRouter.highest) Configuration(org.osgi.service.cm.Configuration) ConfigurationException(org.osgi.service.cm.ConfigurationException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) OSGi.configuration(org.apache.aries.osgi.functional.OSGi.configuration) ServiceReference(org.osgi.framework.ServiceReference) Hashtable(java.util.Hashtable) ServiceRegistration(org.osgi.framework.ServiceRegistration) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) OSGi.serviceReferences(org.apache.aries.osgi.functional.OSGi.serviceReferences) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) BundleContext(org.osgi.framework.BundleContext) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) OSGi.just(org.apache.aries.osgi.functional.OSGi.just) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) OSGi.services(org.apache.aries.osgi.functional.OSGi.services) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) OSGi(org.apache.aries.osgi.functional.OSGi) FrameworkUtil(org.osgi.framework.FrameworkUtil) OSGiResult(org.apache.aries.osgi.functional.OSGiResult) Dictionary(java.util.Dictionary) Assert.assertEquals(org.junit.Assert.assertEquals) Configuration(org.osgi.service.cm.Configuration) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) ConfigurationException(org.osgi.service.cm.ConfigurationException) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Example 28 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project jackrabbit-oak by apache.

the class OsgiWhiteboard method register.

@Override
public <T> Registration register(final Class<T> type, final T service, Map<?, ?> properties) {
    checkNotNull(type);
    checkNotNull(service);
    checkNotNull(properties);
    checkArgument(type.isInstance(service));
    Dictionary<Object, Object> dictionary = new Hashtable<Object, Object>();
    for (Map.Entry<?, ?> entry : properties.entrySet()) {
        dictionary.put(entry.getKey(), entry.getValue());
    }
    final ServiceRegistration registration = context.registerService(type.getName(), service, dictionary);
    return new Registration() {

        private volatile boolean unregistered;

        @Override
        public void unregister() {
            try {
                if (!unregistered) {
                    registration.unregister();
                    unregistered = true;
                } else {
                    log.warn("Service {} of type {} unregistered multiple times", service, type);
                }
            } catch (IllegalStateException ex) {
                log.warn("Error unregistering service: {} of type {}", service, type.getName(), ex);
            }
        }
    };
}
Also used : Hashtable(java.util.Hashtable) ServiceRegistration(org.osgi.framework.ServiceRegistration) Registration(org.apache.jackrabbit.oak.spi.whiteboard.Registration) Map(java.util.Map) Maps.newTreeMap(com.google.common.collect.Maps.newTreeMap) Maps.newHashMap(com.google.common.collect.Maps.newHashMap) SortedMap(java.util.SortedMap) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 29 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project jackrabbit-oak by apache.

the class BaseDocumentDiscoveryLiteServiceTest method createInstance.

SimplifiedInstance createInstance(DocumentNodeStore ns, String workingDir) throws NoSuchFieldException {
    DocumentDiscoveryLiteService discoveryLite = new DocumentDiscoveryLiteService();
    PrivateAccessor.setField(discoveryLite, "nodeStore", ns);
    BundleContext bc = mock(BundleContext.class);
    ComponentContext c = mock(ComponentContext.class);
    when(c.getBundleContext()).thenReturn(bc);
    final Map<String, Object> registeredServices = new HashMap<String, Object>();
    when(bc.registerService(anyString(), anyObject(), (Properties) anyObject())).then(new Answer<ServiceRegistration>() {

        @Override
        public ServiceRegistration answer(InvocationOnMock invocation) {
            registeredServices.put((String) invocation.getArguments()[0], invocation.getArguments()[1]);
            return null;
        }
    });
    discoveryLite.activate(c);
    Descriptors d = (Descriptors) registeredServices.get(Descriptors.class.getName());
    final SimplifiedInstance result = new SimplifiedInstance(discoveryLite, ns, d, registeredServices, 500, workingDir);
    allInstances.add(result);
    logger.info("Created " + result);
    return result;
}
Also used : ComponentContext(org.osgi.service.component.ComponentContext) HashMap(java.util.HashMap) Matchers.anyString(org.mockito.Matchers.anyString) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyObject(org.mockito.Matchers.anyObject) JsonObject(org.apache.jackrabbit.oak.commons.json.JsonObject) Descriptors(org.apache.jackrabbit.oak.api.Descriptors) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 30 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project jackrabbit-oak by apache.

the class ExternalPrincipalConfigurationTest method testRemoveSyncHandler.

@Test
public void testRemoveSyncHandler() throws Exception {
    Dictionary<String, Object> enableProps = new Hashtable(ImmutableMap.<String, Object>of(DefaultSyncConfigImpl.PARAM_USER_DYNAMIC_MEMBERSHIP, true));
    Dictionary<String, Object> disableProps = new Hashtable(ImmutableMap.<String, Object>of(DefaultSyncConfigImpl.PARAM_USER_DYNAMIC_MEMBERSHIP, false));
    DefaultSyncHandler sh = new DefaultSyncHandler();
    BundleContext bundleContext = context.bundleContext();
    ServiceRegistration registration1 = bundleContext.registerService(SyncHandler.class.getName(), sh, enableProps);
    ServiceRegistration registration2 = bundleContext.registerService(SyncHandler.class.getName(), sh, enableProps);
    ServiceRegistration registration3 = bundleContext.registerService(SyncHandler.class.getName(), sh, disableProps);
    assertIsEnabled(principalConfiguration, true);
    registration2.unregister();
    assertIsEnabled(principalConfiguration, true);
    registration1.unregister();
    assertIsEnabled(principalConfiguration, false);
    registration3.unregister();
    assertIsEnabled(principalConfiguration, false);
}
Also used : SyncHandler(org.apache.jackrabbit.oak.spi.security.authentication.external.SyncHandler) DefaultSyncHandler(org.apache.jackrabbit.oak.spi.security.authentication.external.impl.DefaultSyncHandler) Hashtable(java.util.Hashtable) DefaultSyncHandler(org.apache.jackrabbit.oak.spi.security.authentication.external.impl.DefaultSyncHandler) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration) AbstractExternalAuthTest(org.apache.jackrabbit.oak.spi.security.authentication.external.AbstractExternalAuthTest) Test(org.junit.Test)

Aggregations

ServiceRegistration (org.osgi.framework.ServiceRegistration)188 Test (org.junit.Test)80 Hashtable (java.util.Hashtable)61 BundleContext (org.osgi.framework.BundleContext)35 Bundle (org.osgi.framework.Bundle)26 Dictionary (java.util.Dictionary)23 Properties (java.util.Properties)22 HashMap (java.util.HashMap)21 ServiceReference (org.osgi.framework.ServiceReference)21 ArrayList (java.util.ArrayList)18 Map (java.util.Map)13 IOException (java.io.IOException)8 ServiceFactory (org.osgi.framework.ServiceFactory)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 URL (java.net.URL)6 HashSet (java.util.HashSet)6 List (java.util.List)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 ObjectName (javax.management.ObjectName)5 InitialContext (javax.naming.InitialContext)5