Search in sources :

Example 31 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin 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 32 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project aries by apache.

the class DSLTest method testConfigurations.

@Test
public void testConfigurations() throws IOException, InterruptedException {
    ServiceReference<ConfigurationAdmin> serviceReference = bundleContext.getServiceReference(ConfigurationAdmin.class);
    ConfigurationAdmin configurationAdmin = bundleContext.getService(serviceReference);
    AtomicReference<Dictionary<?, ?>> atomicReference = new AtomicReference<>(null);
    CountDownLatch countDownLatch = new CountDownLatch(1);
    Configuration configuration = null;
    try (OSGiResult<Dictionary<String, ?>> result = configurations("test.configuration").run(bundleContext, x -> {
        atomicReference.set(x);
        countDownLatch.countDown();
    })) {
        assertNull(atomicReference.get());
        configuration = configurationAdmin.createFactoryConfiguration("test.configuration");
        configuration.update(new Hashtable<>());
        countDownLatch.await(10, TimeUnit.SECONDS);
        assertNotNull(atomicReference.get());
    } finally {
        bundleContext.ungetService(serviceReference);
        if (configuration != null) {
            configuration.delete();
        }
    }
}
Also used : Dictionary(java.util.Dictionary) Configuration(org.osgi.service.cm.Configuration) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) Test(org.junit.Test)

Example 33 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project camel by apache.

the class CamelBlueprintTestSupport method createBundleContext.

@SuppressWarnings({ "rawtypes", "unchecked" })
protected BundleContext createBundleContext() throws Exception {
    System.setProperty("org.apache.aries.blueprint.synchronous", Boolean.toString(!useAsynchronousBlueprintStartup()));
    // load configuration file
    String[] file = loadConfigAdminConfigurationFile();
    String[][] configAdminPidFiles = new String[0][0];
    if (file != null) {
        if (file.length % 2 != 0) {
            // This needs to return pairs of filename and pid
            throw new IllegalArgumentException("The length of the String[] returned from loadConfigAdminConfigurationFile must divisible by 2, was " + file.length);
        }
        configAdminPidFiles = new String[file.length / 2][2];
        int pair = 0;
        for (int i = 0; i < file.length; i += 2) {
            String fileName = file[i];
            String pid = file[i + 1];
            if (!new File(fileName).exists()) {
                throw new IllegalArgumentException("The provided file \"" + fileName + "\" from loadConfigAdminConfigurationFile doesn't exist");
            }
            configAdminPidFiles[pair][0] = fileName;
            configAdminPidFiles[pair][1] = pid;
            pair++;
        }
    }
    // fetch initial configadmin configuration if provided programmatically
    Properties initialConfiguration = new Properties();
    String pid = setConfigAdminInitialConfiguration(initialConfiguration);
    if (pid != null) {
        configAdminPidFiles = new String[][] { { prepareInitialConfigFile(initialConfiguration), pid } };
    }
    final String symbolicName = getClass().getSimpleName();
    final BundleContext answer = CamelBlueprintHelper.createBundleContext(symbolicName, getBlueprintDescriptor(), includeTestBundle(), getBundleFilter(), getBundleVersion(), getBundleDirectives(), configAdminPidFiles);
    boolean expectReload = expectBlueprintContainerReloadOnConfigAdminUpdate();
    // must register override properties early in OSGi containers
    Properties extra = useOverridePropertiesWithPropertiesComponent();
    if (extra != null) {
        answer.registerService(PropertiesComponent.OVERRIDE_PROPERTIES, extra, null);
    }
    Map<String, KeyValueHolder<Object, Dictionary>> map = new LinkedHashMap<String, KeyValueHolder<Object, Dictionary>>();
    addServicesOnStartup(map);
    List<KeyValueHolder<String, KeyValueHolder<Object, Dictionary>>> servicesList = new LinkedList<KeyValueHolder<String, KeyValueHolder<Object, Dictionary>>>();
    for (Map.Entry<String, KeyValueHolder<Object, Dictionary>> entry : map.entrySet()) {
        servicesList.add(asKeyValueService(entry.getKey(), entry.getValue().getKey(), entry.getValue().getValue()));
    }
    addServicesOnStartup(servicesList);
    for (KeyValueHolder<String, KeyValueHolder<Object, Dictionary>> item : servicesList) {
        String clazz = item.getKey();
        Object service = item.getValue().getKey();
        Dictionary dict = item.getValue().getValue();
        log.debug("Registering service {} -> {}", clazz, service);
        ServiceRegistration<?> reg = answer.registerService(clazz, service, dict);
        if (reg != null) {
            services.add(reg);
        }
    }
    // if blueprint XML uses <cm:property-placeholder> (any update-strategy and any default properties)
    // - org.apache.aries.blueprint.compendium.cm.ManagedObjectManager.register() is called
    // - ManagedServiceUpdate is scheduled in felix.cm
    // - org.apache.felix.cm.impl.ConfigurationImpl.setDynamicBundleLocation() is called
    // - CM_LOCATION_CHANGED event is fired
    // - if BP was alredy created, it's <cm:property-placeholder> receives the event and
    // - org.apache.aries.blueprint.compendium.cm.CmPropertyPlaceholder.updated() is called,
    //   but no BP reload occurs
    // we will however wait for BP container of the test bundle to become CREATED for the first time
    // each configadmin update *may* lead to reload of BP container, if it uses <cm:property-placeholder>
    // with update-strategy="reload"
    // we will gather timestamps of BP events. We don't want to be fooled but repeated events related
    // to the same state of BP container
    Set<Long> bpEvents = new HashSet<>();
    CamelBlueprintHelper.waitForBlueprintContainer(bpEvents, answer, symbolicName, BlueprintEvent.CREATED, null);
    // must reuse props as we can do both load from .cfg file and override afterwards
    final Dictionary props = new Properties();
    // allow end user to override properties
    pid = useOverridePropertiesWithConfigAdmin(props);
    if (pid != null) {
        // we will update the configuration again
        ConfigurationAdmin configAdmin = CamelBlueprintHelper.getOsgiService(answer, ConfigurationAdmin.class);
        // passing null as second argument ties the configuration to correct bundle.
        // using single-arg method causes:
        // *ERROR* Cannot use configuration xxx.properties for [org.osgi.service.cm.ManagedService, id=N, bundle=N/jar:file:xyz.jar!/]: No visibility to configuration bound to felix-connect
        final Configuration config = configAdmin.getConfiguration(pid, null);
        if (config == null) {
            throw new IllegalArgumentException("Cannot find configuration with pid " + pid + " in OSGi ConfigurationAdmin service.");
        }
        // lets merge configurations
        Dictionary<String, Object> currentProperties = config.getProperties();
        final Dictionary newProps = new Properties();
        if (currentProperties == null) {
            currentProperties = newProps;
        }
        for (Enumeration<String> ek = currentProperties.keys(); ek.hasMoreElements(); ) {
            String k = ek.nextElement();
            newProps.put(k, currentProperties.get(k));
        }
        for (String p : ((Properties) props).stringPropertyNames()) {
            newProps.put(p, ((Properties) props).getProperty(p));
        }
        log.info("Updating ConfigAdmin {} by overriding properties {}", config, newProps);
        if (expectReload) {
            CamelBlueprintHelper.waitForBlueprintContainer(bpEvents, answer, symbolicName, BlueprintEvent.CREATED, new Runnable() {

                @Override
                public void run() {
                    try {
                        config.update(newProps);
                    } catch (IOException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            });
        } else {
            config.update(newProps);
        }
    }
    return answer;
}
Also used : Dictionary(java.util.Dictionary) Configuration(org.osgi.service.cm.Configuration) Properties(java.util.Properties) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) KeyValueHolder(org.apache.camel.util.KeyValueHolder) IOException(java.io.IOException) LinkedList(java.util.LinkedList) File(java.io.File) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) BundleContext(org.osgi.framework.BundleContext)

Example 34 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project camel by apache.

the class AbstractFeatureTest method overridePropertiesWithConfigAdmin.

protected void overridePropertiesWithConfigAdmin(String pid, Properties props) throws IOException {
    ConfigurationAdmin configAdmin = getOsgiService(bundleContext, ConfigurationAdmin.class);
    // passing null as second argument ties the configuration to correct bundle.
    Configuration config = configAdmin.getConfiguration(pid, null);
    if (config == null) {
        throw new IllegalArgumentException("Cannot find configuration with pid " + pid + " in OSGi ConfigurationAdmin service.");
    }
    // let's merge configurations
    Dictionary<String, Object> currentProperties = config.getProperties();
    Dictionary newProps = new Properties();
    if (currentProperties == null) {
        currentProperties = newProps;
    }
    for (Enumeration<String> ek = currentProperties.keys(); ek.hasMoreElements(); ) {
        String k = ek.nextElement();
        newProps.put(k, currentProperties.get(k));
    }
    for (String p : props.stringPropertyNames()) {
        newProps.put(p, props.getProperty(p));
    }
    LOG.info("Updating ConfigAdmin {} by overriding properties {}", config, newProps);
    config.update(newProps);
}
Also used : Dictionary(java.util.Dictionary) Configuration(org.osgi.service.cm.Configuration) Properties(java.util.Properties) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin)

Example 35 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project felix by apache.

the class TestDynamicPropsReconfiguration method testReconfigurationUsingManagedService.

@Test
public void testReconfigurationUsingManagedService() throws IOException, InterruptedException {
    ServiceReference sr = ipojoHelper.getServiceReferenceByName(FooService.class.getName(), "FooProvider-3");
    assertNotNull("Check the availability of the FS service", sr);
    // Check service properties
    Integer intProp = (Integer) sr.getProperty("int");
    Boolean boolProp = (Boolean) sr.getProperty("boolean");
    String strProp = (String) sr.getProperty("string");
    String[] strAProp = (String[]) sr.getProperty("strAProp");
    int[] intAProp = (int[]) sr.getProperty("intAProp");
    assertEquals("Check intProp equality", intProp, new Integer(0));
    assertEquals("Check longProp equality", boolProp, Boolean.TRUE);
    assertEquals("Check strProp equality", strProp, "");
    assertNotNull("Check strAProp not nullity", strAProp);
    String[] v = new String[0];
    for (int i = 0; i < strAProp.length; i++) {
        if (!strAProp[i].equals(v[i])) {
            fail("Check the strAProp Equality");
        }
    }
    assertNotNull("Check intAProp not nullity", intAProp);
    int[] v2 = new int[0];
    for (int i = 0; i < intAProp.length; i++) {
        if (intAProp[i] != v2[i]) {
            fail("Check the intAProp Equality");
        }
    }
    // Reconfiguration
    ConfigurationAdmin admin = osgiHelper.getServiceObject(ConfigurationAdmin.class);
    Configuration configuration = admin.getConfiguration("FooProvider-3", "?");
    Dictionary<String, Object> p3 = new Hashtable<String, Object>();
    p3.put("int", 1);
    p3.put("boolean", true);
    p3.put("string", "foo");
    p3.put("strAProp", new String[] { "foo", "bar", "baz" });
    p3.put("intAProp", new int[] { 1, 2, 3 });
    configuration.update(p3);
    TimeUtils.grace(200);
    sr = ipojoHelper.getServiceReferenceByName(FooService.class.getName(), "FooProvider-3");
    assertNotNull("Check the availability of the FS service", sr);
    // Check service properties
    intProp = (Integer) sr.getProperty("int");
    boolProp = (Boolean) sr.getProperty("boolean");
    strProp = (String) sr.getProperty("string");
    strAProp = (String[]) sr.getProperty("strAProp");
    intAProp = (int[]) sr.getProperty("intAProp");
    assertEquals("Check intProp equality", intProp, new Integer(1));
    assertEquals("Check longProp equality", boolProp, Boolean.TRUE);
    assertEquals("Check strProp equality", strProp, "foo");
    assertNotNull("Check strAProp not nullity", strAProp);
    v = new String[] { "foo", "bar", "baz" };
    for (int i = 0; i < strAProp.length; i++) {
        if (!strAProp[i].equals(v[i])) {
            fail("Check the strAProp Equality");
        }
    }
    assertNotNull("Check intAProp not nullity", intAProp);
    v2 = new int[] { 1, 2, 3 };
    for (int i = 0; i < intAProp.length; i++) {
        if (intAProp[i] != v2[i]) {
            fail("Check the intAProp Equality");
        }
    }
    // Invoke
    FooService fs = (FooService) osgiHelper.getRawServiceObject(sr);
    assertTrue("invoke fs", fs.foo());
    // Re-check the property (change)
    intProp = (Integer) sr.getProperty("int");
    boolProp = (Boolean) sr.getProperty("boolean");
    strProp = (String) sr.getProperty("string");
    strAProp = (String[]) sr.getProperty("strAProp");
    intAProp = (int[]) sr.getProperty("intAProp");
    assertEquals("Check intProp equality", intProp, new Integer(2));
    assertEquals("Check longProp equality", boolProp, Boolean.TRUE);
    assertEquals("Check strProp equality", strProp, "foo");
    assertNotNull("Check strAProp not nullity", strAProp);
    v = new String[] { "foo", "bar" };
    for (int i = 0; i < strAProp.length; i++) {
        if (!strAProp[i].equals(v[i])) {
            fail("Check the strAProp Equality");
        }
    }
    assertNull("Check intAProp hiding (no value)", intAProp);
    // Reconfiguration
    p3 = new Hashtable<String, Object>();
    p3.put("int", 1);
    p3.put("boolean", true);
    p3.put("string", "foo");
    p3.put("strAProp", new String[] { "foo", "bar", "baz" });
    p3.put("intAProp", new int[] { 1, 2, 3 });
    configuration.update(p3);
    TimeUtils.grace(200);
    sr = ipojoHelper.getServiceReferenceByName(FooService.class.getName(), "FooProvider-3");
    assertNotNull("Check the availability of the FS service", sr);
    // Check service properties
    intProp = (Integer) sr.getProperty("int");
    boolProp = (Boolean) sr.getProperty("boolean");
    strProp = (String) sr.getProperty("string");
    strAProp = (String[]) sr.getProperty("strAProp");
    intAProp = (int[]) sr.getProperty("intAProp");
    assertEquals("Check intProp equality", intProp, new Integer(1));
    assertEquals("Check longProp equality", boolProp, Boolean.TRUE);
    assertEquals("Check strProp equality", strProp, "foo");
    assertNotNull("Check strAProp not nullity", strAProp);
    v = new String[] { "foo", "bar", "baz" };
    for (int i = 0; i < strAProp.length; i++) {
        if (!strAProp[i].equals(v[i])) {
            fail("Check the strAProp Equality");
        }
    }
    assertNotNull("Check intAProp not nullity", intAProp);
    v2 = new int[] { 1, 2, 3 };
    for (int i = 0; i < intAProp.length; i++) {
        if (intAProp[i] != v2[i]) {
            fail("Check the intAProp Equality");
        }
    }
}
Also used : Configuration(org.osgi.service.cm.Configuration) Hashtable(java.util.Hashtable) ServiceReference(org.osgi.framework.ServiceReference) FooService(org.apache.felix.ipojo.runtime.core.services.FooService) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) Test(org.junit.Test)

Aggregations

ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)211 Configuration (org.osgi.service.cm.Configuration)114 Test (org.junit.Test)65 Hashtable (java.util.Hashtable)57 ServiceReference (org.osgi.framework.ServiceReference)52 IOException (java.io.IOException)44 FooService (org.apache.felix.ipojo.runtime.core.services.FooService)25 BundleContext (org.osgi.framework.BundleContext)25 Subject (javax.security.auth.Subject)24 Dictionary (java.util.Dictionary)23 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)21 Bundle (org.osgi.framework.Bundle)16 Properties (java.util.Properties)15 File (java.io.File)8 HashSet (java.util.HashSet)7 BundleException (org.osgi.framework.BundleException)7 Method (java.lang.reflect.Method)6 ObjectName (javax.management.ObjectName)5 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4