Example usage for org.apache.commons.configuration HierarchicalConfiguration HierarchicalConfiguration

List of usage examples for org.apache.commons.configuration HierarchicalConfiguration HierarchicalConfiguration

Introduction

In this page you can find the example usage for org.apache.commons.configuration HierarchicalConfiguration HierarchicalConfiguration.

Prototype

public HierarchicalConfiguration() 

Source Link

Document

Creates a new instance of HierarchicalConfiguration.

Usage

From source file:org.lable.oss.dynamicconfig.core.ConfigurationInitializer.java

/**
 * Use system properties to initialize a configuration instance.
 *
 * @param defaults     Default configuration. Any keys not overridden by the dynamic configuration will remain as
 *                     set here./*from ww  w. ja  va  2  s .c om*/
 * @param deserializer Deserializer used to interpret the language the configuration file is written in.
 * @return Thread-safe configuration instance.
 * @throws ConfigurationException Thrown when the required system properties are not set.
 */
public static Configuration configureFromProperties(HierarchicalConfiguration defaults,
        HierarchicalConfigurationDeserializer deserializer) throws ConfigurationException {
    String desiredSourceName = System.getProperty(LIBRARY_PREFIX + ".type");
    if (desiredSourceName == null) {
        throw new ConfigurationException("System property " + LIBRARY_PREFIX + ".type is not set.");
    }

    List<ConfigurationSource> sources = detectConfigurationSourceServiceProviders();
    ConfigurationSource desiredSource = null;
    for (ConfigurationSource source : sources) {
        if (source.name().equals(desiredSourceName)) {
            desiredSource = source;
            break;
        }
    }

    if (desiredSource == null) {
        throw new ConfigurationException("Could not find a ConfigurationSource with name " + desiredSourceName);
    }

    Configuration sourceConfiguration = gatherPropertiesFor(desiredSource);
    desiredSource.configure(sourceConfiguration);

    // Create the configuration object with its defaults loaded last. The combiner expects them in that order.
    final CombinedConfiguration allConfig = new CombinedConfiguration(new OverrideCombiner());
    final ConcurrentConfiguration concurrentConfiguration = new ConcurrentConfiguration(allConfig,
            desiredSource);

    // Add an empty named placeholder for the runtime configuration that will be loaded later on.
    allConfig.addConfiguration(new HierarchicalConfiguration(), "runtime");
    if (defaults != null) {
        allConfig.addConfiguration(defaults, "defaults");
    }

    // Listens to changes in the configuration source and updates the configuration tree.
    ConfigChangeListener listener = fresh -> {
        logger.info("New runtime configuration received.");
        concurrentConfiguration.updateConfiguration("runtime", fresh);
    };

    desiredSource.load(deserializer, listener);

    // Listen for future changes in the run-time configuration.
    desiredSource.listen(deserializer, listener);

    return concurrentConfiguration;
}

From source file:org.lable.oss.dynamicconfig.core.DependencyInjectionIT.java

@Test
public void diProviderTestWithDefaults() {
    System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".type", "classpath");
    System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".classpath.path", "test.yml");
    final HierarchicalConfiguration defaults = new HierarchicalConfiguration();
    defaults.setProperty("type.string", "Not okay");
    defaults.setProperty("only.in.defaults", "XXX");

    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override//from  w  w w  .  j  av  a2  s .c o m
        protected void configure() {
            bind(HierarchicalConfiguration.class).annotatedWith(ConfigurationDefaults.class)
                    .toInstance(defaults);
            bind(HierarchicalConfigurationDeserializer.class).to(YamlDeserializer.class);
            bind(Configuration.class).toProvider(ConfigurationProvider.class);
        }
    });

    Configuration configuration = injector.getInstance(Configuration.class);

    // As set in test.yml:
    assertThat(configuration.getString("type.string"), is("Okay"));
    // Overridden in this test:
    assertThat(configuration.getString("only.in.defaults"), is("XXX"));
}

From source file:org.lable.oss.dynamicconfig.core.DependencyInjectionIT.java

@Test
public void diModuleTestWithDefaults() {
    System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".type", "classpath");
    System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".classpath.path", "test.yml");
    final HierarchicalConfiguration defaults = new HierarchicalConfiguration();
    defaults.setProperty("type.string", "Not okay");
    defaults.setProperty("only.in.defaults", "XXX");

    final Injector injector = Guice.createInjector(new AbstractModule() {
        @Override//www .  java2s. c  o m
        protected void configure() {
            install(new DynamicConfigModule());
            bind(HierarchicalConfiguration.class).annotatedWith(ConfigurationDefaults.class)
                    .toInstance(defaults);
        }
    });

    Configuration configuration = injector.getInstance(Configuration.class);

    // As set in test.yml:
    assertThat(configuration.getString("type.string"), is("Okay"));
    // Overridden in this test:
    assertThat(configuration.getString("only.in.defaults"), is("XXX"));
}

From source file:org.lable.oss.dynamicconfig.provider.zookeeper.ZookeepersAsConfigSourceIT.java

@Test
public void configurationMonitorTest() throws Exception {
    setData("\n");

    System.setProperty(LIBRARY_PREFIX + ".type", "zookeeper");
    System.setProperty(LIBRARY_PREFIX + ".zookeeper.znode", "/config");
    System.setProperty(LIBRARY_PREFIX + ".zookeeper.quorum", zookeeperHost);
    System.setProperty(LIBRARY_PREFIX + "." + APPNAME_PROPERTY, "test");
    HierarchicalConfiguration defaults = new HierarchicalConfiguration();
    defaults.setProperty("key", "DEFAULT");

    Configuration configuration = ConfigurationInitializer.configureFromProperties(defaults,
            new YamlDeserializer());

    final AtomicInteger count = new AtomicInteger(0);
    Precomputed<String> precomputed = Precomputed.monitorByUpdate(configuration, config -> {
        count.incrementAndGet();/*  w w w . ja v  a2s  .  c  o m*/
        return config.getString("key");
    });

    assertThat(precomputed.get(), is("DEFAULT"));
    assertThat(count.get(), is(1));
    assertThat(configuration.getString("key"), is("DEFAULT"));

    TimeUnit.MILLISECONDS.sleep(300);

    assertThat(precomputed.get(), is("DEFAULT"));
    assertThat(count.get(), is(1));

    setData("key: AAA");
    TimeUnit.MILLISECONDS.sleep(300);

    assertThat(count.get(), is(1));
    assertThat(configuration.getString("key"), is("AAA"));
    assertThat(precomputed.get(), is("AAA"));
    assertThat(count.get(), is(2));
    assertThat(precomputed.get(), is("AAA"));
    assertThat(count.get(), is(2));
}

From source file:org.lable.oss.dynamicconfig.provider.zookeeper.ZookeepersAsConfigSourceIT.java

@Test
public void viaInitializerTest() throws Exception {
    setData("\n");

    System.setProperty(LIBRARY_PREFIX + ".type", "zookeeper");
    System.setProperty(LIBRARY_PREFIX + ".zookeeper.znode", "/config");
    System.setProperty(LIBRARY_PREFIX + ".zookeeper.quorum", zookeeperHost);
    System.setProperty(LIBRARY_PREFIX + "." + APPNAME_PROPERTY, "test");
    HierarchicalConfiguration defaults = new HierarchicalConfiguration();
    defaults.setProperty("key", "DEFAULT");

    Configuration configuration = ConfigurationInitializer.configureFromProperties(defaults,
            new YamlDeserializer());

    assertThat(configuration.getString("key"), is("DEFAULT"));

    setData("key: AAA");
    TimeUnit.MILLISECONDS.sleep(300);

    assertThat(configuration.getString("key"), is("AAA"));
}

From source file:org.lable.oss.dynamicconfig.serialization.yaml.JsonSerializerTest.java

@Test
public void testSave() throws ConfigurationException, IOException {
    HierarchicalConfigurationSerializer serializer = new JsonSerializer();
    HierarchicalConfiguration configuration = new HierarchicalConfiguration();
    configuration.setProperty("type.unicodeString", "");
    configuration.setProperty("type.booleanFalse", false);
    configuration.setProperty("type.booleanTrue", true);
    configuration.setProperty("type.list", Arrays.asList("1", "2", "3"));

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    serializer.serialize(configuration, output);
    String json = IOUtils.toString(new StringReader(output.toString("UTF-8")));
    JsonNode tree = mapper.readTree(json);

    JsonNode nodeType = tree.get("type");
    assertThat(nodeType.get("unicodeString").textValue(), is(""));
    assertThat(nodeType.get("booleanFalse").booleanValue(), is(false));
    assertThat(nodeType.get("booleanTrue").booleanValue(), is(true));
    ArrayNode listString = (ArrayNode) nodeType.get("list");
    assertThat(listString, instanceOf(ArrayNode.class));
}

From source file:org.lable.oss.dynamicconfig.serialization.yaml.YamlDeserializer.java

/**
 * {@inheritDoc}/*ww  w  .  ja v  a2s  . c om*/
 */
@Override
public HierarchicalConfiguration deserialize(InputStream input) throws ConfigurationException {
    String content;
    try {
        content = IOUtils.toString(input);
    } catch (IOException e) {
        throw new ConfigurationException("Failed to read from stream.");
    }

    if (content.isEmpty()) {
        return new HierarchicalConfiguration();
    }

    Object tree;
    try {
        tree = yaml.load(content);
    } catch (ParserException e) {
        throw new ConfigurationException("Failed to parse input as valid YAML.", e);
    }
    HierarchicalConfiguration configuration = new HierarchicalConfiguration();
    traverseTreeAndLoad(configuration.getRootNode(), tree);
    return configuration;
}

From source file:org.midonet.brain.services.vxgw.BridgeMonitorTest.java

@Before
public void before() throws Exception {
    HierarchicalConfiguration config = new HierarchicalConfiguration();
    BrainTestUtils.fillTestConfig(config);
    Injector injector = Guice.createInjector(BrainTestUtils.modules(config));

    Directory directory = injector.getInstance(Directory.class);
    BrainTestUtils.setupZkTestDirectory(directory);

    this.dataClient = injector.getInstance(DataClient.class);
    this.zkConnWatcher = new ZookeeperConnectionWatcher();

    host = new Host();
    host.setName("TestHost");
    hostId = dataClient.hostsCreate(UUID.randomUUID(), host);

    TunnelZone tz = new TunnelZone();
    tz.setName("TestTz");
    UUID tzId = dataClient.tunnelZonesCreate(tz);
    TunnelZone.HostConfig zoneHost = new TunnelZone.HostConfig(hostId);
    zoneHost.setIp(tunnelZoneHostIp);//from  ww w.  ja  va 2  s. c  o  m
    dataClient.tunnelZonesAddMembership(tzId, zoneHost);

    vtep = new VTEP();
    vtep.setId(vtepMgmtIp);
    vtep.setMgmtPort(vtepMgmntPort);
    vtep.setTunnelZone(tzId);
    dataClient.vtepCreate(vtep);
}

From source file:org.midonet.brain.services.vxgw.HostMonitorTest.java

@Before
public void before() throws Exception {
    HierarchicalConfiguration config = new HierarchicalConfiguration();
    BrainTestUtils.fillTestConfig(config);
    Injector injector = Guice.createInjector(BrainTestUtils.modules(config));

    Directory directory = injector.getInstance(Directory.class);
    BrainTestUtils.setupZkTestDirectory(directory);

    dataClient = injector.getInstance(DataClient.class);
    zkConnWatcher = new ZookeeperConnectionWatcher();
}

From source file:org.midonet.brain.services.vxgw.TunnelZoneMonitorTest.java

@Before
public void before() throws Exception {
    HierarchicalConfiguration config = new HierarchicalConfiguration();
    BrainTestUtils.fillTestConfig(config);
    Injector injector = Guice.createInjector(BrainTestUtils.modules(config));

    Directory directory = injector.getInstance(Directory.class);
    BrainTestUtils.setupZkTestDirectory(directory);

    this.dataClient = injector.getInstance(DataClient.class);
    this.zkConnWatcher = new ZookeeperConnectionWatcher();
}