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

The following examples show how to use org.osgi.service.cm.Configuration#update() . 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: 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 2
Source File: ComponentConfigManager.java    From onos with Apache License 2.0 6 votes vote down vote up
private void triggerUpdate(String componentName) {
    try {
        Configuration cfg = cfgAdmin.getConfiguration(componentName, null);
        Map<String, ConfigProperty> map = properties.get(componentName);
        if (map == null) {
            //  Prevent NPE if the component isn't there
            log.warn("Component not found for " + componentName);
            return;
        }
        Dictionary<String, Object> props = new Hashtable<>();
        map.values().stream().filter(p -> p.value() != null)
                .forEach(p -> props.put(p.name(), p.value()));
        cfg.update(props);
    } catch (IOException e) {
        log.warn("Unable to update configuration for " + componentName, e);
    }
}
 
Example 3
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 4
Source File: VoiceManagerTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void interpretSomethingWhenTheDefaultHliIsSetAndItIsARegisteredService()
        throws IOException, InterpretationException {
    stubConsole = new ConsoleStub();
    hliStub = new HumanLanguageInterpreterStub();
    registerService(hliStub);

    Dictionary<String, Object> voiceConfig = new Hashtable<String, Object>();
    voiceConfig.put("defaultHLI", hliStub.getId());
    ConfigurationAdmin configAdmin = super.getService(ConfigurationAdmin.class);
    String pid = "org.eclipse.smarthome.voice";
    Configuration configuration = configAdmin.getConfiguration(pid);
    configuration.update(voiceConfig);

    String result = voiceManager.interpret("something", hliStub.getId());
    assertThat(result, is("Interpreted text"));
}
 
Example 5
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 6
Source File: Examples.java    From osgi.enroute.examples with Apache License 2.0 5 votes vote down vote up
@Tooltip("Reads a number of configuration from a resource 'example.configs' and installs them. The actions are enclosed by a Coordination")
public void coordinator() throws Exception {
	try (InputStream in = Examples.class
			.getResourceAsStream("example.configs")) {

		Coordination coordination = coordinator.begin("example.1", 100000);
		try {
			List<Config> list = dtos.decoder(
					new TypeReference<List<Config>>() {
					}).get(in);

			for (Config config : list) {
				Configuration c;

				if (config.factoryPid != null)
					c = cm.createFactoryConfiguration(config.factoryPid,
							"?");
				else
					c = cm.getConfiguration(config.pid);

				c.update(config.properties);
			}
			coordination.end();
		} catch (Throwable t) {
			coordination.fail(t);
		}
	}
}
 
Example 7
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 8
Source File: TargetPanel.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Gets and optionally creates, updates the selected configuration.
 *
 * @param create
 *          If {@code true} create the configuration if it does not exists or
 *          if we are working with a factory PID.
 * @param newProps
 *          Update the configuration with these new props before returning it.
 *
 * @return The (updated) selected configuration or {@code null} if
 *         {@code create} is {@code false} and there is no configuration for
 *         the current selection.
 * @throws IOException
 */
Configuration getSelectedConfiguration(boolean create,
                                       Dictionary<String, Object> newProps)
    throws IOException
{
  Configuration cfg = getSelectedConfiguration();
  if (create && (cfg == null || isFactoryPid)) {
    if (isFactoryPid) {
      if (newProps == null) {
        final String msg =
          "getSelectedConfigriation(true,null) for factory "
              + "configuration is not supported.";
        throw new IOException(msg);
      }
      final String fpid = targetedPids[selectedTargetLevel];
      cfg = CMDisplayer.getCA().createFactoryConfiguration(fpid, null);

      // Select the new PID in next call to updateSelection(false).
      nextFactoryPidToSelect = cfg.getPid();
    } else {
      cfg =
        CMDisplayer.getCA()
            .getConfiguration(targetedPids[selectedTargetLevel], null);
      // Let the next call to updateSelection(false) select the new PID.
      nextPidToSelect = cfg.getPid();
    }
  }

  if (cfg != null && newProps != null) {
    // Update the configuration with the given set of properties
    cfg.update(newProps);
    // UI will be updated from the ConfgurationListener callback.
  }

  return cfg;
}
 
Example 9
Source File: Examples.java    From osgi.enroute.examples with Apache License 2.0 5 votes vote down vote up
/**
 * This code is the same as {@link #exampleSingleton()} but it creates a
 * Configuration Listener. A listener receives events from configuration
 * admin.
 */
@Tooltip("Create a a configuration for pid='listener', this activates the ConfigurationListenerExample component")
public void listener() throws IOException {
	Configuration configuration = cm.getConfiguration("listener", "?");
	if (configuration.getProperties() == null)
		configuration.update(new Hashtable<String, Object>());
}
 
Example 10
Source File: VoiceManagerTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void startDialogWithoutPassingAnyParameters() throws IOException, InterruptedException {
    sttService = new STTServiceStub();
    ksService = new KSServiceStub();
    ttsService = new TTSServiceStub();
    hliStub = new HumanLanguageInterpreterStub();
    source = new AudioSourceStub();

    registerService(sttService);
    registerService(ksService);
    registerService(ttsService);
    registerService(hliStub);
    registerService(source);

    Dictionary<String, Object> config = new Hashtable<>();
    config.put(CONFIG_KEYWORD, "word");
    config.put(CONFIG_DEFAULT_STT, sttService.getId());
    config.put(CONFIG_DEFAULT_KS, ksService.getId());
    config.put(CONFIG_DEFAULT_HLI, hliStub.getId());
    config.put(CONFIG_DEFAULT_VOICE, voice.getUID());

    ConfigurationAdmin configAdmin = super.getService(ConfigurationAdmin.class);
    Configuration configuration = configAdmin.getConfiguration(VoiceManagerImpl.CONFIGURATION_PID);
    configuration.update(config);

    waitForAssert(() -> {
        try {
            voiceManager.startDialog();
        } catch (Exception ex) {
            // if the configuration is not updated yet the startDialog method will throw and exception which will
            // break the test
        }

        assertTrue(ksService.isWordSpotted());
    });
}
 
Example 11
Source File: Utils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Method to update pax-logging configuration.
 */
public static void updateLoggingConfiguration() throws IOException {

    ConfigurationAdmin configurationAdmin = ConfigurationHolder.getInstance().getConfigAdminService();
    Configuration configuration =
            configurationAdmin.getConfiguration(Constants.PAX_LOGGING_CONFIGURATION_PID, "?");
    configuration.update();
}
 
Example 12
Source File: ManagedWorkQueueList.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void propertyChange(PropertyChangeEvent evt) {
    try {
        AutomaticWorkQueueImpl queue = (AutomaticWorkQueueImpl)evt.getSource();
        ConfigurationAdmin configurationAdmin = configAdminTracker.getService();
        if (configurationAdmin != null) {
            Configuration selectedConfig = findConfigForQueueName(queue, configurationAdmin);
            if (selectedConfig != null) {
                Dictionary<String, String> properties = queue.getProperties();
                selectedConfig.update(properties);
            }
        }
    } catch (Exception e) {
        LOG.log(Level.WARNING, e.getMessage(), e);
    }
}
 
Example 13
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 14
Source File: Examples.java    From osgi.enroute.examples with Apache License 2.0 5 votes vote down vote up
/**
 * This example shows how to create a factory configuration.
 */
@Tooltip("Create a a factory configuration for pid='factory', this activates the ManagedServiceFactory component")
public void factory() throws IOException {
	Configuration a = cm.createFactoryConfiguration("factory", "?");
	Hashtable<String, Object> map = new Hashtable<String, Object>();
	map.put("msg", "Hello Factory");
	a.update(map);
}
 
Example 15
Source File: ServiceManager.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public void add ( final AddEntry data ) throws IOException
{
    final Configuration cfg = this.configAdmin.createFactoryConfiguration ( ID, null );
    final Dictionary<String, Object> properties = new Hashtable<> ();

    properties.put ( "keyring", data.getKeyring () );
    properties.put ( "key.id", data.getKeyId () );
    properties.put ( "key.passphrase", data.getKeyPassphrase () );
    properties.put ( "description", data.getLabel () );

    cfg.update ( properties );
}
 
Example 16
Source File: ComponentTestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Test that SCR handles factory CM pids with target filters.
 * 
 */

public void runTest() {
  Bundle b1 = null;
  ServiceTracker<ConfigurationAdmin, ConfigurationAdmin> cmt = null;
  try {
    b1 = Util.installBundle(bc, "componentC_test-1.0.0.jar");
    b1.start();
    final String b1loc = b1.getLocation();

    cmt = new ServiceTracker<ConfigurationAdmin,ConfigurationAdmin>(bc, ConfigurationAdmin.class.getName(), null);
    cmt.open();
    
    Thread.sleep(SLEEP_TIME);

    ServiceReference<?> ref = bc.getServiceReference("org.knopflerfish.service.componentC_test.ComponentU");
    assertNull("Should not get serviceRef U", ref);

    ConfigurationAdmin ca = cmt.getService();
    Configuration c = ca.createFactoryConfiguration("componentC_test.U", b1loc);

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("vRef.target", "(vnum=v0)");
    c.update(props);
    
    Thread.sleep(SLEEP_TIME);

    ref = bc.getServiceReference("org.knopflerfish.service.componentC_test.ComponentU");
    assertNull("Should not get serviceRef U", ref);

    props.put("vRef.target", "(vnum=v1)");
    c.update(props);
    
    Thread.sleep(SLEEP_TIME);

    ServiceReference<?> [] refs = bc.getServiceReferences("org.knopflerfish.service.componentC_test.ComponentU", null);
    assertTrue("Should get one serviceRef to ComponentU", refs != null && refs.length == 1);

    Configuration c2 = ca.createFactoryConfiguration("componentC_test.U", b1loc);
    props = new Hashtable<String, Object>();
    props.put("vRef.target", "(vnum=v2)");
    c2.update(props);
    
    Thread.sleep(SLEEP_TIME);

    refs = bc.getServiceReferences("org.knopflerfish.service.componentC_test.ComponentU", null);
    assertTrue("Should get two serviceRef to ComponentU", refs != null && refs.length == 2);

    refs = bc.getServiceReferences("org.knopflerfish.service.componentC_test.ComponentU", "(vRef.target=\\(vnum=v1\\))");
    assertTrue("Should get one serviceRef to ComponentU with ref v1", refs != null && refs.length == 1);
    org.knopflerfish.service.componentC_test.ComponentU u =
        (org.knopflerfish.service.componentC_test.ComponentU)bc.getService(refs[0]);
    assertEquals("Should get v1 version", "v1", u.getV());

    refs = bc.getServiceReferences("org.knopflerfish.service.componentC_test.ComponentU", "(vRef.target=\\(vnum=v2\\))");
    assertTrue("Should get one serviceRef to ComponentU with ref v2", refs != null && refs.length == 1);
    org.knopflerfish.service.componentC_test.ComponentU u2 =
        (org.knopflerfish.service.componentC_test.ComponentU)bc.getService(refs[0]);
    assertNotSame("Services should differ", u, u2);
    assertEquals("Should get v2 version", "v2", u2.getV());
  } catch (Exception e) {
    e.printStackTrace();
    fail("Test11: got unexpected exception " + e);
  } finally {
    if (b1 != null) {
      try {
        if (cmt != null) {
          deleteConfig(cmt.getService(), b1.getLocation());
          cmt.close();
        }
        b1.uninstall();
      } catch (Exception be) {
        be.printStackTrace();
        fail("Test11: got uninstall exception " + be);
      }
    }
  }
}
 
Example 17
Source File: CMCommands.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public int cmdSave(Dictionary<?, ?> opts,
                   Reader in,
                   PrintWriter out,
                   Session session)
{
  int retcode = 1; // 1 initially not set to 0 until end of try block
  final boolean forceOptionNotSpecified = opts.get("-force") == null;
  ConfigurationAdmin srvCA = null;
  try {
    final Configuration cfg = getCurrent(session);
    if (cfg == null) {
      throw new Exception("No configuration open currently");
    }
    srvCA = getCA();

    if (isEditing(session)) {
      final long oldVersion = getEditingVersion(session);
      final long currentVersion = cfg.getChangeCount();

      if (forceOptionNotSpecified && currentVersion > oldVersion) {
        throw new Exception("The configuration has changed in CM since "
                            + "it was opened. Use -force option if you "
                            + "want to force saving of your changes.");
      }
      cfg.update(getEditingDict(session));
      setEditingDict(session);
    } else {
      throw new Exception("No changes to save");
    }
    retcode = 0; // Success!
  } catch (final Exception e) {
    out.print("Save failed. Details:");
    final String reason = e.getMessage();
    out.println(reason == null ? "<unknown>" : reason);
  } finally {
    if (srvCA != null) {
      bc.ungetService(refCA);
    }
  }
  return retcode;
}
 
Example 18
Source File: SayCommandTest.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testSayCommand() throws IOException {
    String[] methodParameters = new String[2];
    methodParameters[0] = SUBCMD_SAY;

    if (defaultTTSService != null) {
        Dictionary<String, Object> config = new Hashtable<String, Object>();
        config.put(CONFIG_DEFAULT_TTS, defaultTTSService);
        ConfigurationAdmin configAdmin = super.getService(ConfigurationAdmin.class);
        String pid = "org.eclipse.smarthome.voice";
        Configuration configuration = configAdmin.getConfiguration(pid);
        configuration.update(config);
    }

    if (TTSServiceMockShouldBeRegistered) {
        registerService(ttsService);
    }

    if (shouldItemsBePassed) {
        VolatileStorageService volatileStorageService = new VolatileStorageService();
        registerService(volatileStorageService);

        ManagedThingProvider managedThingProvider = getService(ThingProvider.class, ManagedThingProvider.class);
        assertNotNull(managedThingProvider);

        ItemRegistry itemRegistry = getService(ItemRegistry.class);
        assertNotNull(itemRegistry);

        Item item = new StringItem("itemName");

        if (shouldItemsBeRegistered) {
            itemRegistry.add(item);
        }
        methodParameters[1] = "%" + item.getName() + "%";

        if (shouldMultipleItemsBeRegistered) {
            Item item1 = new StringItem("itemName1");
            itemRegistry.add(item1);

            Item item2 = new StringItem("itemName2");
            itemRegistry.add(item2);

            Item item3 = new StringItem("itemName3");
            itemRegistry.add(item3);

            methodParameters[1] = "%itemName.%";
        }
    } else {
        methodParameters[1] = "hello";
    }
    extensionService.execute(methodParameters, console);

    assertThat(sink.isStreamProcessed(), is(shouldStreamBeExpected));
}
 
Example 19
Source File: DeployedCMData.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void installIfNeeded()
    throws BundleException
{
  final ConfigurationAdmin ca = DirDeployerImpl.caTracker.getService();
  if (pids == null && ca != null) {
    try {
      fileLastModified = file.lastModified();
      // List with all PIDs that is created from the current file.
      final List<String> pidList = new ArrayList<String>();

      // List with all PIDs for factory configurations that are defined in the
      // current file, used for duplicate detection.
      final List<String> pidListFactory = new ArrayList<String>();

      final Hashtable<String, Object>[] configs = loadCMDataFile(file);
      for (final Hashtable<String, Object> config : configs) {
        final String pid = (String) config.get(CMDataReader.SERVICE_PID);
        config.remove("service.bundleLocation");
        final String fpid = (String) config.get(CMDataReader.FACTORY_PID);

        Configuration cfg;
        if (fpid == null) {
          // Non-factory Configuration
          if (pidList.contains(pid)) {
            DirDeployerImpl.logErr("Skipping dupplicated configuration "
                                   + "with pid='" + pid + "' found in "
                                   + file, null);
            continue;
          }
          final File otherFile = installedCfgs.get(pid);
          if (!file.equals(otherFile)) {
            DirDeployerImpl.log("Overwriting configuration with pid='" + pid
                                + "' defined in '" + otherFile + "'.");
          }
          cfg = ca.getConfiguration(pid, null);
          // Make sure that an existing configuration is unbound from
          // location.
          if (cfg.getBundleLocation() != null) {
            cfg.setBundleLocation(null);
          }
        } else {
          // Factory configuration
          if (pidListFactory.contains(pid)) {
            DirDeployerImpl.logErr("Skipping non-unique factory "
                                   + "configuration with service.pid='" + pid
                                   + "' found in " + file, null);
            continue;
          }
          pidListFactory.add(pid);
          cfg = ca.createFactoryConfiguration(fpid, null);
          DirDeployerImpl.log("Created factory config with pid '"
                              + cfg.getPid()
                              + "' for file configuration with service.pid '"
                              + pid + "'.");
          filePidToCmPid.put(getFilePidForPid(pid), cfg.getPid());
        }

        cfg.update(config);
        pidList.add(cfg.getPid());
        installedCfgs.put(cfg.getPid(), file);
      }
      pids = pidList.toArray(new String[pidList.size()]);

      DirDeployerImpl.log("installed " + this);
    } catch (final Exception e) {
      DirDeployerImpl.log("Failed to install " + this + "; " + e, e);
    }
  } else {
    DirDeployerImpl.log("already installed " + this);
  }

  if (pids != null) {
    saveState();
  }
}
 
Example 20
Source File: LogConfigUpdater.java    From carbon-commons with Apache License 2.0 3 votes vote down vote up
private void updateLoggingConfiguration() throws IOException {

        Configuration configuration =
                configurationAdmin.getConfiguration(LoggingUpdaterConstants.PAX_LOGGING_CONFIGURATION_PID, "?");
        configuration.update();

    }