/** * Removes and unbinds a bundle location from the list of known locations. * * @param location The bundle location to remove */ public synchronized void removedBundle(String location) { bundleLocations.remove(location); String filter = "&((" + ConfigurationAdmin.SERVICE_BUNDLELOCATION + "=" + location + ")(" + CMConstants.SERVICE_DYNAMICLOCATION + "=" + Boolean.TRUE + "))"; try { List /* <Configuration> */ configurations = getConfigurations(filter, null, false); Iterator it = configurations.iterator(); while (it.hasNext()) { Configuration configuration = (Configuration) it.next(); ConfigurationDictionary dictionary = (ConfigurationDictionary) configuration.getProperties(); setBundleLocation(configuration.getPid(), configuration.getFactoryPid(), null, dictionary); } } catch (IOException e) { LOG.error("Error while unbinding configurations bound to " + location, e); } catch (InvalidSyntaxException e) { LOG.error("Error while unbinding configurations bound to " + location, e); } }
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); } }
/** * 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; }
@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 waitForService(Configuration sourceConfig) { long waitForService = 0; boolean serviceStarted = false; List<Map<String, Object>> servicesList; do { try { Thread.sleep(CONFIG_UPDATE_WAIT_INTERVAL_MILLIS); waitForService += CONFIG_UPDATE_WAIT_INTERVAL_MILLIS; } catch (InterruptedException e) { LOGGER.info("Interrupted waiting for service to init"); } if (waitForService >= MANAGED_SERVICE_TIMEOUT) { throw new RuntimeException( String.format( "Service %s not initialized within %d minute timeout", sourceConfig.getPid(), TimeUnit.MILLISECONDS.toMinutes(MANAGED_SERVICE_TIMEOUT))); } servicesList = adminConfig.getDdfConfigAdmin().listServices(); for (Map<String, Object> service : servicesList) { String id = String.valueOf(service.get(ConfigurationAdminExt.MAP_ENTRY_ID)); if (id.equals(sourceConfig.getPid()) || id.equals(sourceConfig.getFactoryPid())) { serviceStarted = true; break; } } } while (!serviceStarted); }
private void startManagedService(Configuration sourceConfig, Map<String, Object> properties) throws IOException { ServiceConfigurationListener listener = new ServiceConfigurationListener(sourceConfig.getPid()); bundleCtx.registerService(ConfigurationListener.class.getName(), listener, null); waitForService(sourceConfig); adminConfig.getDdfConfigAdmin().update(sourceConfig.getPid(), properties); long millis = 0; while (!listener.isUpdated() && millis < MANAGED_SERVICE_TIMEOUT) { try { Thread.sleep(CONFIG_UPDATE_WAIT_INTERVAL_MILLIS); millis += CONFIG_UPDATE_WAIT_INTERVAL_MILLIS; } catch (InterruptedException e) { LOGGER.info("Interrupted exception while trying to sleep for configuration update", e); } LOGGER.info("Waiting for configuration to be updated...{}ms", millis); } if (!listener.isUpdated()) { throw new RuntimeException( String.format( "Service configuration %s was not updated within %d minute timeout.", sourceConfig.getPid(), TimeUnit.MILLISECONDS.toMinutes(MANAGED_SERVICE_TIMEOUT))); } }
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."); } }
@Override public String addProviderFactoryInstance(String factoryUID) { synchronized (factories) { List<KeyValuePair> instanceKeys = settingDao.getSettings(getFactorySettingKey(factoryUID)); int next = instanceKeys.size() + 1; // verify key doesn't exist boolean done = false; while (!done) { done = true; for (KeyValuePair instanceKey : instanceKeys) { if (instanceKey.getKey().equals(String.valueOf(next))) { done = false; next++; } } } String newInstanceKey = String.valueOf(next); settingDao.storeSetting(getFactorySettingKey(factoryUID), newInstanceKey, newInstanceKey); try { Configuration conf = getConfiguration(factoryUID, newInstanceKey); @SuppressWarnings("unchecked") Dictionary<String, Object> props = conf.getProperties(); if (props == null) { props = new Hashtable<String, Object>(); } props.put(OSGI_PROPERTY_KEY_FACTORY_INSTANCE_KEY, newInstanceKey); conf.update(props); return newInstanceKey; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidSyntaxException e) { throw new RuntimeException(e); } } }
@Override public Object getSettingValue(SettingSpecifierProvider provider, SettingSpecifier setting) { if (setting instanceof KeyedSettingSpecifier<?>) { KeyedSettingSpecifier<?> keyedSetting = (KeyedSettingSpecifier<?>) setting; if (keyedSetting.isTransient()) { return keyedSetting.getDefaultValue(); } final String providerUID = provider.getSettingUID(); final String instanceUID = (provider instanceof FactorySettingSpecifierProvider ? ((FactorySettingSpecifierProvider) provider).getFactoryInstanceUID() : null); try { Configuration conf = getConfiguration(providerUID, instanceUID); @SuppressWarnings("unchecked") Dictionary<String, ?> props = conf.getProperties(); Object val = (props == null ? null : props.get(keyedSetting.getKey())); if (val == null) { val = keyedSetting.getDefaultValue(); } return val; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidSyntaxException e) { throw new RuntimeException(e); } } return null; }
protected Dictionary<String, Object> getConfigurationDictionary(Class<?> configurationClass) throws IOException { Configuration configuration = configurationAdmin.getConfiguration(configurationClass.getName()); boolean allowDeleted = false; if ((getClass() == FileSystemStore.class) && (configurationClass != FileSystemStoreConfiguration.class)) { allowDeleted = true; } if ((getClass() == AdvancedFileSystemStore.class) && (configurationClass != AdvancedFileSystemStoreConfiguration.class)) { allowDeleted = true; } try { return configuration.getProperties(); } catch (IllegalStateException ise) { if (allowDeleted) { return null; } throw ise; } }
// FIXME public access on the impl public String getZookeeperInfo(String name) { assertValid(); String zooKeeperUrl = null; // We are looking directly for at the zookeeper for the url, since container might not even be // mananaged. // Also this is required for the integration with the IDE. try { if (curator.get().getZookeeperClient().isConnected()) { Version defaultVersion = getDefaultVersion(); if (defaultVersion != null) { Profile profile = defaultVersion.getProfile("default"); if (profile != null) { Map<String, String> zookeeperConfig = profile.getConfiguration(Constants.ZOOKEEPER_CLIENT_PID); if (zookeeperConfig != null) { zooKeeperUrl = getSubstitutedData(curator.get(), zookeeperConfig.get(name)); } } } } } catch (Exception e) { // Ignore it. } if (zooKeeperUrl == null) { try { Configuration config = configAdmin.get().getConfiguration(Constants.ZOOKEEPER_CLIENT_PID, null); zooKeeperUrl = (String) config.getProperties().get(name); } catch (Exception e) { // Ignore it. } } return zooKeeperUrl; }
public void execute(Session session, String line, PrintStream out, PrintStream err) { // Parse command line. StringTokenizer st = new StringTokenizer(line, " "); // Ignore the command name. st.nextToken(); // Check for optional argument. String property = null; if (st.countTokens() >= 1) { property = st.nextToken().trim(); } try { if (session.getAttribute(Activator.CURRENT) == null) { throw new Exception("No configuration open currently"); } Dictionary dict = (Dictionary) session.getAttribute(Activator.EDITED); if (dict == null) { Configuration cfg = (Configuration) session.getAttribute(Activator.CURRENT); dict = cfg.getProperties(); session.setAttribute(Activator.EDITED, dict); } Object oldValue = dict.remove(property); if (oldValue == null) { throw new Exception("No property named " + property + " in current configuration."); } } catch (Exception e) { out.println("Unset failed. Details:"); String reason = e.getMessage(); out.println(reason == null ? "<unknown>: " + e.toString() : reason); } }
public static void removeModeShapeRepositoryConfigurations(BundleContext bundleContext) throws IOException, InvalidSyntaxException { Configuration[] modeShapeRepositoryConfigurations = getModeShapeConfigurations(bundleContext); for (Configuration modeShapeConfiguration : modeShapeRepositoryConfigurations) { modeShapeConfiguration.delete(); } }
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); }
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()); } }
Configuration mockConfiguration(Dictionary<String, Object> props) { Configuration commandConfig = EasyMock.createMock(Configuration.class); EasyMock.expect(commandConfig.getPid()) .andReturn((String) props.get(Constants.SERVICE_PID)) .anyTimes(); EasyMock.expect(commandConfig.getProperties()).andReturn(props).anyTimes(); EasyMock.replay(commandConfig); return commandConfig; }
@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); }
@SuppressWarnings("rawtypes") protected Object doExecute() throws Exception { Configuration[] configs = configRepository.getConfigAdmin().listConfigurations(query); if (configs != null) { Map<String, Configuration> sortedConfigs = new TreeMap<String, Configuration>(); for (Configuration config : configs) { sortedConfigs.put(config.getPid(), config); } for (String pid : sortedConfigs.keySet()) { Configuration config = sortedConfigs.get(pid); System.out.println("----------------------------------------------------------------"); System.out.println("Pid: " + config.getPid()); if (config.getFactoryPid() != null) { System.out.println("FactoryPid: " + config.getFactoryPid()); } System.out.println("BundleLocation: " + config.getBundleLocation()); if (config.getProperties() != null) { System.out.println("Properties:"); Dictionary props = config.getProperties(); Map<String, Object> sortedProps = new TreeMap<String, Object>(); for (Enumeration e = props.keys(); e.hasMoreElements(); ) { Object key = e.nextElement(); sortedProps.put(key.toString(), props.get(key)); } for (String key : sortedProps.keySet()) { System.out.println(" " + key + " = " + sortedProps.get(key)); } } } } return null; }
/** * 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); }
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"); } } }
// 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(priority = 5) public void testCreateDupeOk() throws Exception { when(enhancedConfig.getConfiguration(any(Dictionary.class), any(String.class), eq(false))) .thenReturn(json(config)); configObjectService.create(rname, id, json(config), true).getOrThrow(); ConfigObjectService.ParsedId parsedId = configObjectService.getParsedId(rname, id); Configuration config = configObjectService.findExistingConfiguration(parsedId); assertNotNull(config); assertNotNull(config.getProperties()); }
private void setConfigProperty(String pid, String propertyName, Object propertyValue) throws IOException { Map<String, Object> existingProperties = Optional.ofNullable(adminConfig.getDdfConfigAdmin().getProperties(pid)) .orElse(new Hashtable<>()); Hashtable<String, Object> updatedProperties = new Hashtable<>(); updatedProperties.putAll(existingProperties); updatedProperties.put(propertyName, propertyValue); Configuration configuration = adminConfig.getConfiguration(RESOURCE_DOWNLOAD_MANAGER_PID, null); configuration.update(updatedProperties); }
@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)); }
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); } }
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 static void toJSON(ConfigurationAdmin admin, Writer osw, String filter) throws Exception { Configuration[] list = admin.listConfigurations(filter); Encoder encoder = codec.enc().to(osw); Protocol p = new Protocol(); p.version = 1; p.date = new Date(); p.size = list.length; encoder.put(p).append('\n'); if (list != null) for (Configuration c : list) { Dictionary<String, Object> d = c.getProperties(); Export export = new Export(); export.values = new HashMap<String, Object>(); export.factoryPid = c.getFactoryPid(); export.pid = c.getPid(); for (Enumeration<String> e = d.keys(); e.hasMoreElements(); ) { String k = e.nextElement(); Object v = d.get(k); if (!(v instanceof String)) { if (export.types == null) export.types = new HashMap<String, Type>(); Type type = new Type(); Class<?> clazz = v.getClass(); if (v instanceof Collection) { Collection<?> coll = (Collection<?>) v; clazz = String.class; if (coll.size() > 0) type.vectorOf = shortName(coll.iterator().next().getClass()); else type.vectorOf = shortName(String.class); } else if (v.getClass().isArray()) { type.arrayOf = shortName(clazz.getComponentType()); } else type.scalar = shortName(v.getClass()); export.types.put(k, type); } export.values.put(k, v); } encoder.mark().put(export); // encoder.put(encoder.digest()); encoder.append('\n'); } osw.flush(); }
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 } }
/** * Store the handler switch configuration in configuration admin. * * @param handler the handler to store. * @param switchStatus the switch status to store. */ private void persist(String handler, SwitchStatus switchStatus) { try { Configuration configuration = configurationAdmin.getConfiguration(Configurations.NODE, null); if (configuration != null) { Dictionary<String, Object> properties = configuration.getProperties(); if (properties != null) { properties.put( Configurations.HANDLER + "." + handler, switchStatus.getValue().toString()); configuration.update(properties); } } } catch (Exception e) { LOGGER.warn("Can't persist the handler {} status", handler, e); } }
private void configureRestForBasic() throws IOException, InterruptedException { PolicyProperties policyProperties = new PolicyProperties(); policyProperties.put( "authenticationTypes", "/=SAML|basic,/admin=SAML|basic,/jolokia=SAML|basic,/system=SAML|basic,/solr=SAML|PKI|basic"); policyProperties.put( "whiteListContexts", "/services/SecurityTokenService,/services/internal,/proxy," + SERVICE_ROOT + "/sdk/SoapService"); Configuration config = configAdmin.getConfiguration(PolicyProperties.FACTORY_PID, null); Dictionary<String, ?> configProps = new Hashtable<>(policyProperties); config.update(configProps); waitForAllBundles(); }