/** * Set the values of an OSGi configuration for a given PID. * * @param pid The PID of the OSGi component to update * @param properties The properties and values of the config to update * @return true if the properties were updated successfully */ public boolean setProperties(final String pid, final Map<String, Object> properties) { try { Configuration conf = configAdmin.getConfiguration(pid); @SuppressWarnings("unchecked") Dictionary<String, Object> props = conf.getProperties(); if (props == null) { props = new Hashtable<String, Object>(); } /* props is of type org.apache.felix.cm.impl.CaseInsensitiveDictionary which * contains an internal HashTable and doesn't contain a putAll(Map) method. * Iterate over the map and put the values into the Dictionary individually. * Remove null values from HashMap as HashTable doesn't support them. */ for (Map.Entry<String, Object> entry : properties.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); props.put(key, value != null ? value : StringUtils.EMPTY); } conf.update(props); } catch (IOException e) { LOGGER.error("Could not set property", e); return false; } return true; }
@Override public Resource create(Request request) throws IllegalActionOnResourceException { String pid = request.get(PID, String.class); String factoryPid = request.get(FACTORY_PID, String.class); Configuration configuration = null; String location = request.get(BUNDLE_LOCATION, String.class); if (location != null) { if (pid != null) { try { configuration = m_configAdmin.getConfiguration(pid, location); } catch (IOException e) { throw new IllegalActionOnResourceException(request, e.getMessage()); } } else if (factoryPid != null) { try { configuration = m_configAdmin.createFactoryConfiguration(factoryPid, location); } catch (IOException e) { throw new IllegalActionOnResourceException(request, e.getMessage()); } } else { throw new IllegalActionOnResourceException( request, "factory pid or pid parameter is mandatory"); } } else { throw new IllegalActionOnResourceException(request, "location parameter is mandatory"); } ConfigurationResource configurationResource = new ConfigurationResource(configuration); synchronized (m_configurationResourceMap) { m_configurationResourceMap.put(pid, configurationResource); } return configurationResource; }
@Test public void testConfigurationEventAdded() throws Exception { String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "test123"; Configuration conf = EasyMock.createMock(Configuration.class); EasyMock.expect(conf.getPid()).andReturn(testPid).anyTimes(); EasyMock.replay(conf); ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class); EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes(); EasyMock.expect(cm.getConfiguration(testPid)).andReturn(conf).anyTimes(); EasyMock.replay(cm); final List<String> generateCalled = new ArrayList<String>(); SecuredCommandConfigTransformer scct = new SecuredCommandConfigTransformer() { @Override void generateServiceGuardConfig(Configuration config) throws IOException { generateCalled.add(config.getPid()); } }; scct.setConfigAdmin(cm); scct.init(); @SuppressWarnings("unchecked") ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class); EasyMock.replay(cmRef); ConfigurationEvent event = new ConfigurationEvent(cmRef, ConfigurationEvent.CM_UPDATED, null, testPid); assertEquals("Precondition", 0, generateCalled.size()); scct.configurationEvent(event); assertEquals(1, generateCalled.size()); assertEquals(testPid, generateCalled.iterator().next()); }
private void pushKeyValue(String key, String value) { ServiceReference<?> reference = Activator.getContext().getServiceReference(ConfigurationAdmin.class.getName()); if (reference != null) { ConfigurationAdmin service = (ConfigurationAdmin) Activator.getContext().getService(reference); if (service != null) { try { Configuration configuration = service.getConfiguration("PrettyPrinterConfigurator"); if (configuration != null) { Dictionary<String, Object> properties = configuration.getProperties(); if (properties == null) properties = new Hashtable<String, Object>(); properties.put(key, value); configuration.update(properties); configuration.update(); } else { System.out.println("configuration (PrettyPrinterConfigurator) bulunamadi"); } } catch (IOException e) { System.out.println("hata olustu: "); e.printStackTrace(System.out); } } else { System.out.println("ConfigurationAdmin servisini bulamadim."); } } else { System.out.println("ConfigurationAdmin servisine ait bir referans bulamadim."); } }
private void loggingDeactivate(final ConfigurationAdmin configAdmin) throws Exception { final org.osgi.service.cm.Configuration config = configAdmin.getConfiguration(PAX_PID, null); config.delete(); Thread.sleep(500); }
@SuppressWarnings({"unchecked", "rawtypes"}) private static void processConfigFile(File configFile) throws IOException, FileNotFoundException { if (configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) { logger.debug("Ignoring file '{}'", configFile.getName()); return; } logger.debug("Processing config file '{}'", configFile.getName()); ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) ConfigActivator.configurationAdminTracker.getService(); if (configurationAdmin != null) { // we need to remember which configuration needs to be updated // because values have changed. Map<Configuration, Dictionary> configsToUpdate = new HashMap<Configuration, Dictionary>(); // also cache the already retrieved configurations for each pid Map<Configuration, Dictionary> configMap = new HashMap<Configuration, Dictionary>(); String pid; String filenameWithoutExt = StringUtils.substringBeforeLast(configFile.getName(), "."); if (filenameWithoutExt.contains(".")) { // it is a fully qualified namespace pid = filenameWithoutExt; } else { pid = getServicePidNamespace() + "." + filenameWithoutExt; } List<String> lines = IOUtils.readLines(new FileInputStream(configFile)); if (lines.size() > 0 && lines.get(0).startsWith(PID_MARKER)) { pid = lines.get(0).substring(PID_MARKER.length()).trim(); } for (String line : lines) { String[] contents = parseLine(configFile.getPath(), line); // no valid configuration line, so continue if (contents == null) continue; if (contents[0] != null) { pid = contents[0]; } String property = contents[1]; String value = contents[2]; Configuration configuration = configurationAdmin.getConfiguration(pid, null); if (configuration != null) { Dictionary configProperties = configMap.get(configuration); if (configProperties == null) { configProperties = new Properties(); configMap.put(configuration, configProperties); } if (!value.equals(configProperties.get(property))) { configProperties.put(property, value); configsToUpdate.put(configuration, configProperties); } } } for (Entry<Configuration, Dictionary> entry : configsToUpdate.entrySet()) { entry.getKey().update(entry.getValue()); } } }
@Test public void testDynamicInstantiationAndUpdate() throws IOException, InterruptedException { assertThat(osgi.getServiceObject(MyComponent.class)).isNull(); Configuration configuration = admin.getConfiguration("org.wisdom.conf"); Properties properties = new Properties(); properties.put("user", "wisdom"); configuration.update(properties); await() .atMost(1, TimeUnit.MINUTES) .until( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return osgi.getServiceObject(MyComponent.class) != null; } }); MyComponent service = osgi.getServiceObject(MyComponent.class); assertThat(service).isNotNull(); assertThat(service.hello()).contains("wisdom"); // Update the configuration configuration = admin.getConfiguration("org.wisdom.conf"); properties = new Properties(); properties.put("user", "wisdom-2"); configuration.update(properties); await() .atMost(1, TimeUnit.MINUTES) .until( new Callable<Boolean>() { @Override public Boolean call() throws Exception { MyComponent cmp = osgi.getServiceObject(MyComponent.class); if (cmp != null) { if (cmp.hello().contains("wisdom-2")) { return true; } } return false; } }); }
protected void deleteConfig(final String pid) { final ConfigurationAdmin ca = getConfigurationAdmin(); try { final Configuration config = ca.getConfiguration(pid); config.delete(); } catch (IOException ioe) { TestCase.fail("Failed deleting configuration " + pid + ": " + ioe.toString()); } }
@Test public void testConfigAdminService() throws IOException { Assert.assertNotNull(configAdmin, "Configuration Service is null"); Configuration config = configAdmin.getConfiguration(LOGGING_CONFIG_PID); Assert.assertNotNull(config, "PAX Logging Configuration is null"); config.update(); Dictionary properties = config.getProperties(); Assert.assertNotNull(properties, "PAX Logging Configuration Admin Service properties is null"); Assert.assertEquals(properties.get("service.pid"), LOGGING_CONFIG_PID); }
/** * Callback when a {@link SettingSpecifierProvider} has been registered. * * @param provider the provider object * @param properties the service properties */ public void onBind(SettingSpecifierProvider provider, Map<String, ?> properties) { log.debug("Bind called on {} with props {}", provider, properties); final String pid = provider.getSettingUID(); List<SettingSpecifierProvider> factoryList = null; String factoryInstanceKey = null; synchronized (factories) { FactoryHelper helper = factories.get(pid); if (helper != null) { // Note: SERVICE_PID not normally provided by Spring: requires // custom SN implementation bundle String instancePid = (String) properties.get(Constants.SERVICE_PID); Configuration conf; try { conf = configurationAdmin.getConfiguration(instancePid, null); @SuppressWarnings("unchecked") Dictionary<String, ?> props = conf.getProperties(); if (props != null) { factoryInstanceKey = (String) props.get(OSGI_PROPERTY_KEY_FACTORY_INSTANCE_KEY); log.debug("Got factory {} instance key {}", pid, factoryInstanceKey); factoryList = helper.getInstanceProviders(factoryInstanceKey); factoryList.add(provider); } } catch (IOException e) { log.error("Error getting factory instance configuration {}", instancePid, e); } } } if (factoryList == null) { synchronized (providers) { providers.put(pid, provider); } } final String settingKey = getFactoryInstanceSettingKey(pid, factoryInstanceKey); List<KeyValuePair> settings = settingDao.getSettings(settingKey); if (settings.size() < 1) { return; } SettingsCommand cmd = new SettingsCommand(); for (KeyValuePair pair : settings) { SettingValueBean bean = new SettingValueBean(); bean.setProviderKey(provider.getSettingUID()); bean.setInstanceKey(factoryInstanceKey); bean.setKey(pair.getKey()); bean.setValue(pair.getValue()); cmd.getValues().add(bean); } updateSettings(cmd); }
// FIXME: This should be a slightly deferred execution to allow changing // values just once per component when a number of updates arrive shortly // after each other. private void triggerUpdate(String componentName) { try { Configuration cfg = cfgAdmin.getConfiguration(componentName, null); Map<String, ConfigProperty> map = properties.get(componentName); Dictionary<String, Object> props = new Hashtable<>(); map.values().forEach(p -> props.put(p.name(), p.value())); cfg.update(props); } catch (IOException e) { log.warn("Unable to update configuration for " + componentName, e); } }
public Object addingService(ServiceReference reference) { try { final ConfigurationAdmin ca = (ConfigurationAdmin) context.getService(reference); Configuration config = ca.getConfiguration("org.ops4j.pax.logging", null); final Map<String, String> logProps = new HashMap<String, String>(); logProps.put("log4j.rootLogger", "INFO"); config.update(new Hashtable(logProps)); return ca; } catch (IOException ex) { logger.error("Unable to configure logging", ex); return null; } }
public String getZooKeeperUrl() { try { Configuration config = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper", null); final String zooKeeperUrl = (String) config.getProperties().get("zookeeper.url"); if (zooKeeperUrl == null) { throw new IllegalStateException("Unable to find the zookeeper url"); } return zooKeeperUrl; } catch (Exception e) { throw new FabricException("Unable to load zookeeper current url", e); } }
private Configuration getConfiguration(String providerUID, String factoryInstanceUID) throws IOException, InvalidSyntaxException { Configuration conf = null; if (factoryInstanceUID == null) { conf = configurationAdmin.getConfiguration(providerUID, null); } else { conf = findExistingConfiguration(providerUID, factoryInstanceUID); if (conf == null) { conf = configurationAdmin.createFactoryConfiguration(providerUID, null); } } return conf; }
@Test public void testConfigAdmin() throws IOException { assertThat(configAdmin, is(notNullValue())); org.osgi.service.cm.Configuration config = configAdmin.getConfiguration(DEBUG_OPTIONS); assertThat(config, is(notNullValue())); config.update(); @SuppressWarnings("unchecked") Dictionary<String, String> dictionary = config.getProperties(); assertThat(dictionary, is(notNullValue())); assertThat(dictionary.get("service.pid"), is(DEBUG_OPTIONS)); }
protected Configuration configure( final String pid, final String location, final boolean withProps) { final ConfigurationAdmin ca = getConfigurationAdmin(); try { final Configuration config = ca.getConfiguration(pid, location); if (withProps) { config.update(theConfig); } return config; } catch (IOException ioe) { TestCase.fail("Failed updating configuration " + pid + ": " + ioe.toString()); return null; // keep the compiler quiet } }
@Activate public void activate() { String consulURL = System.getenv("CONSUL_URL"); if (consulURL != null) { try { Dictionary<String, Object> settings = new Hashtable<>(); settings.put("consulServer", consulURL); this.configuration = configAdmin.getConfiguration("consul.http"); ConfigurationUtils.updateIfChanged(this.configuration, settings); } catch (IOException e) { logger.error("Error: ", e); } } }
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void testConfiguration_shouldHaveWrittenTheLaterOne() throws Exception { ServiceReference[] allServiceReferences = ctx.getAllServiceReferences(ConfigurationAdmin.class.getName(), null); for (ServiceReference serviceReference : allServiceReferences) { ConfigurationAdmin service = (ConfigurationAdmin) ctx.getService(serviceReference); try { org.osgi.service.cm.Configuration configuration = service.getConfiguration("tests"); assertEquals("myvalue2", configuration.getProperties().get("mykey")); return; } catch (Exception e) { // continue } } fail(); }
@Override public void start(BundleContext bundleContext) throws Exception { ServiceReference<ConfigurationAdmin> serviceReference = bundleContext.getServiceReference(ConfigurationAdmin.class); try { ConfigurationAdmin configurationAdmin = bundleContext.getService(serviceReference); _cxfConfiguration = configurationAdmin.createFactoryConfiguration( "com.liferay.portal.cxf.common.configuration." + "CXFEndpointPublisherConfiguration", null); Dictionary<String, Object> properties = new Hashtable<>(); properties.put("contextPath", "/soap-test"); _cxfConfiguration.update(properties); _jaxWsApiConfiguration = configurationAdmin.getConfiguration( "com.liferay.portal.soap.extender.configuration." + "JaxWsApiConfiguration", null); properties = new Hashtable<>(); properties.put("contextPath", "/soap-test"); properties.put("timeout", 10000); _jaxWsApiConfiguration.update(properties); _soapConfiguration = configurationAdmin.createFactoryConfiguration( "com.liferay.portal.soap.extender.configuration." + "SoapExtenderConfiguration", null); properties = new Hashtable<>(); properties.put("contextPaths", new String[] {"/soap-test"}); properties.put("jaxWsHandlerFilterStrings", new String[] {"(soap.address=*)"}); properties.put("jaxWsServiceFilterStrings", new String[] {"(jaxws=true)"}); _soapConfiguration.update(properties); } finally { bundleContext.ungetService(serviceReference); } }
public static void fromJSON(Reader r, ConfigurationAdmin admin) throws Exception { Decoder decoder = codec.dec().from(r); Protocol p = decoder.get(Protocol.class); for (int i = 0; i < p.size; i++) { Export e = decoder.get(Export.class); Configuration c; if (e.factoryPid != null) { c = admin.createFactoryConfiguration(e.factoryPid, "?*"); } else { c = admin.getConfiguration(e.pid, "?*"); } Dictionary<String, Object> d = getDictionary(e.types, e.values); c.update(d); } }
/** * Get the value of an OSGi configuration boolean property for a given PID. * * @param pid The PID of the OSGi component to retrieve * @param property The property of the config to retrieve * @param value The value to assign the provided property * @return The property value */ public boolean getBooleanProperty( final String pid, final String property, final boolean defaultValue) { try { Configuration conf = configAdmin.getConfiguration(pid); @SuppressWarnings("unchecked") Dictionary<String, Object> props = conf.getProperties(); if (props != null) { return PropertiesUtil.toBoolean(props.get(property), defaultValue); } } catch (IOException e) { LOGGER.error("Could not get property", e); } return defaultValue; }
/** 初始化单一实例,从ConfigurationAdmin服务获取配置信息 */ private RepositoryConfig() { BundleContext bc = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); ServiceReference configurationAdminReference = bc.getServiceReference(ConfigurationAdmin.class.getName()); sofaContainerHome = bc.getProperty(Constains.SOFA_CONTAINER_HOME_KEY); if (configurationAdminReference != null) { ConfigurationAdmin configAdmin = (ConfigurationAdmin) bc.getService(configurationAdminReference); Configuration config; try { config = configAdmin.getConfiguration(Constains.CONFIG_SERVICES_PID); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } properties = config.getProperties(); } }
@Test public void testLocalFabricCluster() throws Exception { // Test autostartup. assertNotNull(fabricService); Thread.sleep(DEFAULT_WAIT); Container[] containers = fabricService.getContainers(); assertNotNull(containers); assertEquals("Expected to find 1 container", 1, containers.length); assertEquals("Expected to find the root container", "root", containers[0].getId()); // Test that a generated password exists // We don't inject the configuration admin as it causes issues when the tracker gets closed. ConfigurationAdmin configurationAdmin = getOsgiService(ConfigurationAdmin.class); org.osgi.service.cm.Configuration configuration = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper"); Dictionary<String, Object> dictionary = configuration.getProperties(); assertNotNull("Expected a generated zookeeper password", dictionary.get("zookeeper.password")); }
// Loads existing property values that may have been set. private void loadExistingValues(String componentName) { try { Configuration cfg = cfgAdmin.getConfiguration(componentName, null); Map<String, ConfigProperty> map = properties.get(componentName); Dictionary<String, Object> props = cfg.getProperties(); if (props != null) { Enumeration<String> it = props.keys(); while (it.hasMoreElements()) { String name = it.nextElement(); ConfigProperty p = map.get(name); if (p != null) { map.put(name, ConfigProperty.setProperty(p, (String) props.get(name))); } } } } catch (IOException e) { log.error("Unable to get configuration for " + componentName, e); } }
/** * Set the value of an OSGi configuration property for a given PID. * * @param pid The PID of the OSGi component to update * @param property The property of the config to update * @param value The value to assign the provided property * @return true if the property was updated successfully */ public boolean setProperty(final String pid, final String property, final Object value) { try { Configuration conf = configAdmin.getConfiguration(pid); @SuppressWarnings("unchecked") Dictionary<String, Object> props = conf.getProperties(); if (props == null) { props = new Hashtable<String, Object>(); } props.put(property, value != null ? value : StringUtils.EMPTY); conf.update(props); } catch (IOException e) { LOGGER.error("Could not set property", e); return false; } return true; }
/** * Get the value of an OSGi configuration long property for a given PID. * * @param pid The PID of the OSGi component to retrieve * @param property The property of the config to retrieve * @param value The value to assign the provided property * @return The property value */ public Long getLongProperty(final String pid, final String property, final Long defaultValue) { long placeholder = -1L; long defaultTemp = defaultValue != null ? defaultValue : placeholder; try { Configuration conf = configAdmin.getConfiguration(pid); @SuppressWarnings("unchecked") Dictionary<String, Object> props = conf.getProperties(); if (props != null) { long result = PropertiesUtil.toLong(props.get(property), defaultTemp); return result == placeholder ? null : result; } } catch (IOException e) { LOGGER.error("Could not get property", e); } return defaultValue; }
@Test public void testLocalFabricCluster() throws Exception { System.out.println(executeCommand("fabric:create -n --clean root")); // Wait for zookeeper service to become available. Container[] containers = getFabricService().getContainers(); assertNotNull(containers); assertEquals("Expected to find 1 container", 1, containers.length); assertEquals("Expected to find the root container", "root", containers[0].getId()); // Test that a provided by commmand line password exists // We don't inject the configuration admin as it causes issues when the tracker gets closed. ConfigurationAdmin configurationAdmin = getOsgiService(ConfigurationAdmin.class); org.osgi.service.cm.Configuration configuration = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper"); Dictionary<String, Object> dictionary = configuration.getProperties(); assertEquals( "Expected provided zookeeper password", "systempassword", dictionary.get("zookeeper.password")); }
private void loggingActivate(final ConfigurationAdmin configAdmin) throws Exception { final URL propsURL = TestAny.class.getResource("/log4j.properties"); final Properties props = new Properties(); props.load(propsURL.openStream()); final org.osgi.service.cm.Configuration config = configAdmin.getConfiguration(PAX_PID, null); config.update(props); final ServiceTracker tracker = new ServiceTracker(context, PAX_SERVICE, null); tracker.open(true); final Object service = tracker.waitForService(3 * 1000); assertNotNull(service); Thread.sleep(500); }
@Override public void start(BundleContext bundleContext) throws Exception { try { this.bundleContext = bundleContext; log.debug("Initializing bundle {}.", bundleContext.getBundle().getBundleId()); camelContext = createCamelContext(); camelContext.addRoutes(this); ConfigurationAdmin configurationAdmin = requiredService(ConfigurationAdmin.class); Configuration camelKuraConfig = configurationAdmin.getConfiguration("kura.camel"); if (camelKuraConfig != null && camelKuraConfig.getProperties() != null) { Object routePropertyValue = camelKuraConfig.getProperties().get(camelXmlRoutesProperty()); if (routePropertyValue != null) { InputStream routesXml = new ByteArrayInputStream(routePropertyValue.toString().getBytes()); RoutesDefinition loadedRoutes = camelContext.loadRoutesDefinition(routesXml); camelContext.addRouteDefinitions(loadedRoutes.getRoutes()); } } beforeStart(camelContext); log.debug("About to start Camel Kura router: {}", getClass().getName()); camelContext.start(); producerTemplate = camelContext.createProducerTemplate(); consumerTemplate = camelContext.createConsumerTemplate(); log.debug("Bundle {} started.", bundleContext.getBundle().getBundleId()); } catch (Throwable e) { String errorMessage = "Problem when starting Kura module " + getClass().getName() + ":"; log.warn(errorMessage, e); // Print error to the Kura console. System.err.println(errorMessage); e.printStackTrace(); throw e; } }
@Override public void setConfiguration(String configuration) { try { Properties props = new Properties(); props.load(new StringReader(configuration)); String strategy = getStrategy(); BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext(); ServiceReference<ConfigurationAdmin> sr = bundleContext.getServiceReference(ConfigurationAdmin.class); ConfigurationAdmin ca = bundleContext.getService(sr); if (ca != null) { Configuration config = ca.getConfiguration(Activator.INSIGHT_CAMEL_PID); Dictionary<String, Object> dic = config.getProperties(); if (dic == null) { dic = new Hashtable<String, Object>(); } Set<String> s = new HashSet<String>(); for (Enumeration<String> keyEnum = dic.keys(); keyEnum.hasMoreElements(); ) { String key = keyEnum.nextElement(); if (key.startsWith(strategy + ".")) { s.add(key); } } for (String key : s) { dic.remove(key); } for (String key : props.stringPropertyNames()) { dic.put(strategy + "." + key, props.getProperty(key)); } config.update(dic); } } catch (IOException e) { throw new RuntimeException(e); } }