org.osgi.service.cm.Configuration Java Examples

The following examples show how to use org.osgi.service.cm.Configuration. 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: 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 #2
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 #3
Source File: InstanceGrapeIT.java    From wisdom with Apache License 2.0 6 votes vote down vote up
protected void cleanupConfigurationAdmin() throws IOException, InvalidSyntaxException {
    Configuration[] configurations = admin.listConfigurations(null);
    if (configurations != null) {
        for (Configuration conf : configurations) {
            if (!conf.getPid().contains("instantiated.at.boot")) {
                conf.delete();
            }
        }
    }
    // Wait until instances are deleted
    await().atMost(1, TimeUnit.MINUTES).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return osgi.getServiceObject(C1.class) == null
                    && osgi.getServiceObject(C2.class) == null
                    && osgi.getServiceObject(C3.class) == null;

        }
    });
}
 
Example #4
Source File: DiscoveryConsoleCommandExtension.java    From openhab-core 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 #5
Source File: ConfigAdminBinding.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @{inheritDoc
 *
 *              Whenever a {@link Configuration} is updated all items for
 *              the given <code>pid</code> are queried and updated. Since
 *              the {@link ConfigurationEvent} contains no information which
 *              key changed we have to post updates for all configured
 *              items.
 */
@Override
public void configurationEvent(ConfigurationEvent event) {
    // we do only care for updates of existing configs!
    if (ConfigurationEvent.CM_UPDATED == event.getType()) {
        try {
            Configuration config = configAdmin.getConfiguration(event.getPid());
            for (ConfigAdminBindingProvider provider : this.providers) {
                for (ConfigAdminBindingConfig bindingConfig : provider.getBindingConfigByPid(event.getPid())) {
                    postUpdate(config, bindingConfig);
                }
            }
        } catch (IOException ioe) {
            logger.warn("Fetching configuration for pid '" + event.getPid() + "' failed", ioe);
        }
    }
}
 
Example #6
Source File: DeployedCMData.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void uninstall()
    throws BundleException
{
  final ConfigurationAdmin ca = DirDeployerImpl.caTracker.getService();
  if (pids != null && ca != null) {
    for (final String pid : pids) {
      try {
        final Configuration cfg = ca.getConfiguration(pid, null);
        cfg.delete();
        installedCfgs.remove(pid);
        deleteFilePidToCmPidEntry(pid);
      } catch (final IOException e) {
        DirDeployerImpl.log("Failed to uninstall configuration with pid '"
                            + pid + "': " + e.getMessage(), e);
      }
    }
    saveState();
    pids = null;
  }
}
 
Example #7
Source File: CMDataWriter.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void writeConfigurations(final Configuration[] cs,
                                       final PrintWriter w)
{
  writeLines(PRE, w);
  for (final Configuration cfg : cs) {
    if (cfg.getFactoryPid() != null) {
      w.println("<factoryconfiguration factorypid=\"" + cfg.getFactoryPid()
                + "\" mode=\"update\">");
      writeProperties(cfg.getProperties(), w);
      w.println("</factoryconfiguration>");
    } else {
      w.println("<configuration pid=\"" + cfg.getPid() + "\" mode=\"new\">");
      writeProperties(cfg.getProperties(), w);
      w.println("</configuration>");
    }
  }
  writeLines(POST, w);
}
 
Example #8
Source File: ConfigDispatcher.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void processOrphanExclusivePIDs() {
    for (String orphanPID : exclusivePIDMap.getOrphanPIDs()) {
        try {
            Configuration configuration = null;
            if (orphanPID.contains(ConfigConstants.SERVICE_CONTEXT_MARKER)) {
                configuration = getConfigurationWithContext(orphanPID);
            } else {
                configuration = configAdmin.getConfiguration(orphanPID, null);
            }
            if (configuration != null) {
                configuration.delete();
            }
            logger.debug("Deleting configuration for orphan pid {}", orphanPID);
        } catch (IOException | InvalidSyntaxException e) {
            logger.error("Error deleting configuration for orphan pid {}.", orphanPID);
        }
    }
}
 
Example #9
Source File: VoiceManagerTest.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    voiceManager = getService(VoiceManager.class, VoiceManagerImpl.class);
    assertNotNull(voiceManager);

    BundleContext context = bundleContext;
    ttsService = new TTSServiceStub(context);
    sink = new SinkStub();
    voice = new VoiceStub();
    source = new AudioSourceStub();

    registerService(sink);
    registerService(voice);

    Dictionary<String, Object> voiceConfig = new Hashtable<>();
    voiceConfig.put(CONFIG_DEFAULT_TTS, ttsService.getId());
    ConfigurationAdmin configAdmin = super.getService(ConfigurationAdmin.class);
    Configuration configuration = configAdmin.getConfiguration(VoiceManagerImpl.CONFIGURATION_PID);
    configuration.update(voiceConfig);

    audioManager = new AudioManagerStub();
    registerService(audioManager);
}
 
Example #10
Source File: ConfigDispatcherOSGiTest.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void whenContextExistsInExlusivePIDCreateMultipleServicesAndDeleteOneOfThem() throws IOException {
    String configDirectory = configBaseDirectory + SEP + "multiple_service_contexts";
    String servicesDirectory = "multiple_contexts";

    initialize(null);

    cd.processConfigFile(new File(getAbsoluteConfigDirectory(configDirectory, servicesDirectory)));

    verifyValueOfConfigurationPropertyWithContext("service.pid#ctx1", "property1", "value1");
    verifyValueOfConfigurationPropertyWithContext("service.pid#ctx2", "property1", "value2");

    File serviceConfigFile = new File(getAbsoluteConfigDirectory(configDirectory, servicesDirectory),
            "service-ctx1.cfg");

    cd.fileRemoved(serviceConfigFile.getAbsolutePath());

    Configuration c1 = getConfigurationWithContext("service.pid#ctx1");
    assertThat(c1, is(nullValue()));

    Configuration c2 = getConfigurationWithContext("service.pid#ctx2");
    assertThat(c2.getProperties().get("property1"), is("value2"));
}
 
Example #11
Source File: CMCommands.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Configuration[] getConfigurationsMatchingFilters(ConfigurationAdmin cm,
                                                         Filter[] filters)
    throws Exception
{
  final Configuration[] cs = cm.listConfigurations(null);
  if (cs == null || cs.length == 0) {
    return new Configuration[0];
  }
  if (filters == null || filters.length == 0) {
    return cs;
  }

  final List<Configuration> matching = new ArrayList<Configuration>();
  for (final Configuration cfg : cs) {
    for (final Filter filter : filters) {
      if (filter.match(cfg.getProperties())) {
        matching.add(cfg);
        break;
      }
    }
  }

  return matching.toArray(new Configuration[matching.size()]);
}
 
Example #12
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 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;
}
 
Example #13
Source File: Examples.java    From osgi.enroute.examples with Apache License 2.0 6 votes vote down vote up
/**
 * Create a configuration that kicks of a component with a Cron schedule
 * CronScheduleComponent
 * 
 * @throws IOException
 */

@Tooltip(description = "Create a configuration for the the ConfiguredCronScheduleComponent component. The service will stay registered until you cancel it.", deflt = "message=foo\n0/5 * * * * ?", type = "text")
public CancellablePromise<?> cronComponent(int id, String cronExpression)
		throws IOException {
	Configuration config = cm
			.getConfiguration(ConfiguredCronScheduleComponent.PID);
	Hashtable<String, Object> d = new Hashtable<String, Object>() {
		private static final long serialVersionUID = 1L;
		{
			put(CronJob.CRON, cronExpression);
			put("id", id);
		}
	};
	config.update(d);

	return new Closer<Object>(() -> config.delete());
}
 
Example #14
Source File: ConfigurationBackupServiceImpl.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
protected List<Configuration> getAllConfigurations () throws IOException, InvalidSyntaxException
{
    final Configuration[] result = this.configAdmin.listConfigurations ( null );

    if ( result == null )
    {
        return Collections.emptyList ();
    }

    final List<Configuration> list = new LinkedList<> ( Arrays.asList ( result ) );

    // remove ignored factories

    final Iterator<Configuration> i = list.iterator ();
    while ( i.hasNext () )
    {
        final Configuration cfg = i.next ();
        if ( this.ignoredFactories.contains ( cfg.getFactoryPid () ) )
        {
            i.remove ();
        }
    }

    return list;
}
 
Example #15
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 #16
Source File: ConfigurableServiceResourceOSGiTest.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    Configuration configuration = mock(Configuration.class);
    doAnswer(answer -> propertiesWrapper.getWrappedObject()).when(configuration).getProperties();
    doAnswer(answer -> {
        propertiesWrapper.set(answer.getArgument(0));
        return null;
    }).when(configuration).update(any(Dictionary.class));
    doAnswer(answer -> {
        propertiesWrapper.reset();
        return null;
    }).when(configuration).delete();

    propertiesWrapper.reset();

    ConfigurationAdmin configAdmin = mock(ConfigurationAdmin.class);
    when(configAdmin.getConfiguration(any())).thenReturn(configuration);
    when(configAdmin.getConfiguration(any(), nullable(String.class))).thenReturn(configuration);

    registerService(configAdmin);

    configurableServiceResource = getService(ConfigurableServiceResource.class);
    assertThat(configurableServiceResource, is(notNullValue()));
}
 
Example #17
Source File: ConfigController.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private boolean applyConfiguration ( final String basePath ) throws IOException
{
    final Configuration cfg = this.configurationAdmin.getConfiguration ( PID_STORAGE_MANAGER, null );
    if ( basePath == null || basePath.isEmpty () )
    {
        cfg.update ( new Hashtable<> () );
        return false;
    }
    else
    {
        final Dictionary<String, Object> data = new Hashtable<> ();
        data.put ( "basePath", basePath );
        cfg.update ( data );
        return true;
    }
}
 
Example #18
Source File: InterpretCommandTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException, InterruptedException {
    ttsService = new TTSServiceStub();
    hliStub = new HumanLanguageInterpreterStub();
    voice = new VoiceStub();

    registerService(voice);
    registerService(hliStub);
    registerService(ttsService);

    Dictionary<String, Object> config = new Hashtable<String, Object>();
    config.put(CONFIG_DEFAULT_TTS, ttsService.getId());
    config.put(CONFIG_DEFAULT_HLI, hliStub.getId());
    config.put(CONFIG_DEFAULT_VOICE, voice.getUID());
    ConfigurationAdmin configAdmin = super.getService(ConfigurationAdmin.class);
    String pid = "org.eclipse.smarthome.voice";
    Configuration configuration = configAdmin.getConfiguration(pid);
    configuration.update(config);
}
 
Example #19
Source File: CMConfig.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void configSet(String factoryPid, String cpid, Configuration c, boolean doReport) {
  String p;
  if (factoryPid != null) {
    if (component instanceof FactoryComponent) {
      Activator.logError(bundle.getBundleContext(), "FactoryComponent can not have factory config, ignored", null);
      return;
    }
    if (!factorySet(this)) {
      Activator.logError(bundle.getBundleContext(), "Component " + component + " has at least two factory CM configurations, " +
                         " ignoring " + factoryPid, null);
      return;
    }
    p = cpid;
  } else {
    if (factoryReset(this)) {
      resetAll();
    }
    p = pid;
  }
  set(p, c.getProperties(), doReport);
}
 
Example #20
Source File: ConfigurableServiceResourceOSGiTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    Configuration configuration = mock(Configuration.class);
    doAnswer(answer -> propertiesWrapper.getWrappedObject()).when(configuration).getProperties();
    doAnswer(answer -> {
        propertiesWrapper.set(answer.getArgument(0));
        return null;
    }).when(configuration).update(any(Dictionary.class));
    doAnswer(answer -> {
        propertiesWrapper.reset();
        return null;
    }).when(configuration).delete();

    propertiesWrapper.reset();

    ConfigurationAdmin configAdmin = mock(ConfigurationAdmin.class);
    when(configAdmin.getConfiguration(any())).thenReturn(configuration);
    when(configAdmin.getConfiguration(any(), nullable(String.class))).thenReturn(configuration);

    registerService(configAdmin);

    configurableServiceResource = getService(ConfigurableServiceResource.class);
    assertThat(configurableServiceResource, is(notNullValue()));
}
 
Example #21
Source File: SystemMetatypeProvider.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
Set<String> getCMFactoryPIDs()
{
  final Set<String> pids = new HashSet<String>();
  final ConfigurationAdmin ca = cmTracker.getService();
  if (ca != null) {
    try {
      final Configuration[] configs = ca.listConfigurations("(service.pid=*)");
      for (int i = 0; configs != null && i < configs.length; i++) {
        if (configs[i].getFactoryPid() != null) {
          pids.add(configs[i].getFactoryPid());
        }
      }
    } catch (final Exception e) {
      log.error("Failed to get service pids", e);
    }
  }
  return pids;
}
 
Example #22
Source File: SystemMetatypeProvider.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
Set<String> getCMServicePIDs()
{
  final Set<String> pids = new HashSet<String>();
  final ConfigurationAdmin ca = cmTracker.getService();
  if (ca != null) {
    try {
      final Configuration[] configs = ca.listConfigurations("(service.pid=*)");
      for (int i = 0; configs != null && i < configs.length; i++) {
        if (configs[i].getFactoryPid() == null) {
          pids.add(configs[i].getPid());
        }
      }
    } catch (final Exception e) {
      log.error("Failed to get service pids", e);
    }
  }
  return pids;
}
 
Example #23
Source File: ServletReregistrationService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Dictionary obtainProperties(){
    Dictionary properties = null;
    ServiceReference reference = bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
    ConfigurationAdmin admin = (ConfigurationAdmin) bundleContext.getService(reference);
    try {
        Configuration configuration = admin.getConfiguration("org.apache.cxf.osgi");
        properties = configuration.getProperties();
    } catch (Exception e){
        log.warn("Unable to obtain cxf osgi configadmin reference.", e);
    }
    return properties;
}
 
Example #24
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 #25
Source File: ConfigurationAdminFactory.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Configuration[] listConfigurations(final String filterString)
    throws IOException, InvalidSyntaxException
{
  Configuration[] configurations = null;

  try {
    configurations =
      AccessController
          .doPrivileged(new PrivilegedExceptionAction<Configuration[]>() {
            @Override
            public Configuration[] run()
                throws IOException, InvalidSyntaxException
            {
              return ConfigurationAdminFactory.this
                  .listConfigurations(filterString,
                                      ConfigurationAdminImpl.this.callingBundle,
                                      true);
            }
          });
  } catch (final PrivilegedActionException e) {
    final Exception ee = e.getException();
    // Android don't supply nested exception
    if (ee != null) {
      if (ee instanceof InvalidSyntaxException) {
        throw (InvalidSyntaxException) ee;
      }
      throw (IOException) ee;
    } else {
      throw new IOException("Failed to handle CM data");
    }
  }
  return configurations;
}
 
Example #26
Source File: CMConfig.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 *
 */
void configUpdated(String factoryPid, String cpid) {
  Configuration c = getConfiguration(factoryPid, cpid);
  if (c != null) {
    configSet(factoryPid, cpid, c, true);
  }
}
 
Example #27
Source File: Console.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public void getConfig ( final String pid ) throws IOException
{
    final Configuration cfg = this.configAdmin.getConfiguration ( pid );
    if ( cfg == null )
    {
        System.out.println ( "Not found" );
        return;
    }

    System.out.format ( "Location: %s%n", cfg.getBundleLocation () );
    System.out.format ( "Factory PID: %s%n", cfg.getFactoryPid () );
    System.out.format ( "PID: %s%n", cfg.getPid () );

    if ( cfg.getProperties () != null )
    {
        final List<List<String>> data = new LinkedList<> ();

        final Enumeration<String> en = cfg.getProperties ().keys ();
        while ( en.hasMoreElements () )
        {
            final String key = en.nextElement ();
            final Object value = cfg.getProperties ().get ( key );

            data.add ( Arrays.asList ( key, "" + value ) );
        }

        Tables.showTable ( System.out, Arrays.asList ( "Key", "Value" ), data, 2 );
    }
}
 
Example #28
Source File: CMConfig.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Register Component as a subscriber of CM events which have
 * component name as CM pid.
 *
 * @param comp Component which config needs to be tracked
 * @return true if all pids are available, otherwise false
 */
boolean subscribe() {
  if (ComponentDescription.POLICY_IGNORE != policy) {
    for (int i = 0; i < pids.length; i++) {
      String[] cs = pids[i].getTargetedPIDs();
      Configuration [] conf = null;
      for (int j = cs.length - 1; j >= 0; j--) {
        handler.addSubscriberCMPid(cs[j], pids[i]);
        if (conf == null) {
          conf = handler.listConfigurations(ConfigurationAdmin.SERVICE_FACTORYPID, cs[j]);
          if (conf != null) {
            for (Configuration c : conf) {
              pids[i].configSet(pids[i].pid, c.getPid(), c, false);
            }
          }
        }
        if (conf == null) {
          conf = handler.listConfigurations(Constants.SERVICE_PID, cs[j]);
          if (conf != null) {
            pids[i].configSet(null, pids[i].pid, conf[0], false);
          }
        }
      }
    }
  }
  return isSatisfied();
}
 
Example #29
Source File: ConfigurableServiceResourceOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void assertConfigurationManagementWorks() {
    Response response = configurableServiceResource.getConfiguration("id");
    assertThat(response.getStatus(), is(200));

    Map<String, Object> newConfiguration = new HashMap<>();
    newConfiguration.put("a", "b");
    response = configurableServiceResource.updateConfiguration("id", newConfiguration);
    assertThat(response.getStatus(), is(204));

    response = configurableServiceResource.getConfiguration("id");
    assertThat(response.getStatus(), is(200));
    assertThat(((Map) response.getEntity()).get("a"), is(equalTo("b")));

    newConfiguration.put("a", "c");
    response = configurableServiceResource.updateConfiguration("id", newConfiguration);
    assertThat(response.getStatus(), is(200));
    assertThat(((Map) response.getEntity()).get("a"), is(equalTo("b")));

    response = configurableServiceResource.deleteConfiguration("id");
    assertThat(response.getStatus(), is(200));
    assertThat(((org.eclipse.smarthome.config.core.Configuration) response.getEntity()).getProperties().get("a"),
            is(equalTo("c")));

    response = configurableServiceResource.getConfiguration("id");
    assertThat(response.getStatus(), is(200));
    assertThat(((Map) response.getEntity()).get("a"), nullValue());

    response = configurableServiceResource.deleteConfiguration("id");
    assertThat(response.getStatus(), is(204));
}
 
Example #30
Source File: ConfigSupplier.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public ConfigSupplier(@Nullable Configuration config) {
    if (config != null) {
        this.props = dictToMap(config.getProperties());
    } else {
        this.props = MutableMap.of();
    }
}