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

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

Introduction

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

Prototype

public MapConfiguration(Map map) 

Source Link

Document

Create a Configuration decorator around the specified Map.

Usage

From source file:com.nesscomputing.config.Config.java

/**
 * Creates a fixed configuration for the supplied key/value pairs. The number of elements passed in must be an
 * even number of elements, otherwise the last one is ignored.
 *
 * Config objects created from this method will not accept overrides from system properties.
 *//*from  w w w. ja  v  a  2 s. c o m*/
public static Config getFixedConfig(final String... keyValuePairs) {
    final ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();

    if (keyValuePairs != null) {
        for (final Iterator<String> it = Arrays.asList(keyValuePairs).iterator(); it.hasNext();) {
            final String key = it.next();
            if (it.hasNext()) {
                builder.put(key, it.next());
            } else {
                LOG.warn("Found an odd number of arguments for key/value pairs. Ignoring key %s", key);
                break;
            }
        }
    }
    return getFixedConfig(new MapConfiguration(builder.build()));
}

From source file:com.nesscomputing.testing.ServiceDefinitionBuilder.java

private Config getConfig(final Map<String, String> config) {
    final Map<String, String> configTweaks = Maps.newHashMap();
    for (TweakedModule tweakedModule : tweakedModules) {
        configTweaks.putAll(tweakedModule.getServiceConfigTweaks());
    }/* ww  w .  j  ava  2 s  .c o  m*/

    return Config.getOverriddenConfig(baseConfig, new MapConfiguration(config),
            new MapConfiguration(configKeys));
}

From source file:com.kixeye.chassis.bootstrap.ZookeeperConfigurationWriterTest.java

@Test
public void partialBasePathExists() throws Exception {
    Assert.assertNull(curatorFramework.checkExists().forPath(base));

    curatorFramework.create().forPath("/" + environmentName);

    Assert.assertNotNull(curatorFramework.checkExists().forPath("/" + environmentName));

    try (CuratorFramework zkCurator = createCuratorFramework()) {
        ZookeeperConfigurationWriter writer = new ZookeeperConfigurationWriter(applicationName, environmentName,
                version, zkCurator, false);
        writer.write(new MapConfiguration(props), new DefaultPropertyFilter());

        Assert.assertEquals(val1, new String(curatorFramework.getData().forPath(base + "/" + key1)));
    }/*from ww w .ja  v  a 2 s. c  o  m*/
}

From source file:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQLController.java

/**
 * Override a {@link Config} to set <code>ness.db.[db-name].uri</code> to a unique
 * database in the cluster./*from  ww w  . j  av  a2 s  . c  o m*/
 */
public Config getTweakedConfig(Config config, String dbModuleName) {
    return Config.getOverriddenConfig(config, new MapConfiguration(getConfigurationTweak(dbModuleName)));
}

From source file:com.liferay.portal.configuration.ConfigurationImpl.java

public void addProperties(Properties properties) {
    try {/*from   www. j av a 2  s.  c  om*/
        ComponentProperties componentProperties = _componentConfiguration.getProperties();

        AggregatedProperties aggregatedProperties = (AggregatedProperties) componentProperties
                .toConfiguration();

        Field field1 = CompositeConfiguration.class.getDeclaredField("configList");

        field1.setAccessible(true);

        // Add to configList of base conf

        List<Configuration> configurations = (List<Configuration>) field1.get(aggregatedProperties);

        MapConfiguration newConfiguration = new MapConfiguration(properties);

        configurations.add(0, newConfiguration);

        // Add to configList of AggregatedProperties itself

        Class<?> clazz = aggregatedProperties.getClass();

        Field field2 = clazz.getDeclaredField("baseConf");

        field2.setAccessible(true);

        CompositeConfiguration compositeConfiguration = (CompositeConfiguration) field2
                .get(aggregatedProperties);

        configurations = (List<Configuration>) field1.get(compositeConfiguration);

        configurations.add(0, newConfiguration);

        clearCache();
    } catch (Exception e) {
        _log.error("The properties could not be added", e);
    }
}

From source file:com.feedzai.fos.impl.weka.config.WekaModelConfig.java

private void parseModelConfig() throws FOSException {
    configuration = new MapConfiguration((Map) modelConfig.getProperties());
    classIndex = this.modelConfig.getIntProperty(CLASS_INDEX, -1);
    if (classIndex < 0) {
        classIndex = this.modelConfig.getAttributes().size() - 1;
    }/*from  w ww  .j a va  2 s .c  o  m*/

    String modelFile = configuration.getString(MODEL_FILE);
    if (modelFile != null) {
        this.model = new File(modelFile);
    }

    String formatValue = configuration.getString(CLASSIFIER_FORMAT);
    if (formatValue != null) {
        ModelDescriptor.Format format = ModelDescriptor.Format.valueOf(formatValue);
        this.modelDescriptor = new ModelDescriptor(format, modelFile);
    }

    classifierThreadSafe = configuration.getBoolean(IS_CLASSIFIER_THREAD_SAFE,
            false /* defaults to Pool implementation*/);

    String uuid = configuration.getString(ID);
    if (uuid != null) {
        this.id = UUID.fromString(uuid);
    }
}

From source file:com.nesscomputing.service.discovery.server.TestConfiguredStaticAnnouncements.java

@Before
public void spinup() throws Exception {
    final Map<String, String> announceConfig = ImmutableMap.<String, String>builder()
            .put("org.quartz.threadPool.threadCount", "1")
            .put("ness.discovery.static-announce.65f57132-8415-422e-b44a-7543dda54858.name", "foo")
            .put("ness.discovery.static-announce.65f57132-8415-422e-b44a-7543dda54858.scheme", "http")
            .put("ness.discovery.static-announce.65f57132-8415-422e-b44a-7543dda54858.address", "127.0.0.1")
            .put("ness.discovery.static-announce.65f57132-8415-422e-b44a-7543dda54858.port", "12345")
            .put("ness.discovery.static-announce.65f57132-8415-422e-b44a-7543dda54858.type", "bar").build();

    System.setProperty("ness.discovery.enabled", "true");
    server = new DiscoveryServerMain() {
        @Override//from  ww  w .j  a v  a2 s . c om
        public Config getConfig() {
            final File tmpDir = Files.createTempDir();
            tmpDir.deleteOnExit();
            final String httpPort = Integer.toString(findUnusedPort());

            serverBase = "http://localhost:" + httpPort;

            System.setProperty("galaxy.internal.port.http", httpPort);
            System.setProperty("ness.zookeeper.dataDir", tmpDir.getAbsolutePath());
            System.setProperty("ness.zookeeper.clientPort", Integer.toString(findUnusedPort()));
            System.setProperty("ness.jmx.enabled", "false");

            final int port1 = findUnusedPort();
            final int port2 = findUnusedPort();
            System.setProperty("ness.zookeeper.server.1", format("127.0.0.1:%d:%d", port1, port2));
            System.setProperty("ness.zookeeper.clientPortAddress", "127.0.0.1");

            return Config.getOverriddenConfig(
                    Config.getConfig(URI.create("classpath:/config"), "discovery-server"),
                    new MapConfiguration(announceConfig));
        }
    };

    server.startServer();

    Guice.createInjector(Stage.PRODUCTION, new AbstractModule() {
        @Override
        protected void configure() {
            binder().requireExplicitBindings();
            binder().disableCircularProxies();

            install(new ConfigModule(Config.getFixedConfig(new SystemConfiguration())));
            install(new LifecycleModule(ServiceDiscoveryLifecycle.class));
            install(new NessJacksonModule());
            install(new DiscoveryClientModule(true));
        }
    }).injectMembers(this);

    lifecycle.executeTo(LifecycleStage.START_STAGE);
}

From source file:com.kixeye.chassis.bootstrap.ZookeeperConfigurationWriterTest.java

@Test
public void basePathExists_noOverwrite() throws Exception {
    Assert.assertNull(curatorFramework.checkExists().forPath(base));

    try (CuratorFramework zkCurator = createCuratorFramework()) {
        ZookeeperConfigurationWriter writer = new ZookeeperConfigurationWriter(applicationName, environmentName,
                version, zkCurator, false);
        writer.write(new MapConfiguration(props), new DefaultPropertyFilter());

        Assert.assertEquals(val1, new String(curatorFramework.getData().forPath(base + "/" + key1)));
        Assert.assertEquals(val2, new String(curatorFramework.getData().forPath(base + "/" + key2)));

        try {//from w  ww.j  ava2 s  . c  o  m
            writer.write(new MapConfiguration(props), new DefaultPropertyFilter());
            Assert.fail();
        } catch (BootstrapException e) {
            //expected
        }
    }
}

From source file:com.yahoo.bard.webservice.config.LayeredFileSystemConfig.java

/**
 * Build a Layered File System Configuration, using first the environment and an application configuration source,
 * then drill down into available modules and load each of them in package dependency order.
 *///from  ww  w. j ava 2 s .c  o  m
@SuppressWarnings(value = "unchecked")
public LayeredFileSystemConfig() {
    masterConfiguration = new CompositeConfiguration();
    masterConfiguration.setThrowExceptionOnMissing(true);
    runtimeProperties = new Properties();

    try {

        List<Configuration> userConfig = loader.loadConfigurations(USER_CONFIG_FILE_NAME);

        // User configuration provides overrides for configuration on a specific environment or specialized role
        if (userConfig.size() > 1) {
            List<Resource> resources = loader.loadResourcesWithName(USER_CONFIG_FILE_NAME)
                    .collect(Collectors.toList());
            LOG.error(TOO_MANY_USER_CONFIGS.logFormat(resources.toString()));
            throw new SystemConfigException(TOO_MANY_USER_CONFIGS.format(resources.size()));
        }

        // Test application configuration provides overrides for configuration in a testing environment
        List<Configuration> testApplicationConfig = loader.loadConfigurationsNoJars(TEST_CONFIG_FILE_NAME);

        // Application configuration defines configuration at an application level for a bard instance
        List<Configuration> applicationConfig = loader.loadConfigurations(APPLICATION_CONFIG_FILE_NAME);

        if (applicationConfig.size() > 1) {
            List<Resource> resources = loader.loadResourcesWithName(APPLICATION_CONFIG_FILE_NAME)
                    .collect(Collectors.toList());
            LOG.error(TOO_MANY_APPLICATION_CONFIGS.logFormat(resources.toString()));
            throw new SystemConfigException(TOO_MANY_APPLICATION_CONFIGS.format(resources.size()));
        }

        // Environment config has higher priority than java system properties
        // Java system properties have higher priority than file based configuration
        // Also, a runtime map is maintained to support on-the-fly configuration changes

        // Load the rest of the config "top down" through the layers, in highest to lowest precedence
        Stream.of(Stream.of(new MapConfiguration(runtimeProperties)), Stream.of(new EnvironmentConfiguration()),
                Stream.of(new SystemConfiguration()), userConfig.stream(), testApplicationConfig.stream(),
                applicationConfig.stream()).flatMap(Function.identity()).filter(Objects::nonNull)
                .forEachOrdered(masterConfiguration::addConfiguration);

        // Use the config which has been loaded to identify module dependencies
        List<String> dependentModules = (List<String>) masterConfiguration
                .getList(ConfigurationGraph.DEPENDENT_MODULE_KEY, Collections.<String>emptyList());

        // Add module dependencies to the master configuration
        new ModuleLoader(loader).getConfigurations(dependentModules)
                .forEach(masterConfiguration::addConfiguration);
    } catch (IOException e) {
        throw new SystemConfigException(e);
    }
}

From source file:com.kixeye.chassis.bootstrap.ZookeeperConfigurationWriterTest.java

@Test
public void basePathExists_overwrite() throws Exception {
    Assert.assertNull(curatorFramework.checkExists().forPath(base));

    try (CuratorFramework zkCurator = createCuratorFramework()) {
        ZookeeperConfigurationWriter writer = new ZookeeperConfigurationWriter(applicationName, environmentName,
                version, zkCurator, true);

        writer.write(new MapConfiguration(props), new DefaultPropertyFilter());

        Assert.assertEquals(val1, new String(curatorFramework.getData().forPath(base + "/" + key1)));
        Assert.assertEquals(val2, new String(curatorFramework.getData().forPath(base + "/" + key2)));

        String key3 = RandomUtils.nextInt() + "";
        String val3 = RandomUtils.nextInt() + "";
        String newVal1 = RandomUtils.nextInt() + "";

        props.clear();/*from   w ww .  j  a  v  a 2  s  .c  o m*/

        //updates key1
        props.put(key1, newVal1);
        //adds key3
        props.put(key3, val3);

        //key2 should be deleted

        writer.write(new MapConfiguration(props), new DefaultPropertyFilter());

        Assert.assertEquals(newVal1, new String(curatorFramework.getData().forPath(base + "/" + key1)));
        Assert.assertEquals(val3, new String(curatorFramework.getData().forPath(base + "/" + key3)));
        Assert.assertNull(curatorFramework.checkExists().forPath(base + "/" + key2));
    }
}