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);
}
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();
}
}
}
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;
}
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);
}
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");
}
}
}
Aggregations