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

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

Introduction

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

Prototype

public void addConfiguration(Configuration config) 

Source Link

Document

Add a configuration.

Usage

From source file:cz.mzk.editor.server.config.EditorConfigurationImpl.java

public EditorConfigurationImpl() {
    File dir = new File(WORKING_DIR);
    if (!dir.exists()) {
        boolean mkdirs = dir.mkdirs();
        if (!mkdirs) {
            LOGGER.error("cannot create directory '" + dir.getAbsolutePath() + "'");
            throw new RuntimeException("cannot create directory '" + dir.getAbsolutePath() + "'");
        }/*from  w w  w .  j a  v  a2  s .  co  m*/
    }
    File confFile = new File(CONFIGURATION);
    if (!confFile.exists()) {
        try {
            confFile.createNewFile();
        } catch (IOException e) {
            LOGGER.error("cannot create configuration file '" + confFile.getAbsolutePath() + "'", e);
            throw new RuntimeException("cannot create configuration file '" + confFile.getAbsolutePath() + "'");
        }
        FileOutputStream confFos;
        try {
            confFos = new FileOutputStream(confFile);
        } catch (FileNotFoundException e) {
            LOGGER.error("cannot create configuration file '" + confFile.getAbsolutePath() + "'", e);
            throw new RuntimeException("cannot create configuration file '" + confFile.getAbsolutePath() + "'");
        }
        try {
            try {
                new Properties().store(confFos, "configuration file for module metadata editor");
            } catch (IOException e) {
                LOGGER.error("cannot create configuration file '" + confFile.getAbsolutePath() + "'", e);
                throw new RuntimeException(
                        "cannot create configuration file '" + confFile.getAbsolutePath() + "'");
            }
        } finally {
            try {
                if (confFos != null)
                    confFos.close();
            } catch (IOException e) {
                LOGGER.error("cannot create configuration file '" + confFile.getAbsolutePath() + "'", e);
                throw new RuntimeException(
                        "cannot create configuration file '" + confFile.getAbsolutePath() + "'");
            } finally {
                confFos = null;
            }
        }
    }

    CompositeConfiguration constconf = new CompositeConfiguration();
    PropertiesConfiguration file = null;
    try {
        file = new PropertiesConfiguration(confFile);
    } catch (ConfigurationException e) {
        LOGGER.error(e.getMessage(), e);
        new RuntimeException("cannot read configuration");
    }
    file.setReloadingStrategy(new FileChangedReloadingStrategy());
    constconf.addConfiguration(file);
    constconf.setProperty(ServerConstants.EDITOR_HOME, WORKING_DIR);
    this.configuration = constconf;

    String hostname = configuration.getString(EditorClientConfiguration.Constants.HOSTNAME, "editor.mzk.cz");
    if (hostname.contains("://")) {
        hostname = hostname.substring(hostname.indexOf("://") + "://".length());
    }
    File imagesDir = new File(ServerConstants.DEFAULT_IMAGES_LOCATION + hostname + File.separator);
    if (!imagesDir.exists()) {
        boolean mkdirs = imagesDir.mkdirs();
        if (!mkdirs) {
            LOGGER.error("cannot create directory '" + imagesDir.getAbsolutePath() + "'");
            throw new RuntimeException("cannot create directory '" + imagesDir.getAbsolutePath() + "'");
        }
    }
    constconf.setProperty(ServerConstants.IMAGES_LOCATION,
            ServerConstants.DEFAULT_IMAGES_LOCATION + hostname + File.separator);
    EnvironmentConfiguration environmentConfiguration = new EnvironmentConfiguration();
    for (Iterator it = environmentConfiguration.getKeys(); it.hasNext();) {
        String key = (String) it.next();
        Object value = environmentConfiguration.getProperty(key);
        key = key.replaceAll("_", ".");
        key = key.replaceAll("\\.\\.", "__");
        constconf.addProperty(key, value);
    }
}

From source file:com.dm.estore.common.config.Cfg.java

private Configuration createConfiguration() {
    try {//  www .  j a  v  a  2s. co m
        final CompositeConfiguration compositeConfig = new CompositeConfiguration();

        String configuredHome = null;
        if (overrideProperties != null) {
            MapConfiguration initialConfig = new MapConfiguration(overrideProperties);
            compositeConfig.addConfiguration(initialConfig);

            if (overrideProperties.containsKey(CommonConstants.Cfg.CFG_HOME_FOLDER)) {
                configuredHome = overrideProperties.getProperty(CommonConstants.Cfg.CFG_HOME_FOLDER);
            }
        }

        configurationHome = getOrCreateHomeFolder(configuredHome);

        final DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(
                configurationHome + File.separator + ROOT_CONFIG_NAME);
        final CombinedConfiguration reloadableConfig = builder.getConfiguration(true);
        ConfigurationLogListener listener = new ConfigurationLogListener();
        reloadableConfig.addConfigurationListener(listener);
        reloadableConfig.addErrorListener(listener);
        // reloadableConfig.setForceReloadCheck(true);
        compositeConfig.addConfiguration(reloadableConfig);

        lastReloadTime = new Date();
        return compositeConfig;
    } catch (ConfigurationException e) {
        LOG.error("Unable to load configuration", e);
    }

    return null;
}

From source file:com.germinus.easyconf.AggregatedProperties.java

/**
 * Read the given source of properties and add it to the composite
 * configuration. The added configuration will be returned. If it is not
 * found null will be returned.// w w w.  j  av  a 2 s  .  c  o m
 */
private Configuration addPropertiesSource(String sourceName, CompositeConfiguration loadedConf) {
    try {
        Configuration newConf;
        if (DatasourceURL.isDatasource(sourceName)) {
            newConf = addDatasourceProperties(sourceName);
        } else if (JndiURL.isJndi(sourceName)) {
            newConf = addJndiProperties(sourceName);
        } else {
            newConf = addFileProperties(sourceName, loadedConf);
        }
        if (newConf != null) {
            loadedConf.addConfiguration(newConf);
            super.addConfiguration(newConf);
            if (newConf instanceof AbstractFileConfiguration) {
                loadedSources.add(((AbstractFileConfiguration) newConf).getURL().toString());
            } else {
                loadedSources.add(sourceName);
            }
        }
        return newConf;
    } catch (Exception ignore) {
        if (log.isDebugEnabled()) {
            log.debug("Configuration source " + sourceName + " ignored");
        }
        return null;
    }
}

From source file:com.yahoo.sshd.server.settings.SshdSettingsBuilder.java

protected Configuration createConfiguration(final String overriddenPath) {
    try {//w  ww . j  a v  a 2s. c o  m

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("got overriddenPath {}", overriddenPath);
        }

        CompositeConfiguration compositeConfig = new CompositeConfiguration();
        // TODO: see how Systems and properties interact.
        compositeConfig.addConfiguration(new SystemConfiguration());
        compositeConfig.addConfiguration(findPropertiesConfiguration(overriddenPath));

        return compositeConfig;
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:br.eti.kinoshita.testlinkjavaapi.TestLinkAPI.java

/**
 * Creates application composite configuration.
 * /* www  .java2s. co m*/
 * @return Application composite configuration.
 */
private CompositeConfiguration createApplicationConfiguration() {
    CompositeConfiguration appConfig = new CompositeConfiguration();
    appConfig.addConfiguration(new SystemConfiguration());
    try {
        appConfig.addConfiguration(new PropertiesConfiguration("testlinkjavaapi.properties"));
    } catch (ConfigurationException ce) {
        this.debug(ce);
    }
    return appConfig;
}

From source file:com.germinus.easyconf.ComponentProperties.java

protected Object getPropertyWithFilter(String key, Filter filter, Class theClass, Object defaultValue) {
    CompositeConfiguration filteredConf = properties;
    Object value = null;//from w  w  w .  j a v  a  2 s .  co m
    for (int i = filter.numOfSelectors(); (i >= 0) && (value == null); i--) {
        MapConfiguration varsConf = null;
        if (filter.hasVariables()) {
            varsConf = new MapConfiguration(filter.getVariables());
            filteredConf = new CompositeConfiguration();
            filteredConf.addConfiguration(varsConf);
            filteredConf.addConfiguration(properties);
        }
        value = getTypedPropertyWithDefault(key + filter.getFilterSuffix(i), theClass, filteredConf, null);
        if (varsConf != null) {
            properties.removeConfiguration(varsConf);
        }
        log.debug("Value for " + key + filter.getFilterSuffix(i) + "=" + value);
    }
    if (value == null) {
        value = defaultValue;
    }
    return value;
}

From source file:com.liferay.portal.configuration.easyconf.ClassLoaderAggregateProperties.java

private Configuration _addPropertiesSource(String sourceName, URL url,
        CompositeConfiguration loadedCompositeConfiguration) {

    boolean checkGetClassLoader = PortalSecurityManagerThreadLocal.isCheckGetClassLoader();

    try {/*from  w w w.  j a  va2s .c  o  m*/
        PortalSecurityManagerThreadLocal.setCheckGetClassLoader(false);

        Configuration newConfiguration = null;

        if (DatasourceURL.isDatasource(sourceName)) {
            newConfiguration = _addDatasourceProperties(sourceName);
        } else if (JndiURL.isJndi(sourceName)) {
            newConfiguration = _addJNDIProperties(sourceName);
        } else if (url != null) {
            newConfiguration = _addURLProperties(url, loadedCompositeConfiguration);
        } else {
            newConfiguration = _addFileProperties(sourceName, loadedCompositeConfiguration);
        }

        if (newConfiguration == null) {
            return newConfiguration;
        }

        loadedCompositeConfiguration.addConfiguration(newConfiguration);

        super.addConfiguration(newConfiguration);

        if (newConfiguration instanceof AbstractFileConfiguration) {
            AbstractFileConfiguration abstractFileConfiguration = (AbstractFileConfiguration) newConfiguration;

            URL abstractFileConfigurationURL = abstractFileConfiguration.getURL();

            _loadedSources.add(abstractFileConfigurationURL.toString());
        } else {
            _loadedSources.add(sourceName);
        }

        return newConfiguration;
    } catch (Exception e) {
        if (_log.isDebugEnabled()) {
            _log.debug("Configuration source " + sourceName + " ignored: " + e.getMessage());
        }

        return null;
    } finally {
        PortalSecurityManagerThreadLocal.setCheckGetClassLoader(checkGetClassLoader);
    }
}

From source file:com.intel.mtwilson.MyConfiguration.java

private Configuration gatherConfiguration(Properties customProperties) {
    CompositeConfiguration composite = new CompositeConfiguration();

    // first priority: custom properties take priority over any other source
    if (customProperties != null) {
        MapConfiguration customconfig = new MapConfiguration(customProperties);
        logConfiguration("custom", customconfig);
        composite.addConfiguration(customconfig);
    }// w w w .  j  a v  a2 s  .c  o  m

    // second priority are properties defined on the current JVM (-D switch
    // or through web container)
    SystemConfiguration system = new SystemConfiguration();
    logConfiguration("system", system);
    composite.addConfiguration(system);

    // third priority: environment variables (regular and also converted from dot-notation to all-caps)
    EnvironmentConfiguration env = new EnvironmentConfiguration();
    logConfiguration("environment", env);
    composite.addConfiguration(env);
    //        AllCapsEnvironmentConfiguration envAllCaps = new AllCapsEnvironmentConfiguration();
    //        logConfiguration("environment_allcaps", envAllCaps);
    //        composite.addConfiguration(envAllCaps);

    List<File> files = listConfigurationFiles();
    // add all the files we found so far, in the priority order
    for (File f : files) {
        //            System.out.println("Looking for "+f.getAbsolutePath());
        try {
            if (f.exists() && f.canRead()) {
                // first check if the file is encrypted... if it is, we need to decrypt it before loading!
                try (FileInputStream in = new FileInputStream(f)) {
                    String content = IOUtils.toString(in);

                    if (Pem.isPem(content)) { // starts with something like -----BEGIN ENCRYPTED DATA----- and ends with -----END ENCRYPTED DATA-----
                        // a pem-format file indicates it's encrypted... we could check for "ENCRYPTED DATA" in the header and footer too.
                        String password = getApplicationConfigurationPassword();
                        if (password == null) {
                            log.warn(
                                    "Found encrypted configuration file, but no password was found in system properties or environment");
                        }
                        if (password != null) {
                            ExistingFileResource resource = new ExistingFileResource(f);
                            PasswordEncryptedFile encryptedFile = new PasswordEncryptedFile(resource, password);
                            String decryptedContent = encryptedFile.loadString();
                            Properties p = new Properties();
                            p.load(new StringReader(decryptedContent));
                            MapConfiguration encrypted = new MapConfiguration(p);
                            logConfiguration("encrypted-file:" + f.getAbsolutePath(), encrypted);
                            composite.addConfiguration(encrypted);
                        }
                    } else {
                        log.debug("FILE {} IS IN REGULAR PROPERTIES FORMAT", f.getAbsolutePath());
                        PropertiesConfiguration standard = new PropertiesConfiguration(f);
                        logConfiguration("file:" + f.getAbsolutePath(), standard);
                        composite.addConfiguration(standard);
                    }
                }
            }
        } catch (FileNotFoundException ex) { // shouldn't happen since we check for f.exists() first, but must handle it because FileInputStream can throw it
            log.error("File not found: " + f.getAbsolutePath(), ex);
        } catch (IOException ex) {
            log.error("Cannot load configuration: " + f.getAbsolutePath(), ex);
        } catch (ConfigurationException ex) {
            log.error("Cannot load configuration from " + f.getAbsolutePath(), ex);
        }
    }

    // seventh priority are properties defined on the classpath (for example defaults provided with the application, or placed in the web server container)
    String propertiesFilename = "mtwilson.properties";
    InputStream in = getClass().getResourceAsStream("/" + propertiesFilename);
    try {
        // user's home directory (assuming it's on the classpath!)
        if (in != null) {
            Properties properties = new Properties();
            properties.load(in);
            MapConfiguration classpath = new MapConfiguration(properties);
            logConfiguration("classpath:" + propertiesFilename, classpath);
            composite.addConfiguration(classpath);
        }
    } catch (IOException ex) {
        log.debug("Did not find [" + propertiesFilename + "] properties on classpath", ex);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                log.error("Failed to close input stream for " + propertiesFilename);
            }
        }
    }

    return composite;
}

From source file:at.gv.egiz.bku.spring.ConfigurationFactoryBean.java

@Override
public Object getObject() throws Exception {

    log.info("Configuration resource is {}.", configurationResource);

    CompositeConfiguration configuration = null;
    if (configurationResource != null) {
        if (configurationResource.exists()) {
            // initialize with writable configuration
            URL url = configurationResource.getURL();
            XMLConfiguration writableConfiguration = new XMLConfiguration(url);
            configuration = new CompositeConfiguration(writableConfiguration);
            log.info("Initialized with configuration from '{}'.", url);
        } else if (failOnMissingResource) {
            StringBuilder message = new StringBuilder();
            message.append("ConfigurationResource '");
            message.append(configurationResource.getDescription());
            message.append("' does not exist!");
            log.error(message.toString());
            throw new MoccaConfigurationException(message.toString());
        }/*w  w  w  .  j a v a2s. c o  m*/
    }

    if (configuration == null) {
        // initialize default configuration
        log.warn("Initializing with default configuration.");
        configuration = new CompositeConfiguration();
    }

    configuration.addConfiguration(getDefaultConfiguration());
    configuration.addConfiguration(getVersionConfiguration());
    return configuration;
}

From source file:com.manydesigns.portofino.i18n.ResourceBundleManager.java

public ResourceBundle getBundle(Locale locale) {
    ConfigurationResourceBundle bundle = resourceBundles.get(locale);
    if (bundle == null) {
        CompositeConfiguration configuration = new CompositeConfiguration();
        Iterator<String> iterator = searchPaths.descendingIterator();
        while (iterator.hasNext()) {
            String path = iterator.next();
            int index = path.lastIndexOf('/') + 1;
            String basePath = path.substring(0, index);
            int suffixIndex = path.length() - ".properties".length();
            String resourceBundleBaseName = path.substring(index, suffixIndex);
            String bundleName = getBundleFileName(resourceBundleBaseName, locale);
            PropertiesConfiguration conf;
            try {
                conf = new PropertiesConfiguration();
                conf.setFileName(basePath + bundleName);
                conf.setDelimiterParsingDisabled(true);
                conf.load();//  w  ww.  j av  a2 s .com
            } catch (ConfigurationException e) {
                logger.debug("Couldn't load resource bundle for locale " + locale + " from " + basePath, e);
                //Fall back to default .properties without _locale
                try {
                    String defaultBundleName = basePath + resourceBundleBaseName + ".properties";
                    conf = new PropertiesConfiguration();
                    conf.setFileName(defaultBundleName);
                    conf.setDelimiterParsingDisabled(true);
                    conf.load();
                } catch (ConfigurationException e1) {
                    logger.debug("Couldn't load default resource bundle from " + basePath, e1);
                    conf = null;
                }
            }
            if (conf != null) {
                FileChangedReloadingStrategy reloadingStrategy = new FileChangedReloadingStrategy();
                conf.setReloadingStrategy(reloadingStrategy);
                configuration.addConfiguration(conf);
            }
        }
        bundle = new ConfigurationResourceBundle(configuration, locale);
        //TODO setParent?
        resourceBundles.put(locale, bundle);
    }
    return bundle;
}