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

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

Introduction

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

Prototype

public CombinedConfiguration(NodeCombiner comb) 

Source Link

Document

Creates a new instance of CombinedConfiguration and initializes the combiner to be used.

Usage

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  av a2  s.c o m
                    }
                    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 readTestConfig(File testFile)
        throws ConfigurationException, FileNotFoundException, IOException {
    HierarchicalConfiguration finalConf = null;
    CombinedConfiguration mergedConf = null;
    HierarchicalConfiguration loadedConf = null;
    if (isXMLConfig(testFile)) {
        loadedConf = new XMLPropertyListConfiguration(testFile);
    } else {/*from w w  w. jav a  2  s. com*/
        loadedConf = new PropertyListConfiguration(testFile);
    }

    /*
     * Some compatibility magic: Our initial version had very specific uses and according configuration wording.
     * We want to be more generic, so we re-route some information in the configs.
     */

    HierarchicalConfiguration groupsConf = (HierarchicalConfiguration) loadedConf
            .getProperty("groupOntologies");
    if (null == loadedConf.getProperty("studentOntologies") && (null != groupsConf)) {
        HierarchicalConfiguration cfg = new HierarchicalConfiguration();
        mergedConf = new CombinedConfiguration(new OverrideCombiner());
        cfg.setProperty("studentOntologies", groupsConf);
        mergedConf.addConfiguration(cfg);
        mergedConf.addConfiguration(loadedConf);
        finalConf = mergedConf;
    } else {
        finalConf = loadedConf;
    }
    return finalConf;

}

From source file:com.shanke.common.conf.CustomConfigurationBuilder.java

/**
 * Returns the configuration provided by this builder. If the boolean
 * parameter is <b>true</b>, the configuration definition file will be
 * loaded. It will then be parsed, and instances for the declared
 * configurations will be created.//from  w w  w.  java2 s. co  m
 * 
 * @param load
 *            a flag whether the configuration definition file should be
 *            loaded; a value of <b>false</b> would make sense if the file
 *            has already been created or its content was manipulated using
 *            some of the property accessor methods
 * @return the configuration
 * @throws ConfigurationException
 *             if an error occurs
 */
public Configuration getConfiguration(boolean load) throws ConfigurationException {
    if (load) {
        load();
    }

    Configuration result = createResultConfiguration();
    constructedConfiguration = result;

    List overrides = configurationsAt(KEY_OVERRIDE1);
    overrides.addAll(configurationsAt(KEY_OVERRIDE2));
    initCombinedConfiguration(result, overrides, KEY_OVERRIDE_LIST);

    List additionals = configurationsAt(KEY_UNION);
    if (!additionals.isEmpty()) {
        CombinedConfiguration addConfig = new CombinedConfiguration(new UnionCombiner());
        result.addConfiguration(addConfig, ADDITIONAL_NAME);
        initCombinedConfiguration(addConfig, additionals, KEY_ADDITIONAL_LIST);
    }

    return result;
}

From source file:org.ambraproject.configuration.ConfigurationStore.java

/**
 * Load/Reload the configuration from the factory config url.
 *
 * @param configURL URL to the config file for ConfigurationFactory
 * @throws ConfigurationException when the config factory configuration has an error
 *///w w w. j  a  v a  2s .c  o  m
public void loadConfiguration(URL configURL) throws ConfigurationException {
    root = new CombinedConfiguration(new OverrideCombiner());

    // System properties override everything
    root.addConfiguration(new SystemConfiguration());

    // Load from ambra.configuration -- /etc/... (optional)
    if (configURL != null) {
        try {
            root.addConfiguration(getConfigurationFromUrl(configURL));
            log.info("Added URL '" + configURL + "'");
        } catch (ConfigurationException ce) {
            if (!(ce.getCause() instanceof FileNotFoundException))
                throw ce;
            log.info("Unable to open '" + configURL + "'");
        }
    }

    // Add ambra.configuration.overrides (if defined)
    String overrides = System.getProperty(OVERRIDES_URL);
    if (overrides != null) {
        try {
            root.addConfiguration(getConfigurationFromUrl(new URL(overrides)));
            log.info("Added override URL '" + overrides + "'");
        } catch (MalformedURLException mue) {
            // Must not be a URL, so it must be a resource
            addResources(root, overrides);
        }
    }

    CombinedConfiguration defaults = new CombinedConfiguration(new UnionCombiner());
    // Add defaults.xml from classpath
    addResources(defaults, DEFAULTS_RESOURCE);
    // Add journal.xml from journals/journal-name/configuration/journal.xml
    addJournalResources(root, defaults, JOURNAL_DIRECTORY);
    root.addConfiguration(defaults);

    // Add global-defaults.xml (presumably found in this jar)
    addResources(root, GLOBAL_DEFAULTS_RESOURCE);

    if (log.isDebugEnabled())
        log.debug("Configuration dump: " + System.getProperty("line.separator")
                + ConfigurationUtils.toString(root));

    /**
     * This prefix is needed by the AmbraIdGenerator to create prefixes for object IDs.
     * Because of the way the AmbraIdGenerator class is created by hibernate, passing in values
     * is very difficult.  If a better method is discovered... by all means use that.  Until that time
     * I've created a system level property to store this prefix.
     */
    String objectIDPrefix = root.getString("ambra.platform.guid-prefix");

    if (objectIDPrefix == null) {
        throw new RuntimeException(
                "ambra.platform.guid-prefix node is not found in the defined configuration file.");
    }

    System.setProperty(SYSTEM_OBJECT_ID_PREFIX, objectIDPrefix);
}

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  a  va  2 s.  co 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 va  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;
}