Esempio n. 1
0
 @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;
 }
Esempio n. 2
0
 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 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;
 }
 @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);
     }
   }
 }
Esempio n. 5
0
  // 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;
  }
 /**
  * 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);
   }
 }
  /**
   * Set the values of an OSGi configuration for a given PID.
   *
   * @param pid The PID of the OSGi component to update
   * @param properties The properties and values of the config to update
   * @return true if the properties were updated successfully
   */
  public boolean setProperties(final String pid, final Map<String, Object> properties) {
    try {
      Configuration conf = configAdmin.getConfiguration(pid);

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

      if (props == null) {
        props = new Hashtable<String, Object>();
      }

      /* props is of type org.apache.felix.cm.impl.CaseInsensitiveDictionary which
       * contains an internal HashTable and doesn't contain a putAll(Map) method.
       * Iterate over the map and put the values into the Dictionary individually.
       * Remove null values from HashMap as HashTable doesn't support them. */
      for (Map.Entry<String, Object> entry : properties.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        props.put(key, value != null ? value : StringUtils.EMPTY);
      }

      conf.update(props);
    } catch (IOException e) {
      LOGGER.error("Could not set property", e);
      return false;
    }

    return true;
  }
  protected 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;
    }
  }
  @Test
  public void testValidConfiguration() {
    configureActionProvider();
    Dictionary<String, Object> testDictionary = new Hashtable<>();

    testDictionary.put(RegistryObjectMetacardType.REGISTRY_ID, SAMPLE_REGISTRY_ID);

    when(configuration.getProperties()).thenReturn(testDictionary);

    List<Action> actions = actionProvider.getActions(configuration);

    assertThat(actions.size(), is(1));
    assertThat(
        actions.get(0).getUrl().toString(),
        is(
            SAMPLE_PROTOCOL
                + SAMPLE_IP
                + ":"
                + SAMPLE_PORT
                + SAMPLE_SERVICES_ROOT
                + SAMPLE_PATH
                + metacard
                    .getAttribute(RegistryObjectMetacardType.REGISTRY_ID)
                    .getValue()
                    .toString()
                + PATH_AND_FORMAT));
  }
Esempio n. 10
0
  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);
    }
  }
 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 testNullRegistryIdConfiguration() {
    configureActionProvider();

    when(configuration.getProperties()).thenReturn(new Hashtable<>());

    List<Action> actions = actionProvider.getActions(configuration);

    assertThat(actions.size(), is(0));
  }
  @SuppressWarnings("rawtypes")
  @Test(priority = 3)
  public void testCreateNew() throws Exception {
    config.put("property1", "value1");
    config.put("property2", "value2");

    configObjectService.create(rname, id, json(config), false).getOrThrow();

    ConfigObjectService.ParsedId parsedId = configObjectService.getParsedId(rname, id);
    Configuration config = configObjectService.findExistingConfiguration(parsedId);
    assertNotNull(config);
    assertNotNull(config.getProperties());

    Dictionary properties = config.getProperties();
    EnhancedConfig enhancedConfig = new JSONEnhancedConfig();
    JsonValue value = enhancedConfig.getConfiguration(properties, rname.toString(), false);
    assertTrue(value.keys().contains("property1"));
    Assert.assertEquals(value.get("property1").asString(), "value1");
  }
 @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);
 }
  /**
   * 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);
  }
  @Override
  public synchronized void unregisterConfiguration(Configuration configuration) {

    Dictionary<String, Object> properties = configuration.getProperties();

    T configurable = Configurable.createConfigurable(getMetatype(), properties);

    long companyId = configurable.companyId();

    _configurations.remove(companyId);
  }
  @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());
  }
 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);
   }
 }
  @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));
  }
  @SuppressWarnings("rawtypes")
  @Test(priority = 6)
  public void testUpdate() throws Exception {
    config.put("property1", "newvalue1");
    config.put("property2", "newvalue2");

    when(enhancedConfig.getConfiguration(any(Dictionary.class), any(String.class), eq(false)))
        .thenReturn(json(config));

    configObjectService.update(rname, id, json(config)).getOrThrow();

    ConfigObjectService.ParsedId parsedId = configObjectService.getParsedId(rname, id);
    Configuration config = configObjectService.findExistingConfiguration(parsedId);
    assertNotNull(config);
    assertNotNull(config.getProperties());

    Dictionary properties = config.getProperties();
    JSONEnhancedConfig enhancedConfig = new JSONEnhancedConfig();
    JsonValue value = enhancedConfig.getConfiguration(properties, rname.toString(), false);
    assertTrue(value.keys().contains("property1"));
    Assert.assertEquals(value.get("property1").asString(), "newvalue1");
  }
  @Test
  public void testConfigurationBadUri() {
    configureActionProvider(SAMPLE_PROTOCOL, "23^&*#", SAMPLE_PORT, SAMPLE_SERVICES_ROOT);
    Dictionary<String, Object> testDictionary = new Hashtable<>();

    testDictionary.put(RegistryObjectMetacardType.REGISTRY_ID, SAMPLE_REGISTRY_ID);

    when(configuration.getProperties()).thenReturn(testDictionary);

    List<Action> actions = actionProvider.getActions(configuration);

    assertThat(actions.size(), is(0));
  }
Esempio n. 22
0
  @Test
  public void test_not_updated_new_configuration_not_bound_after_bundle_uninstall()
      throws IOException, BundleException {
    final String pid = "test_not_updated_new_configuration_not_bound_after_bundle_uninstall";

    // create a configuration but do not update with properties
    final Configuration newConfig = configure(pid, null, false);
    TestCase.assertNull(newConfig.getProperties());
    TestCase.assertNull(newConfig.getBundleLocation());

    // start and settle bundle
    bundle = installBundle(pid);
    bundle.start();
    delay();

    // ensure no properties provided to bundle
    final ManagedServiceTestActivator tester = ManagedServiceTestActivator.INSTANCE;
    TestCase.assertNotNull("Activator not started !!", tester);
    TestCase.assertNull("Expect no properties after Service Registration", tester.props);
    TestCase.assertEquals("Expect a single update call", 1, tester.numManagedServiceUpdatedCalls);

    // assert configuration is still unset but bound
    TestCase.assertNull(newConfig.getProperties());
    TestCase.assertEquals(bundle.getLocation(), newConfig.getBundleLocation());

    // uninstall bundle, should unbind configuration
    bundle.uninstall();
    bundle = null;

    delay();

    // assert configuration is still unset and unbound
    TestCase.assertNull(newConfig.getProperties());
    TestCase.assertNull(newConfig.getBundleLocation());

    // remove the configuration for good
    deleteConfig(pid);
  }
Esempio n. 23
0
  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();
  }
Esempio n. 24
0
  @Test
  public void test_create_with_location_unbind_before_service_supply()
      throws BundleException, IOException {

    final String pid = "test_create_with_location_unbind_before_service_supply";
    final String dummyLocation = "http://some/dummy/location";

    // 1. create and statically bind the configuration
    final Configuration config = configure(pid, dummyLocation, false);
    TestCase.assertEquals(pid, config.getPid());
    TestCase.assertEquals(dummyLocation, config.getBundleLocation());

    // 2. update configuration
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put(PROP_NAME, PROP_NAME);
    config.update(props);
    TestCase.assertEquals(PROP_NAME, config.getProperties().get(PROP_NAME));
    TestCase.assertEquals(pid, config.getPid());
    TestCase.assertEquals(dummyLocation, config.getBundleLocation());

    // 3. (statically) set location to null
    config.setBundleLocation(null);
    TestCase.assertNull(config.getBundleLocation());

    // 4. install bundle with service
    bundle = installBundle(pid);
    bundle.start();
    delay();

    final ManagedServiceTestActivator tester = ManagedServiceTestActivator.INSTANCE;
    TestCase.assertNotNull("Activator not started !!", tester);

    // assert activater has configuration (two calls, one per pid)
    TestCase.assertNotNull("Expect Properties after Service Registration", tester.props);
    TestCase.assertEquals("Expect a single update call", 1, tester.numManagedServiceUpdatedCalls);

    TestCase.assertEquals(bundle.getLocation(), config.getBundleLocation());

    bundle.uninstall();
    bundle = null;

    delay();

    // statically bound configurations must remain bound after bundle
    // uninstall
    TestCase.assertNull(config.getBundleLocation());

    // remove the configuration for good
    deleteConfig(pid);
  }
Esempio n. 25
0
  @Override
  public void start(BundleContext bundleContext) throws Exception {
    try {
      this.bundleContext = bundleContext;
      log.debug("Initializing bundle {}.", bundleContext.getBundle().getBundleId());
      camelContext = createCamelContext();

      camelContext.addRoutes(this);
      ConfigurationAdmin configurationAdmin = requiredService(ConfigurationAdmin.class);
      Configuration camelKuraConfig = configurationAdmin.getConfiguration("kura.camel");
      if (camelKuraConfig != null && camelKuraConfig.getProperties() != null) {
        Object routePropertyValue = camelKuraConfig.getProperties().get(camelXmlRoutesProperty());
        if (routePropertyValue != null) {
          InputStream routesXml =
              new ByteArrayInputStream(routePropertyValue.toString().getBytes());
          RoutesDefinition loadedRoutes = camelContext.loadRoutesDefinition(routesXml);
          camelContext.addRouteDefinitions(loadedRoutes.getRoutes());
        }
      }

      beforeStart(camelContext);
      log.debug("About to start Camel Kura router: {}", getClass().getName());
      camelContext.start();
      producerTemplate = camelContext.createProducerTemplate();
      consumerTemplate = camelContext.createConsumerTemplate();
      log.debug("Bundle {} started.", bundleContext.getBundle().getBundleId());
    } catch (Throwable e) {
      String errorMessage = "Problem when starting Kura module " + getClass().getName() + ":";
      log.warn(errorMessage, e);

      // Print error to the Kura console.
      System.err.println(errorMessage);
      e.printStackTrace();

      throw e;
    }
  }
 /**
  * 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);
   }
 }
  @Test(priority = 8)
  public void testDelete() throws Exception {
    when(enhancedConfig.getConfiguration(any(Dictionary.class), any(String.class), eq(false)))
        .thenReturn(json(object(field(ResourceResponse.FIELD_CONTENT_REVISION, "revX"))));

    configObjectService.delete(rname, "0").getOrThrow();

    ConfigObjectService.ParsedId parsedId = configObjectService.getParsedId(rname, id);
    Configuration config = configObjectService.findExistingConfiguration(parsedId);

    // "deleting" the object does not remove it from the configAdmin but it does invalidate the
    // config
    assertNotNull(config);
    assertNull(config.getProperties());
  }
  /**
   * 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;
  }
 @Test
 @SuppressWarnings({"unchecked", "rawtypes"})
 public void testConfiguration_shouldHaveWrittenTheLaterOne() throws Exception {
   ServiceReference[] allServiceReferences =
       ctx.getAllServiceReferences(ConfigurationAdmin.class.getName(), null);
   for (ServiceReference serviceReference : allServiceReferences) {
     ConfigurationAdmin service = (ConfigurationAdmin) ctx.getService(serviceReference);
     try {
       org.osgi.service.cm.Configuration configuration = service.getConfiguration("tests");
       assertEquals("myvalue2", configuration.getProperties().get("mykey"));
       return;
     } catch (Exception e) {
       // continue
     }
   }
   fail();
 }
Esempio n. 30
0
  @Test
  public void testLocalFabricCluster() throws Exception {
    // Test autostartup.
    assertNotNull(fabricService);
    Thread.sleep(DEFAULT_WAIT);
    Container[] containers = fabricService.getContainers();
    assertNotNull(containers);
    assertEquals("Expected to find 1 container", 1, containers.length);
    assertEquals("Expected to find the root container", "root", containers[0].getId());

    // Test that a generated password exists
    // We don't inject the configuration admin as it causes issues when the tracker gets closed.
    ConfigurationAdmin configurationAdmin = getOsgiService(ConfigurationAdmin.class);
    org.osgi.service.cm.Configuration configuration =
        configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper");
    Dictionary<String, Object> dictionary = configuration.getProperties();
    assertNotNull("Expected a generated zookeeper password", dictionary.get("zookeeper.password"));
  }