@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."); } }
@Test public void testConfigurationEventDeletedNonScope() throws Exception { String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "abc.def"; ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class); EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes(); EasyMock.replay(cm); SecuredCommandConfigTransformer scct = new SecuredCommandConfigTransformer(); scct.setConfigAdmin(cm); scct.init(); @SuppressWarnings("unchecked") ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class); EasyMock.replay(cmRef); ConfigurationEvent event = new ConfigurationEvent(cmRef, ConfigurationEvent.CM_DELETED, null, testPid); EasyMock.reset(cm); // Do not expect any further calls to cm... EasyMock.replay(cm); scct.configurationEvent(event); EasyMock.verify(cm); }
@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; }
public static Configuration[] getConfigurationsFor(BundleContext bundleContext, String factoryPid) throws IOException, InvalidSyntaxException { ConfigurationAdmin configurationAdminService = getConfigurationAdminService(bundleContext); Configuration[] modeShapeRepositoryConfigurations = configurationAdminService.listConfigurations( "(" + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + factoryPid + ")"); return modeShapeRepositoryConfigurations; }
@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()); } } }
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()); } }
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; } }
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; }
protected Configuration createFactoryConfiguration( final String factoryPid, final String location, final boolean withProps) { final ConfigurationAdmin ca = getConfigurationAdmin(); try { final Configuration config = ca.createFactoryConfiguration(factoryPid, null); if (withProps) { config.update(theConfig); } return config; } catch (IOException ioe) { TestCase.fail("Failed updating factory configuration " + factoryPid + ": " + ioe.toString()); return null; // keep the compiler quiet } }
/** * 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; }
protected void deleteFactoryConfigurations(String factoryPid) { ConfigurationAdmin ca = getConfigurationAdmin(); try { final String filter = "(service.factoryPid=" + factoryPid + ")"; Configuration[] configs = ca.listConfigurations(filter); if (configs != null) { for (Configuration configuration : configs) { configuration.delete(); } } } catch (InvalidSyntaxException ise) { // unexpected } catch (IOException ioe) { TestCase.fail("Failed deleting configurations " + factoryPid + ": " + ioe.toString()); } }
public void clean() { try { for (; ; ) { Configuration[] configs = configurationAdmin.listConfigurations( "(|(service.factoryPid=org.fusesource.fabric.zookeeper.server)(service.pid=org.fusesource.fabric.zookeeper))"); if (configs != null && configs.length > 0) { for (Configuration config : configs) { config.delete(); } Thread.sleep(100); } else { break; } } File zkDir = new File("data/zookeeper"); if (zkDir.isDirectory()) { File newZkDir = new File("data/zookeeper." + System.currentTimeMillis()); if (!zkDir.renameTo(newZkDir)) { newZkDir = zkDir; } delete(newZkDir); } } catch (Exception e) { throw new FabricException("Unable to delete zookeeper configuration", e); } }
protected Configuration getConfiguration(final String pid) { final ConfigurationAdmin ca = getConfigurationAdmin(); try { final String filter = "(" + Constants.SERVICE_PID + "=" + pid + ")"; final Configuration[] configs = ca.listConfigurations(filter); if (configs != null && configs.length > 0) { return configs[0]; } } catch (InvalidSyntaxException ise) { // unexpected } catch (IOException ioe) { TestCase.fail("Failed listing configurations " + pid + ": " + ioe.toString()); } TestCase.fail("No Configuration " + pid + " found"); return null; }
@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(); }
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); }
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); } }
@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); } }
@Test public void testDynamicInstantiationAndUpdateUsingConfigurationFactory() throws IOException, InterruptedException { assertThat(osgi.getServiceObject(MyComponent.class)).isNull(); Configuration configuration = admin.createFactoryConfiguration("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(configuration.getPid()); 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; } }); }
/** 初始化单一实例,从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")); }
@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); }
@Test public void testConfigurationEventAddedNonCommand() throws Exception { ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class); EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes(); EasyMock.replay(cm); SecuredCommandConfigTransformer scct = new SecuredCommandConfigTransformer(); 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, "test123"); scct.configurationEvent(event); EasyMock.verify(cm); // Ensure that this doesn't cause any unwanted calls on ConfigAdmin }
public void init() { synchronized (this.monitor) { try { for (Configuration configuration : configurationAdmin.listConfigurations(null)) { exportConfiguration(configuration.getPid()); } } catch (Exception e) { logger.warn("Could not enumerate existing configurations"); } } }
/** * 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); } }
@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")); }
@Validate void start() throws IOException { { Dictionary properties = new Hashtable(); properties.put("id", getId()); properties.put("service", Constants.GRANITE_SERVICE); destination = configurationAdmin.createFactoryConfiguration( "org.granite.config.flex.Destination", null); destination.update(properties); } }
@Test public void testConfigurationLocationChangedEventNoEffect() throws Exception { String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "test123"; ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class); EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes(); EasyMock.replay(cm); SecuredCommandConfigTransformer scct = new SecuredCommandConfigTransformer(); scct.setConfigAdmin(cm); scct.init(); @SuppressWarnings("unchecked") ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class); EasyMock.replay(cmRef); ConfigurationEvent event = new ConfigurationEvent(cmRef, ConfigurationEvent.CM_LOCATION_CHANGED, null, testPid); scct.configurationEvent(event); EasyMock.verify(cm); // Ensure that this doesn't cause any unwanted calls on ConfigAdmin }
@Test public void testConfigurationEventDeleted() throws Exception { String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "test123"; ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class); EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes(); EasyMock.replay(cm); SecuredCommandConfigTransformer scct = new SecuredCommandConfigTransformer(); scct.setConfigAdmin(cm); scct.init(); @SuppressWarnings("unchecked") ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class); EasyMock.replay(cmRef); ConfigurationEvent event = new ConfigurationEvent(cmRef, ConfigurationEvent.CM_DELETED, null, testPid); Configuration c1 = EasyMock.createMock(Configuration.class); c1.delete(); EasyMock.expectLastCall().once(); EasyMock.replay(c1); Configuration c2 = EasyMock.createMock(Configuration.class); c2.delete(); EasyMock.expectLastCall().once(); EasyMock.replay(c2); EasyMock.reset(cm); EasyMock.expect( cm.listConfigurations("(service.pid=org.apache.karaf.service.acl.command.test123.*)")) .andReturn(new Configuration[] {c1, c2}) .once(); EasyMock.replay(cm); scct.configurationEvent(event); EasyMock.verify(cm); EasyMock.verify(c1); EasyMock.verify(c2); }