Example usage for org.apache.commons.configuration CombinedConfiguration addConfiguration

List of usage examples for org.apache.commons.configuration CombinedConfiguration addConfiguration

Introduction

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

Prototype

public void addConfiguration(AbstractConfiguration config, String name) 

Source Link

Document

Adds a new configuration to this combined configuration with an optional name.

Usage

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

CombinedConfiguration load() {
    // Allow foo/bar/baz and foo:bar:baz
    final String[] configNames = StringUtils.stripAll(StringUtils.split(configName, "/:"));

    final CombinedConfiguration cc = new CombinedConfiguration(new OverrideCombiner());

    // All properties can be overridden by the System properties.
    cc.addConfiguration(new SystemConfiguration(), "systemProperties");

    boolean loadedConfig = false;
    for (int i = 0; i < configNames.length; i++) {
        final String configFileName = configNames[configNames.length - i - 1];
        final String configFilePath = StringUtils.join(configNames, "/", 0, configNames.length - i);

        try {//w w  w . ja  v a  2  s  . c o m
            final AbstractConfiguration subConfig = configStrategy.load(configFileName, configFilePath);
            if (subConfig == null) {
                LOG.debug("Configuration '%s' does not exist, skipping", configFileName);
            } else {
                cc.addConfiguration(subConfig, configFileName);
                loadedConfig = true;
            }
        } catch (ConfigurationException ce) {
            LOG.error(String.format("While loading configuration '%s'", configFileName), ce);
        }
    }

    if (!loadedConfig && configNames.length > 0) {
        LOG.warn("Config name '%s' was given but no config file could be found, this looks fishy!", configName);
    }

    return cc;
}

From source file:com.opentable.config.ConfigFactory.java

private CombinedConfiguration loadOTStrategy() throws ConfigurationException {
    final String[] configPaths = StringUtils.stripAll(StringUtils.split(configName, ","));
    final CombinedConfiguration cc = new CombinedConfiguration(new OverrideCombiner());

    // All properties can be overridden by the System properties.
    cc.addConfiguration(new SystemConfiguration(), "systemProperties");
    LOG.info("Configuration source: SYSTEM");

    for (int i = configPaths.length - 1; i >= 0; i--) {
        final String configPath = configPaths[i];
        final AbstractConfiguration subConfig = configStrategy.load(configPath, configPath);
        if (subConfig == null) {
            throw new IllegalStateException(String.format("Configuration '%s' does not exist!", configPath));
        }//from   w  w  w .  ja v a  2s  . c o m
        cc.addConfiguration(subConfig, configPath);
        LOG.info("New-style configuration source: {}", configPath);
    }

    return cc;
}

From source file:com.opentable.config.ConfigFactory.java

private CombinedConfiguration loadNessStrategy() {
    // Allow foo/bar/baz and foo:bar:baz
    final String[] configNames = StringUtils.stripAll(StringUtils.split(configName, "/:"));

    final CombinedConfiguration cc = new CombinedConfiguration(new OverrideCombiner());

    // All properties can be overridden by the System properties.
    cc.addConfiguration(new SystemConfiguration(), "systemProperties");
    LOG.info("Configuration source: SYSTEM");

    boolean loadedConfig = false;
    for (int i = 0; i < configNames.length; i++) {
        final String configFileName = configNames[configNames.length - i - 1];
        final String configFilePath = StringUtils.join(configNames, "/", 0, configNames.length - i);

        try {/*from   w w  w  .  j  a va2  s.com*/
            final AbstractConfiguration subConfig = configStrategy.load(configFileName, configFilePath);
            if (subConfig == null) {
                throw new IllegalStateException(
                        String.format("Configuration '%s' does not exist!", configFileName));
            } else {
                cc.addConfiguration(subConfig, configFileName);
                LOG.info("Configuration source: {}", configFileName);
                loadedConfig = true;
            }
        } catch (ConfigurationException ce) {
            LOG.error(String.format("While loading configuration '%s'", configFileName), ce);
        }
    }

    if (!loadedConfig && configNames.length > 0) {
        throw new IllegalStateException(String.format(
                "Config name '%s' was given but no config file could be found, this looks fishy!", configName));
    }

    return cc;
}

From source file:com.nesscomputing.migratory.mojo.database.AbstractDatabaseMojo.java

@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
    ConfigureLog4j.start(this);

    try {/*from  w w w  .  j  ava 2  s .c o m*/
        // Load the default manifest information.
        //
        final CombinedConfiguration config = new CombinedConfiguration(new OverrideCombiner());
        // everything can be overridden by system properties.
        config.addConfiguration(new SystemConfiguration(), "systemProperties");

        final String userHome = System.getProperty("user.home");
        if (userHome != null) {
            final File propertyFile = new File(userHome, MIGRATORY_PROPERTIES_FILE);
            if (propertyFile.exists() && propertyFile.canRead() && propertyFile.isFile()) {
                config.addConfiguration(new PropertiesConfiguration(propertyFile));
            }
        }

        final ConfigurationObjectFactory initialConfigFactory = new ConfigurationObjectFactory(
                new CommonsConfigSource(config));

        // Load the initial config from the local config file
        this.initialConfig = initialConfigFactory.build(InitialConfig.class);

        if (this.manifestUrl == null) {
            this.manifestUrl = initialConfig.getManifestUrl();
        }

        if (this.manifestName == null) {
            this.manifestName = initialConfig.getManifestName();
        }

        if (manifestUrl == null) {
            throw new MojoExecutionException(
                    "no manifest url found (did you create a .migratory.properties file?)");
        }

        if (manifestName == null) {
            throw new MojoExecutionException(
                    "no manifest name found (did you create a .migratory.properties file?)");
        }

        LOG.debug("Manifest URL:      %s", manifestUrl);
        LOG.debug("Manifest Name:     %s", manifestName);

        this.optionList = parseOptions(options);

        final StringBuilder location = new StringBuilder(manifestUrl);
        if (!this.manifestUrl.endsWith("/")) {
            location.append("/");
        }

        // After here, the manifestUrl is guaranteed to have a / at the end!
        this.manifestUrl = location.toString();

        location.append(manifestName);
        location.append(".manifest");

        LOG.debug("Manifest Location: %s", location);

        final MigratoryConfig initialMigratoryConfig = initialConfigFactory.build(MigratoryConfig.class);
        final LoaderManager initialLoaderManager = createLoaderManager(initialMigratoryConfig);
        final String contents = initialLoaderManager.loadFile(URI.create(location.toString()));

        if (contents == null) {
            throw new MojoExecutionException(
                    format("Could not load manifest '%s' from '%s'", manifestName, manifestUrl));
        }

        //
        // Now add the contents of the manifest file to the configuration creating the
        // final configuration for building the sql migration sets.
        //
        final PropertiesConfiguration pc = new PropertiesConfiguration();
        pc.load(new StringReader(contents));
        config.addConfiguration(pc);

        if (!validateConfiguration(config)) {
            throw new MojoExecutionException(
                    format("Manifest '%s' is not valid. Refusing to execute!", manifestName));
        }

        this.config = config;
        this.factory = new ConfigurationObjectFactory(new CommonsConfigSource(config));
        this.migratoryConfig = factory.build(MigratoryConfig.class);
        this.loaderManager = createLoaderManager(migratoryConfig);

        LOG.debug("Configuration: %s", this.config);

        this.rootDBIConfig = getDBIConfig(getPropertyName("default.root_"));

        stateCheck();

        doExecute();
    } catch (Exception e) {
        Throwables.propagateIfInstanceOf(e, MojoExecutionException.class);

        LOG.errorDebug(e, "While executing Mojo %s", this.getClass().getSimpleName());
        throw new MojoExecutionException("Failure:", e);
    } finally {
        ConfigureLog4j.stop(this);
    }
}

From source file:eu.eubrazilcc.lvl.core.conf.ConfigurationManager.java

private Configuration configuration() {
    if (dont_use == null) {
        synchronized (Configuration.class) {
            if (dont_use == null && urls != null) {
                try {
                    XMLConfiguration main = null;
                    // sorting secondary configurations ensures that combination always result the same
                    final SortedMap<String, XMLConfiguration> secondary = newTreeMap();
                    // extract main configuration
                    for (final URL url : urls) {
                        final String filename = getName(url.getPath());
                        if (MAIN_CONFIG.equalsIgnoreCase(filename)) {
                            main = new XMLConfiguration(url);
                            LOGGER.info("Loading main configuration from: " + url.toString());
                        } else if (!IGNORE_LIST.contains(getName(url.getPath()))) {
                            secondary.put(filename, new XMLConfiguration(url));
                            LOGGER.info("Loading secondary configuration from: " + url.toString());
                        } else {
                            LOGGER.info("Ignoring: " + url.toString());
                        }//from  w  w w .j a  v a  2  s  .  com
                    }
                    if (main != null) {
                        final CombinedConfiguration configuration = new CombinedConfiguration(
                                new OverrideCombiner());
                        configuration.addConfiguration(main, MAIN_CONFIG);
                        for (final Map.Entry<String, XMLConfiguration> entry : secondary.entrySet()) {
                            configuration.addConfiguration(entry.getValue(), entry.getKey());
                        }
                        if (LOGGER.isDebugEnabled()) {
                            String names = "";
                            for (final String name : configuration.getConfigurationNameList()) {
                                names += name + " ";
                            }
                            LOGGER.trace("Loading configuration from: " + names);
                        }
                        final List<String> foundNameList = newArrayList();
                        // get main property will fail if the requested property is missing
                        configuration.setThrowExceptionOnMissing(true);
                        final File rootDir = getFile("lvl-root", configuration, foundNameList, true, null);
                        final File localCacheDir = getFile("storage.local-cache", configuration, foundNameList,
                                true, null);
                        final File htdocsDir = getFile("storage.htdocs", configuration, foundNameList, false,
                                null);
                        final String dbName = getString("database.name", configuration, foundNameList, "lvldb");
                        final String dbUsername = getString("database.credentials.username", configuration,
                                foundNameList, null);
                        final String dbPassword = getString("database.credentials.password", configuration,
                                foundNameList, null);
                        final ImmutableList<String> dbHosts = getStringList("database.hosts.host",
                                Pattern.compile("^[\\w]+:[\\d]+$"), configuration, foundNameList,
                                newArrayList("localhost:27017"));
                        final boolean brokerEmbedded = getBoolean("broker.embedded", configuration,
                                foundNameList, true);
                        final ImmutableList<String> messageBrokers = getStringList("messaging.hosts.host",
                                Pattern.compile("^[\\w]+:[\\d]+$"), configuration, foundNameList,
                                newArrayList("localhost:61616"));
                        final String smtpHost = getString("smtp.host", configuration, foundNameList,
                                "localhost");
                        final int smtpPort = getInteger("smtp.port", configuration, foundNameList, 25);
                        final String smtpSupportEmail = getString("smtp.support-email", configuration,
                                foundNameList, "support@example.com");
                        final String smtpNoreplyEmail = getString("smtp.noreply-email", configuration,
                                foundNameList, "noreply@example.com");
                        final String portalEndpoint = getString("portal.endpoint", configuration, foundNameList,
                                null);
                        final String wfHostname = getString("workflow.endpoint.hostname", configuration,
                                foundNameList, "localhost");
                        final boolean wfSecure = getBoolean("workflow.endpoint.secure", configuration,
                                foundNameList, false);
                        final int wfPort = getInteger("workflow.endpoint.port", configuration, foundNameList,
                                wfSecure ? 443 : 80);
                        final String wfUsername = getString("workflow.credentials.username", configuration,
                                foundNameList, null);
                        final String wfPasswd = getString("workflow.credentials.password", configuration,
                                foundNameList, null);
                        // get secondary property will return null if the requested property is missing
                        configuration.setThrowExceptionOnMissing(false);
                        final String linkedInAPIKey = getString("authz-server.linkedin.api-key", configuration,
                                foundNameList, null);
                        final String linkedInSecretKey = getString("authz-server.linkedin.secret-key",
                                configuration, foundNameList, null);
                        final String googleAPIKey = getString("rest-service.google.api-key", configuration,
                                foundNameList, null);
                        // get other (free-format) properties
                        final Iterator<String> keyIterator = configuration.getKeys();
                        final Map<String, String> othersMap = new Hashtable<String, String>();
                        while (keyIterator.hasNext()) {
                            final String key = keyIterator.next();
                            if (key != null && !foundNameList.contains(key)) {
                                final String value = configuration.getString(key);
                                if (value != null) {
                                    othersMap.put(key, value);
                                }
                            }
                        }
                        dont_use = new Configuration(rootDir, localCacheDir, htdocsDir, dbName, dbUsername,
                                dbPassword, dbHosts, brokerEmbedded, messageBrokers, smtpHost, smtpPort,
                                smtpSupportEmail, smtpNoreplyEmail, portalEndpoint, wfHostname, wfSecure,
                                wfPort, wfUsername, wfPasswd, linkedInAPIKey, linkedInSecretKey, googleAPIKey,
                                othersMap);
                        LOGGER.info(dont_use.toString());
                    } else {
                        throw new IllegalStateException("Main configuration not found");
                    }
                } catch (IllegalStateException e1) {
                    throw e1;
                } catch (ConfigurationException e2) {
                    throw new IllegalStateException(e2);
                } catch (Exception e) {
                    LOGGER.error("Failed to load configuration", e);
                }
            }
        }
    }
    return dont_use;
}

From source file:de.uni_rostock.goodod.tools.Configuration.java

private HierarchicalConfiguration getConfigMap(String args[]) {

    CombinedConfiguration cfg = new CombinedConfiguration();
    HierarchicalConfiguration envCfg = new CombinedConfiguration();
    String repoRoot = System.getenv("GOODOD_REPO_ROOT");
    boolean helpMode = false;

    envCfg.addProperty("repositoryRoot", repoRoot);
    if (null == args) {
        return cfg;
    }/*  www .j a  v  a  2  s. co m*/
    GnuParser cmdLineParser = new GnuParser();
    CommandLine cmdLine = null;
    try {
        // parse the command line arguments
        cmdLine = cmdLineParser.parse(options, args);
    } catch (ParseException exception) {
        logger.fatal("Could not validate command-line.", exception);
        System.exit(1);
    }

    if (cmdLine.hasOption('c')) {
        envCfg.addProperty("configFile", cmdLine.getOptionValue('c'));
    }
    if (cmdLine.hasOption('t')) {
        envCfg.addProperty("threadCount", cmdLine.getOptionObject('t'));
    }

    if (cmdLine.hasOption('s')) {
        envCfg.addProperty("similarity", cmdLine.getOptionValue('s'));
    }
    if (cmdLine.hasOption('h')) {
        envCfg.addProperty("helpMode", true);
        helpMode = true;
    }
    if (cmdLine.hasOption('d')) {
        envCfg.addProperty("debug", true);
    }
    if (cmdLine.hasOption('1')) {
        envCfg.addProperty("one-way", true);
    }
    //Fetch the remaining arguments, but alas, commons-cli is not generics aware
    @SuppressWarnings("unchecked")
    List<String> argList = cmdLine.getArgList();
    HierarchicalConfiguration testConfig = null;
    try {
        if (argList.isEmpty() && (false == helpMode)) {
            logger.fatal("No test specification provided.");
            System.exit(1);
        } else if (1 == argList.size()) {
            File testFile = new File(argList.get(0));
            testConfig = readTestConfig(testFile);
            assert (null != testConfig);
            envCfg.addProperty("testFile", testFile.toString());

        } else if (false == helpMode) {
            /*
             *  For > 1 file, we assume that both are ontologies and we
             *  construct ourselves a test case configuration for them.
             */
            testConfig = new HierarchicalConfiguration();
            String ontologyA = argList.get(0);
            String ontologyB = argList.get(1);
            testConfig.addProperty("testName", "Comparison of " + ontologyA + " and " + ontologyB);
            testConfig.addProperty("notInRepository", true);
            Node studentOntologies = new Node("studentOntologies");
            Node groupA = new Node("groupA", Collections.singletonList(ontologyA));
            Node groupB = new Node("groupB", Collections.singletonList(ontologyB));
            studentOntologies.addChild(groupA);
            studentOntologies.addChild(groupB);
            testConfig.getRoot().addChild(studentOntologies);
            if (2 < argList.size()) {
                logger.warn("Ignoring extra arguments to comparison between individual ontologies.");
            }
            envCfg.addProperty("testFile", "unknown.plist");
        }
    } catch (Throwable t) {
        logger.fatal("Could not load test configuration.", t);
        System.exit(1);
    }
    cfg.addConfiguration(envCfg, "environment");
    if (false == helpMode) {
        cfg.addConfiguration(testConfig, "TestSubTree", "testDescription");
    }
    return cfg;
}

From source file:org.grycap.gpf4med.conf.ConfigurationManager.java

private ConfigurationManager.Configuration configuration() {
    if (dont_use == null) {
        synchronized (ConfigurationManager.Configuration.class) {
            if (dont_use == null && urls != null) {
                try {
                    XMLConfiguration main = null;
                    // sorting secondary configurations ensures that combination 
                    // always result the same
                    final SortedMap<String, XMLConfiguration> secondary = new TreeMap<String, XMLConfiguration>();
                    // extract main configuration
                    for (final URL url : urls) {
                        final String filename = FilenameUtils.getName(url.getPath());
                        if (MAIN_CONFIGURATION.equalsIgnoreCase(filename)) {
                            main = new XMLConfiguration(url);
                            LOGGER.info("Loading main configuration from: " + url.toString());
                        } else if (!IGNORE_LIST.contains(FilenameUtils.getName(url.getPath()))) {
                            secondary.put(filename, new XMLConfiguration(url));
                            LOGGER.info("Loading secondary configuration from: " + url.toString());
                        } else {
                            LOGGER.info("Ignoring: " + url.toString());
                        }//from  w  w  w  .j av a 2  s .  c o  m
                    }
                    if (main != null) {
                        final CombinedConfiguration configuration = new CombinedConfiguration(
                                new OverrideCombiner());
                        configuration.addConfiguration(main, MAIN_CONFIGURATION);
                        for (final Map.Entry<String, XMLConfiguration> entry : secondary.entrySet()) {
                            configuration.addConfiguration(entry.getValue(), entry.getKey());
                        }
                        if (LOGGER.isDebugEnabled()) {
                            String names = "";
                            for (final String name : configuration.getConfigurationNameList()) {
                                names += name + " ";
                            }
                            LOGGER.trace("Loading configuration from: " + names);
                        }
                        final List<String> foundNameList = new ArrayList<String>();
                        // get main property will fail if the requested property is missing
                        configuration.setThrowExceptionOnMissing(true);
                        final File rootDir = getFile("gpf4med-root", configuration, foundNameList, true, null);
                        final URL templatesUrl = getUrl("storage.templates", configuration, foundNameList,
                                null);
                        final URL connectorsUrl = getUrl("storage.connectors", configuration, foundNameList,
                                null);
                        final File localCacheDir = getFile("storage.local-cache", configuration, foundNameList,
                                true, null);
                        final File htdocsDir = getFile("storage.htdocs", configuration, foundNameList, false,
                                null);
                        final boolean encryptLocalStorage = getBoolean("security.encrypt-local-storage",
                                configuration, foundNameList, true);
                        final boolean useStrongCryptography = getBoolean("security.use-strong-cryptography",
                                configuration, foundNameList, false);
                        final String templatesVersion = getString("dicom.version", configuration, foundNameList,
                                null);
                        final URL templatesIndex = getUrl("dicom.index", configuration, foundNameList, null);
                        final String connectorsVersion = getString("graph.version", configuration,
                                foundNameList, null);
                        final URL connectorsIndex = getUrl("graph.index", configuration, foundNameList, null);
                        // get secondary property will return null if the requested property is missing
                        configuration.setThrowExceptionOnMissing(false);
                        final String containerHostname = getString("service-container.hostname", configuration,
                                foundNameList, null);
                        final int containerPort = getInteger("service-container.port", configuration,
                                foundNameList, new Integer(8080));
                        final String enactorProvider = getString("enactor.provider", configuration,
                                foundNameList, null);
                        final File enactorIdentity = getFile("enactor.identity", configuration, foundNameList,
                                false, null);
                        final File enactorCredential = getFile("enactor.credential", configuration,
                                foundNameList, false, null);
                        final String serverVersion = getString("container-server.version", configuration,
                                foundNameList, null);
                        final URL serverInstallerUrl = getUrl("container-server.installer.url", configuration,
                                foundNameList, null);
                        final File serverHome = getFile("container-server.home", configuration, foundNameList,
                                false, null);

                        // Add this for read the TRENCADIS configuration
                        final File trencadisConfiguration = getFile("trencadis.config-file", configuration,
                                foundNameList, false, null);
                        final String trencadisPassword = getString("trencadis.pass", configuration,
                                foundNameList, null);

                        // get other (free-format) properties
                        final Iterator<String> keyIterator = configuration.getKeys();
                        final Map<String, String> othersMap = new Hashtable<String, String>();
                        while (keyIterator.hasNext()) {
                            final String key = keyIterator.next();
                            if (key != null && !foundNameList.contains(key)) {
                                final String value = configuration.getString(key);
                                if (value != null) {
                                    othersMap.put(key, value);
                                }
                            }
                        }
                        dont_use = new Configuration(rootDir, templatesUrl, connectorsUrl, localCacheDir,
                                htdocsDir, encryptLocalStorage, useStrongCryptography, templatesVersion,
                                templatesIndex, connectorsVersion, connectorsIndex, containerHostname,
                                containerPort, enactorProvider, enactorIdentity, enactorCredential,
                                serverVersion, serverInstallerUrl, serverHome, trencadisConfiguration,
                                trencadisPassword, othersMap);
                        LOGGER.info(dont_use.toString());
                    } else {
                        throw new IllegalStateException("Main configuration not found");
                    }
                } catch (IllegalStateException e1) {
                    throw e1;
                } catch (ConfigurationException e2) {
                    throw new IllegalStateException(e2);
                } catch (Exception e) {
                    LOGGER.error("Failed to load configuration", e);
                }
            }
        }
    }
    return dont_use;
}

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./*w  w  w . ja  v a  2 s. c o m*/
 * @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;
}