Java Code Examples for org.osgi.service.cm.Configuration#getProperties()

The following examples show how to use org.osgi.service.cm.Configuration#getProperties() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CmApplication.java    From osgi.enroute.examples with Apache License 2.0 6 votes vote down vote up
@Override
public void configurationEvent(ConfigurationEvent event) {
	try {
		ConfigurationEventProperties cep = new ConfigurationEventProperties();
		cep.factoryPid = event.getFactoryPid();
		cep.pid = event.getPid();
		if (ConfigurationEvent.CM_DELETED != event.getType()) {
			Configuration configuration = cm.getConfiguration(event
					.getPid());
			cep.location = configuration.getBundleLocation();
			Dictionary<String, Object> properties = configuration
					.getProperties();
			if (properties == null) {
				cep.properties = new HashMap<>();
			} else
				cep.properties = toMap(properties);
		}
		ea.postEvent(new Event(TOPIC, dtos.asMap(cep)));
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 2
Source File: FeatureInstaller.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
public boolean addAddon(String type, String id) {
    try {
        Configuration cfg = configurationAdmin.getConfiguration(OpenHAB.ADDONS_SERVICE_PID, null);
        Dictionary<String, Object> props = cfg.getProperties();
        Object typeProp = props.get(type);
        String[] addonIds = typeProp != null ? typeProp.toString().split(",") : new String[0];
        List<String> trimmedAddonIds = Arrays.stream(addonIds).map(addonId -> addonId.trim())
                .collect(Collectors.toList());
        if (!trimmedAddonIds.contains(id)) {
            List<String> newAddonIds = new ArrayList<>(trimmedAddonIds.size() + 1);
            newAddonIds.addAll(trimmedAddonIds);
            newAddonIds.add(id);
            props.put(type, newAddonIds.stream().collect(Collectors.joining(",")));
            cfg.update(props);
            return true;
        } else {
            // it is already contained
            return false;
        }
    } catch (IOException e) {
        logger.warn("Adding add-on 'openhab-{}-{}' failed: {}", type, id, e.getMessage());
        return false;
    }
}
 
Example 3
Source File: OsgiConfigurationServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: OsgiConfigurationServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Get the value of an OSGi configuration string 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 String getStringProperty(final String pid, final String property, final String defaultValue) {
    try {
        Configuration conf = configAdmin.getConfiguration(pid);

        @SuppressWarnings("unchecked")
        Dictionary<String, Object> props = conf.getProperties();

        if (props != null) {
            return PropertiesUtil.toString(props.get(property), defaultValue);
        }
    } catch (IOException e) {
        LOGGER.error("Could not get property", e);
    }

    return defaultValue;
}
 
Example 5
Source File: DefaultLocaleSetter.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Configures the i18n provider based on the provided locale. Note that the configuration is not necessarily
 * effective yet when this method returns, as the configuration admin might configure the i18n provider in another
 * thread.
 *
 * @param locale the locale to use, must not be null.
 */
public void setDefaultLocale(Locale locale) throws IOException {
    assertThat(locale, is(notNullValue()));

    Configuration config = configAdmin.getConfiguration(I18nProviderImpl.CONFIGURATION_PID, null);
    assertThat(config, is(notNullValue()));

    Dictionary<String, Object> properties = config.getProperties();
    if (properties == null) {
        properties = new Hashtable<>();
    }

    properties.put(I18nProviderImpl.LANGUAGE, locale.getLanguage());
    properties.put(I18nProviderImpl.SCRIPT, locale.getScript());
    properties.put(I18nProviderImpl.REGION, locale.getCountry());
    properties.put(I18nProviderImpl.VARIANT, locale.getVariant());

    config.update(properties);
}
 
Example 6
Source File: ConfigAdminBinding.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @{inheritDoc
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected void internalReceiveCommand(String itemName, Command command) {
    if (configAdmin != null) {
        for (ConfigAdminBindingProvider provider : this.providers) {
            ConfigAdminBindingConfig bindingConfig = provider.getBindingConfig(itemName);
            Configuration config = getConfiguration(bindingConfig);
            if (config != null) {
                Dictionary props = config.getProperties();
                props.put(bindingConfig.configParameter, command.toString());
                try {
                    config.update(props);
                } catch (IOException ioe) {
                    logger.error("updating Configuration '{}' with '{}' failed", bindingConfig.normalizedPid,
                            command.toString());
                }
                logger.debug("successfully updated configuration (pid={}, value={})", bindingConfig.normalizedPid,
                        command.toString());
            } else {
                logger.info("There is no configuration found for pid '{}'", bindingConfig.normalizedPid);
            }
        }
    }
}
 
Example 7
Source File: CMCommands.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/***************************************************************************
 * Helper method that gets the editing dictionary of the current configuration
 * from the session. Returns a new empty dictionary if current is set but have
 * no dictionary set yet.
 **************************************************************************/
private Dictionary<String, Object> getEditingDict(Session session)
{
  @SuppressWarnings("unchecked")
  Dictionary<String, Object> dict =
    (Dictionary<String, Object>) session.getProperties().get(EDITED);
  if (dict == null) {
    final Configuration cfg = getCurrent(session);
    long changeCount = Long.MIN_VALUE;
    if (cfg != null) {
      changeCount = cfg.getChangeCount();
      dict = cfg.getProperties();
    }
    if (dict == null) {
      dict = new Hashtable<String, Object>();
    }
    setEditingDict(session, dict, changeCount);
  }
  return dict;
}
 
Example 8
Source File: OsgiConfigurationServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Source File: DiscoveryConsoleCommandExtension.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void configureBackgroundDiscovery(Console console, String discoveryServicePID, boolean enabled) {
    try {
        Configuration configuration = configurationAdmin.getConfiguration(discoveryServicePID);
        Dictionary<String, Object> properties = configuration.getProperties();
        if (properties == null) {
            properties = new Hashtable<>();
        }
        properties.put(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, enabled);
        configuration.update(properties);
        console.println("Background discovery for discovery service '" + discoveryServicePID + "' was set to "
                + enabled + ".");
    } catch (IOException ex) {
        String errorText = "Error occurred while trying to configure background discovery with PID '"
                + discoveryServicePID + "': " + ex.getMessage();
        logger.error(errorText, ex);
        console.println(errorText);
    }
}
 
Example 10
Source File: ConfigController.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
@RequestMapping
public ModelAndView config ()
{
    final Map<String, Object> model = new HashMap<> ();

    final StorageConfiguration command = new StorageConfiguration ();

    try
    {
        final Configuration cfg = this.configurationAdmin.getConfiguration ( PID_STORAGE_MANAGER, null );
        if ( cfg != null && cfg.getProperties () != null )
        {
            command.setBasePath ( (String)cfg.getProperties ().get ( "basePath" ) );
        }
    }
    catch ( final Exception e )
    {
        // ignore
    }

    model.put ( "command", command );
    fillData ( model );

    return new ModelAndView ( "/config/index", model );
}
 
Example 11
Source File: ConfigController.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
protected MailSettings getCurrent ()
{
    try
    {
        final Configuration cfg = this.admin.getConfiguration ( DefaultMailService.SERVICE_PID );
        if ( cfg == null || cfg.getProperties () == null )
        {
            return createDefault ();
        }

        final MailSettings result = new MailSettings ();

        result.setUsername ( getString ( cfg, "username" ) );
        result.setPassword ( getString ( cfg, "password" ) );
        result.setFrom ( getString ( cfg, "from" ) );
        result.setPrefix ( getString ( cfg, "prefix" ) );
        result.setHost ( getString ( cfg, DefaultMailService.PROPERTY_PREFIX + "mail.smtp.host" ) );
        result.setPort ( getInteger ( cfg, DefaultMailService.PROPERTY_PREFIX + "mail.smtp.port" ) );

        return result;
    }
    catch ( final IOException e )
    {
        return createDefault ();
    }
}
 
Example 12
Source File: ManagedWorkQueueList.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Configuration findConfigForQueueName(AutomaticWorkQueueImpl queue,
                                             ConfigurationAdmin configurationAdmin) throws Exception {
    Configuration selectedConfig = null;
    String filter = "(service.factoryPid=" + ManagedWorkQueueList.FACTORY_PID + ")";
    Configuration[] configs = configurationAdmin.listConfigurations(filter);
    for (Configuration configuration : configs) {
        Dictionary<String, Object> props = configuration.getProperties();
        String name = (String)props.get(AutomaticWorkQueueImpl.PROPERTY_NAME);
        if (queue.getName().equals(name)) {
            selectedConfig = configuration;
        }
    }
    return selectedConfig;
}
 
Example 13
Source File: OSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
protected void setDefaultLocale(Locale locale) throws Exception {
    assertThat(locale, is(notNullValue()));

    ConfigurationAdmin configAdmin = (ConfigurationAdmin) getService(
            Class.forName("org.osgi.service.cm.ConfigurationAdmin"));
    assertThat(configAdmin, is(notNullValue()));

    LocaleProvider localeProvider = (LocaleProvider) getService(
            Class.forName("org.eclipse.smarthome.core.i18n.LocaleProvider"));
    assertThat(localeProvider, is(notNullValue()));

    Configuration config = configAdmin.getConfiguration("org.eclipse.smarthome.core.i18nprovider", null);
    assertThat(config, is(notNullValue()));

    Dictionary<String, Object> properties = config.getProperties();
    if (properties == null) {
        properties = new Hashtable<>();
    }

    properties.put("language", locale.getLanguage());
    properties.put("script", locale.getScript());
    properties.put("region", locale.getCountry());
    properties.put("variant", locale.getVariant());

    config.update(properties);

    waitForAssert(new Closure<Object>(null) {
        private static final long serialVersionUID = -5083904877474902686L;

        public Object doCall() {
            assertThat(localeProvider.getLocale(), is(locale));
            return null;
        }
    });
}
 
Example 14
Source File: CassandraReconfigureTest.java    From Karaf-Cassandra with Apache License 2.0 5 votes vote down vote up
@Test
public void reconfigureEmbeddedCassandra() throws Exception {
	logger.info("Re-Configuring Embedded Cassandra");
	
	File yamlFile = new File("etc/cassandra.yaml");
       CassandraService service = getOsgiService(CassandraService.class, null, 120000);
       
	//assertThat(yamlFile.exists(), is(true));
	
	URI yamlUri = yamlFile.toURI();
	
	logger.info("using following cassandra.yaml file: {}", yamlUri);
	
	Configuration configuration = cm.getConfiguration("de.nierbeck.cassandra.embedded");
	Dictionary<String,Object> properties = configuration.getProperties();
	if (properties == null) {
		properties = new Hashtable<>();
	}
	properties.put("cassandra.yaml", yamlUri.toString());
	properties.put("jmx_port", "7299");
       properties.put("native_transport_port", "9242");
	
       logger.info("updating configuration with new properties.");
	configuration.setBundleLocation(null);
	configuration.update(properties);
	
	Thread.sleep(6000L);
	
	logger.info("verify restart successful");
	service = getOsgiService(CassandraService.class, null, 120000);
	assertThat(service.isRunning(), is(true));
	
	logger.info("checking command");
	assertThat(executeCommand("cassandra-admin:isRunning"),
			containsString("Embedded Cassandra is available"));
	
	logger.info("shutting down cassandra");
	cassandraService.stop();
}
 
Example 15
Source File: CMCommands.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void printConfiguration(PrintWriter out,
                                Session session,
                                final Configuration cfg,
                                boolean printTypes)
    throws Exception
{
  final String pid = cfg.getPid();
  final int listIndex = getIndexOfPidInLastList(session, pid);
  out.print('[');
  out.print(listIndex > -1 ? String.valueOf(listIndex) : "-" );
  out.print("] ");
  out.println(pid);

  final String factoryPid = cfg.getFactoryPid();
  if (factoryPid != null) {
    out.print(" factory PID: ");
    out.println(factoryPid);
  }

  out.print(" location: ");
  final String location = cfg.getBundleLocation();
  out.println(location != null ? location : "-");

  out.print(" change count: ");
  out.println(cfg.getChangeCount());

  final Dictionary<String, Object> d = cfg.getProperties();
  out.println(" properties:");
  if (d == null) {
    out.println("  -");
  } else {
    printDictionary(out, d, printTypes);
  }
}
 
Example 16
Source File: BindingInfoI18nTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void assertUsingDefaultLocale() throws Exception {
    // Set german locale
    ConfigurationAdmin configAdmin = getService(ConfigurationAdmin.class);
    assertThat(configAdmin, is(notNullValue()));

    Configuration config = configAdmin.getConfiguration(I18nProviderImpl.CONFIGURATION_PID, null);
    assertThat(config, is(notNullValue()));

    Dictionary<String, Object> properties = config.getProperties();
    if (properties == null) {
        properties = new Hashtable<>();
    }

    properties.put("language", "de");
    properties.put("region", "DE");

    config.update(properties);

    // before running the test with a default locale make sure the locale has been set
    LocaleProvider localeProvider = getService(LocaleProvider.class);
    assertThat(localeProvider, is(notNullValue()));

    waitForAssert(() -> assertThat(localeProvider.getLocale().toString(), is("de_DE")));

    bindingInstaller.exec(TEST_BUNDLE_NAME, () -> {
        // use default locale
        Set<BindingInfo> bindingInfos = bindingInfoRegistry.getBindingInfos(null);
        BindingInfo bindingInfo = bindingInfos.iterator().next();
        assertThat(bindingInfo, is(notNullValue()));
        assertThat(bindingInfo.getName(), is("Yahoo Wetter Binding"));
        assertThat(bindingInfo.getDescription(), is(
                "Das Yahoo Wetter Binding stellt verschiedene Wetterdaten wie die Temperatur, die Luftfeuchtigkeit und den Luftdruck für konfigurierbare Orte vom yahoo Wetterdienst bereit"));
    });
}
 
Example 17
Source File: SymmetricKeyCipher.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private SecretKey getOrGenerateEncryptionKey() throws NoSuchAlgorithmException, IOException {
    Configuration configuration = configurationAdmin.getConfiguration(PID);
    String encryptionKeyInBase64 = null;
    Dictionary<String, Object> properties = configuration.getProperties();
    if (properties == null) {
        properties = new Hashtable<>();
    }

    if (properties.get(PROPERTY_KEY_ENCRYPTION_KEY_BASE64) == null) {
        SecretKey secretKey = generateEncryptionKey();
        encryptionKeyInBase64 = new String(Base64.getEncoder().encode(secretKey.getEncoded()));

        // Put encryption key back into config
        properties.put(PROPERTY_KEY_ENCRYPTION_KEY_BASE64, encryptionKeyInBase64);
        configuration.update(properties);

        logger.debug("Encryption key generated");
        return secretKey;
    }

    // encryption key already present in config
    encryptionKeyInBase64 = (String) properties.get(PROPERTY_KEY_ENCRYPTION_KEY_BASE64);
    byte[] encKeyBytes = Base64.getDecoder().decode(encryptionKeyInBase64);
    // 128 bit key/ 8 bit = 16 bytes length
    logger.debug("Encryption key loaded");
    return new SecretKeySpec(encKeyBytes, 0, ENCRYPTION_KEY_SIZE_BITS / 8, ENCRYPTION_ALGO);
}
 
Example 18
Source File: LoggingConfigurationOSGiTest.java    From carbon-kernel with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 19
Source File: FeatureInstaller.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private boolean setOnlineStatus(boolean status) {
    boolean changed = false;
    if (onlineRepoUrl != null) {
        try {
            Configuration paxCfg = configurationAdmin.getConfiguration(PAX_URL_PID, null);
            paxCfg.setBundleLocation("?");
            Dictionary<String, Object> properties = paxCfg.getProperties();
            if (properties == null) {
                properties = new Hashtable<>();
            }
            List<String> repoCfg = new ArrayList<>();
            Object repos = properties.get(PROPERTY_MVN_REPOS);
            if (repos instanceof String) {
                repoCfg = new ArrayList<>(Arrays.asList(((String) repos).split(",")));
                repoCfg.remove("");
            }
            if (status) {
                if (!repoCfg.contains(onlineRepoUrl)) {
                    repoCfg.add(onlineRepoUrl);
                    changed = true;
                    logger.debug("Added repo '{}' to feature repo list.", onlineRepoUrl);
                }
            } else {
                if (repoCfg.contains(onlineRepoUrl)) {
                    repoCfg.remove(onlineRepoUrl);
                    changed = true;
                    logger.debug("Removed repo '{}' from feature repo list.", onlineRepoUrl);
                }
            }
            if (changed) {
                properties.put(PROPERTY_MVN_REPOS, repoCfg.stream().collect(Collectors.joining(",")));
                paxCfg.update(properties);
            }
        } catch (IOException e) {
            logger.error("Failed setting the add-on management online/offline mode: {}", e.getMessage());
        }
    }
    return changed;
}
 
Example 20
Source File: ComponentConfigManager.java    From onos with Apache License 2.0 5 votes vote down vote up
private void preSet(String componentName, String name, String value) {
    try {
        Configuration config = cfgAdmin.getConfiguration(componentName, null);
        Dictionary<String, Object> props = config.getProperties();
        if (props == null) {
            props = new Hashtable<>();
        }
        props.put(name, value);
        config.update(props);
    } catch (IOException e) {
        log.error("Failed to preset configuration for {}", componentName);
    }
}