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

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

Introduction

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

Prototype

public CompositeConfiguration() 

Source Link

Document

Creates an empty CompositeConfiguration object which can then be added some other Configuration files

Usage

From source file:ninja.utils.NinjaPropertiesImpl.java

public NinjaPropertiesImpl(NinjaMode ninjaMode, String externalConfigurationPath) {

    this.ninjaMode = ninjaMode;

    // This is our main configuration.
    // In the following we'll read the individual configurations and merge
    // them into the composite configuration at the end.
    compositeConfiguration = new CompositeConfiguration();

    // That is the default config.
    PropertiesConfiguration defaultConfiguration = null;

    // Config of prefixed mode corresponding to current mode (eg.
    // %test.myproperty=...)
    Configuration prefixedDefaultConfiguration = null;

    // (Optional) Config set via a system property
    PropertiesConfiguration externalConfiguration = null;

    // (Optional) Config of prefixed mode corresponding to current mode (eg.
    // %test.myproperty=...)
    Configuration prefixedExternalConfiguration = null;

    // First step => load application.conf and also merge properties that
    // correspond to a mode into the configuration.

    defaultConfiguration = SwissKnife.loadConfigurationInUtf8(NinjaProperties.CONF_FILE_LOCATION_BY_CONVENTION);

    if (defaultConfiguration != null) {
        // Second step:
        // Copy special prefix of mode to parent configuration
        // By convention it will be something like %test.myproperty
        prefixedDefaultConfiguration = defaultConfiguration.subset("%" + ninjaMode.name());

        // allow application.conf to be reloaded on changes in dev mode
        if (NinjaMode.dev == ninjaMode) {
            defaultConfiguration.setReloadingStrategy(new FileChangedReloadingStrategy());
        }/* w w w .j  a va  2  s .c  o  m*/

    } else {

        // If the property was set, but the file not found we emit
        // a RuntimeException
        String errorMessage = String.format(
                "Error reading configuration file. Make sure you got a default config file %s",
                NinjaProperties.CONF_FILE_LOCATION_BY_CONVENTION);

        logger.error(errorMessage);

        throw new RuntimeException(errorMessage);
    }

    // third step => load external configuration when a system property is defined.
    String ninjaExternalConf = externalConfigurationPath;

    if (ninjaExternalConf == null) {
        // if not set fallback to system property
        ninjaExternalConf = System.getProperty(NINJA_EXTERNAL_CONF);
    }

    if (ninjaExternalConf != null) {

        // only load it when the property is defined.

        externalConfiguration = SwissKnife.loadConfigurationInUtf8(ninjaExternalConf);

        // this should not happen:
        if (externalConfiguration == null) {

            String errorMessage = String.format(
                    "Ninja was told to use an external configuration%n" + " %s = %s %n."
                            + "But the corresponding file cannot be found.%n"
                            + " Make sure it is visible to this application and on the classpath.",
                    NINJA_EXTERNAL_CONF, ninjaExternalConf);

            logger.error(errorMessage);

            throw new RuntimeException(errorMessage);

        } else {

            // allow the external configuration to be reloaded at
            // runtime based on detected file changes
            final boolean shouldReload = Boolean.getBoolean(NINJA_EXTERNAL_RELOAD);
            if (shouldReload) {
                externalConfiguration.setReloadingStrategy(new FileChangedReloadingStrategy());
            }

            // Copy special prefix of mode to parent configuration
            // By convention it will be something like %test.myproperty
            prefixedExternalConfiguration = externalConfiguration.subset("%" + ninjaMode.name());
        }

    }

    // /////////////////////////////////////////////////////////////////////
    // Finally add the stuff to the composite configuration
    // Note: Configurations added earlier will overwrite configurations
    // added later.
    // /////////////////////////////////////////////////////////////////////

    if (prefixedExternalConfiguration != null) {
        compositeConfiguration.addConfiguration(prefixedExternalConfiguration);
    }

    if (externalConfiguration != null) {
        compositeConfiguration.addConfiguration(externalConfiguration);
    }

    if (prefixedDefaultConfiguration != null) {
        compositeConfiguration.addConfiguration(prefixedDefaultConfiguration);
    }

    if (defaultConfiguration != null) {
        compositeConfiguration.addConfiguration(defaultConfiguration);
    }

    // /////////////////////////////////////////////////////////////////////
    // Check that the secret is set or generate a new one if the property
    // does not exist
    // /////////////////////////////////////////////////////////////////////
    NinjaPropertiesImplTool.checkThatApplicationSecretIsSet(isProd(), new File("").getAbsolutePath(),
            defaultConfiguration, compositeConfiguration);

}

From source file:org.aksw.palmetto.webapp.config.PalmettoConfiguration.java

public static synchronized Configuration getInstance() {
    if (instance == null) {
        instance = new CompositeConfiguration();
        loadAdditionalProperties(DEFAULT_PALMETTO_PROPERTIES_FILE_NAME);
    }// ww  w  .ja  va 2  s .  com
    return instance;
}

From source file:org.apache.accumulo.core.conf.SiteConfiguration.java

@SuppressFBWarnings(value = "URLCONNECTION_SSRF_FD", justification = "location of props is specified by an admin")
private static ImmutableMap<String, String> createMap(URL accumuloPropsLocation,
        Map<String, String> overrides) {
    CompositeConfiguration config = new CompositeConfiguration();
    config.setThrowExceptionOnMissing(false);
    config.setDelimiterParsingDisabled(true);
    PropertiesConfiguration propsConfig = new PropertiesConfiguration();
    propsConfig.setDelimiterParsingDisabled(true);
    if (accumuloPropsLocation != null) {
        try {//from  w  ww. j  a va2 s  .co m
            propsConfig.load(accumuloPropsLocation.openStream());
        } catch (IOException | ConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
    }
    config.addConfiguration(propsConfig);

    // Add all properties in config file
    Map<String, String> result = new HashMap<>();
    config.getKeys().forEachRemaining(key -> result.put(key, config.getString(key)));

    // Add all overrides
    overrides.forEach(result::put);

    // Add sensitive properties from credential provider (if set)
    String credProvider = result.get(Property.GENERAL_SECURITY_CREDENTIAL_PROVIDER_PATHS.getKey());
    if (credProvider != null) {
        org.apache.hadoop.conf.Configuration hadoopConf = new org.apache.hadoop.conf.Configuration();
        hadoopConf.set(CredentialProviderFactoryShim.CREDENTIAL_PROVIDER_PATH, credProvider);
        for (Property property : Property.values()) {
            if (property.isSensitive()) {
                char[] value = CredentialProviderFactoryShim.getValueFromCredentialProvider(hadoopConf,
                        property.getKey());
                if (value != null) {
                    result.put(property.getKey(), new String(value));
                }
            }
        }
    }
    return ImmutableMap.copyOf(result);
}

From source file:org.apache.airavata.gfac.hadoop.handler.HadoopDeploymentHandler.java

private ClusterSpec whirrConfigurationToClusterSpec(HostDescription hostDescription, File workingDirectory)
        throws IOException, GFacHandlerException, ConfigurationException {
    File whirrConfig = getWhirrConfigurationFile(hostDescription, workingDirectory);
    CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
    Configuration configuration = new PropertiesConfiguration(whirrConfig);
    compositeConfiguration.addConfiguration(configuration);

    ClusterSpec hadoopClusterSpec = new ClusterSpec(compositeConfiguration);

    for (ClusterSpec.Property required : EnumSet.of(CLUSTER_NAME, PROVIDER, IDENTITY, CREDENTIAL,
            INSTANCE_TEMPLATES, PRIVATE_KEY_FILE)) {
        if (hadoopClusterSpec.getConfiguration().getString(required.getConfigName()) == null) {
            throw new IllegalArgumentException(String.format("Option '%s' not set.", required.getSimpleName()));
        }//ww w  .j  av a  2s. co  m
    }

    return hadoopClusterSpec;
}

From source file:org.apache.bookkeeper.bookie.BookieShell.java

public static void main(String argv[]) throws Exception {
    BookieShell shell = new BookieShell();
    if (argv.length <= 0) {
        shell.printShellUsage();//w w w.j a v a  2s  .com
        System.exit(-1);
    }

    CompositeConfiguration conf = new CompositeConfiguration();
    // load configuration
    if ("-conf".equals(argv[0])) {
        if (argv.length <= 1) {
            shell.printShellUsage();
            System.exit(-1);
        }
        conf.addConfiguration(new PropertiesConfiguration(new File(argv[1]).toURI().toURL()));

        String[] newArgv = new String[argv.length - 2];
        System.arraycopy(argv, 2, newArgv, 0, newArgv.length);
        argv = newArgv;
    }

    shell.setConf(conf);
    int res = shell.run(argv);
    System.exit(res);
}

From source file:org.apache.bookkeeper.common.conf.ConfigKeyTest.java

@Test
public void testGetList() {
    String keyName = runtime.getMethodName();
    List<String> defaultList = Lists.newArrayList("item1", "item2", "item3");
    ConfigKey key = ConfigKey.builder(keyName).required(true).type(Type.LIST).defaultValue(defaultList).build();

    Configuration conf = new CompositeConfiguration();

    // get default value
    assertEquals(defaultList, key.getList(conf));
    assertEquals(defaultList, key.get(conf));

    // set value/*from  ww  w.  ja  v a  2s  .  co m*/
    List<String> newList = Lists.newArrayList("item4", "item5", "item6");
    key.set(conf, newList);
    assertEquals(newList, key.getList(conf));
    assertEquals(newList, key.get(conf));

    // set string value
    newList = Lists.newArrayList("item7", "item8", "item9");
    conf.setProperty(key.name(), "item7,item8,item9");
    assertEquals(newList, key.getList(conf));
    assertEquals(newList, key.get(conf));
}

From source file:org.apache.bookkeeper.common.conf.ConfigKeyTest.java

@Test
public void testGetClass() {
    String keyName = runtime.getMethodName();
    Class defaultClass = TestFunctionA.class;
    ConfigKey key = ConfigKey.builder(keyName).required(true).type(Type.CLASS).defaultValue(defaultClass)
            .build();/*from w w w.  ja v  a  2  s  .  c o  m*/

    Configuration conf = new CompositeConfiguration();

    // get default value
    assertEquals(defaultClass, key.getClass(conf));
    assertEquals(defaultClass, key.get(conf));

    // set value
    Class newClass = TestFunctionB.class;
    key.set(conf, newClass);
    assertEquals(newClass, key.getClass(conf));
    assertEquals(newClass, key.get(conf));

    // set string value
    String newClassName = TestFunctionC.class.getName();
    conf.setProperty(key.name(), newClassName);
    assertEquals(TestFunctionC.class, key.getClass(conf));
    assertEquals(TestFunctionC.class, key.get(conf));
}

From source file:org.apache.bookkeeper.common.conf.ConfigKeyTest.java

@Test
public void testGetString() {
    String keyName = runtime.getMethodName();
    String defaultValue = "default-string-value";
    ConfigKey key = ConfigKey.builder(keyName).required(true).type(Type.STRING).defaultValue(defaultValue)
            .build();/* w w  w.j a  v  a  2  s .com*/

    Configuration conf = new CompositeConfiguration();

    // get default value
    assertEquals(defaultValue, key.getString(conf));
    assertEquals(defaultValue, key.get(conf));

    // set value
    String newValue = "new-string-value";
    key.set(conf, newValue);
    assertEquals(newValue, key.getString(conf));
    assertEquals(newValue, key.get(conf));
}

From source file:org.apache.bookkeeper.metastore.TestMetaStore.java

protected Configuration getConfiguration() {
    return new CompositeConfiguration();
}

From source file:org.apache.bookkeeper.stream.cluster.StandaloneStarter.java

static int doMain(String[] args) throws Exception {
    StarterArgs starterArgs = new StarterArgs();

    JCommander commander = new JCommander();
    try {//from  www.  jav a  2  s  .  co  m
        commander.setProgramName("standalone-starter");
        commander.addObject(starterArgs);
        commander.parse(args);
        if (starterArgs.help) {
            commander.usage();
            return 0;
        }
    } catch (Exception e) {
        commander.usage();
        return -1;
    }

    StreamClusterSpec.StreamClusterSpecBuilder specBuilder = StreamClusterSpec.builder();
    if (starterArgs.metadataServiceUri == null) {
        specBuilder = specBuilder.zkPort(starterArgs.zkPort).shouldStartZooKeeper(true);
    } else {
        ServiceURI serviceURI = ServiceURI.create(starterArgs.metadataServiceUri);
        specBuilder = specBuilder.metadataServiceUri(serviceURI).shouldStartZooKeeper(false);
    }

    CompositeConfiguration conf = new CompositeConfiguration();
    if (null != starterArgs.configFile) {
        PropertiesConfiguration propsConf = new PropertiesConfiguration(starterArgs.configFile);
        conf.addConfiguration(propsConf);
    }

    checkArgument(starterArgs.numBookies > 0, "Invalid number of bookies : " + starterArgs.numBookies);
    if (starterArgs.numBookies == 1) {
        conf.setProperty("dlog.bkcEnsembleSize", 1);
        conf.setProperty("dlog.bkcWriteQuorumSize", 1);
        conf.setProperty("dlog.bkcAckQuorumSize", 1);
    } else {
        conf.setProperty("dlog.bkcEnsembleSize", starterArgs.numBookies);
        conf.setProperty("dlog.bkcWriteQuorumSize", starterArgs.numBookies);
        conf.setProperty("dlog.bkcAckQuorumSize", starterArgs.numBookies - 1);
    }

    StreamClusterSpec spec = specBuilder.baseConf(conf).numServers(starterArgs.numBookies)
            .initialBookiePort(starterArgs.initialBookiePort).initialGrpcPort(starterArgs.initialBookieGrpcPort)
            .storageRootDir(new File(starterArgs.dataDir)).build();

    CountDownLatch liveLatch = new CountDownLatch(1);

    StreamCluster cluster = StreamCluster.build(spec);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        cluster.stop();
        cluster.close();
        liveLatch.countDown();
    }, "Standalone-Shutdown-Thread"));

    cluster.start();

    try {
        liveLatch.await();
    } catch (InterruptedException e) {
        log.error("The standalone cluster is interrupted : ", e);
    }
    return 0;
}