Example usage for org.apache.commons.configuration Configuration subset

List of usage examples for org.apache.commons.configuration Configuration subset

Introduction

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

Prototype

Configuration subset(String prefix);

Source Link

Document

Return a decorator Configuration containing every key from the current Configuration that starts with the specified prefix.

Usage

From source file:org.apache.torque.TorqueInstance.java

/**
 * Reads the settings for the DataSourceFactories from the
 * configuration and creates and/or configures the DataSourceFactories
 * and the database objects./*from   w w  w. j av a 2s . co m*/
 * If no DataSorceFactory is assigned to the database with the name
 * <code>DEFAULT_NAME</code>, a reference to the DataSourceFactory
 * of the default database is made from the database with the name
 * <code>DEFAULT_NAME</code>.
 *
 * @param conf the Configuration representing the properties file.
 *
 * @throws TorqueException Any exceptions caught during processing will be
 *         rethrown wrapped into a TorqueException.
 */
private void initDataSourceFactories(Configuration conf) throws TorqueException {
    log.debug("initDataSourceFactories(" + conf + ")");

    Configuration c = conf.subset(DataSourceFactory.DSFACTORY_KEY);
    if (c == null || c.isEmpty()) {
        String error = "Invalid configuration: " + "No keys starting with " + Torque.TORQUE_KEY + "."
                + DataSourceFactory.DSFACTORY_KEY + " found in configuration";
        log.error(error);
        throw new TorqueException(error);
    }

    // read dsfactory config (may contain schema)
    try {
        for (Iterator<?> it = c.getKeys(); it.hasNext();) {
            String key = (String) it.next();
            if (key.endsWith(DataSourceFactory.FACTORY_KEY)) {
                String classname = c.getString(key);
                String handle = key.substring(0, key.indexOf('.'));
                log.debug("handle: " + handle + " DataSourceFactory: " + classname);
                Class<?> dsfClass = Class.forName(classname);
                DataSourceFactory dsf = (DataSourceFactory) dsfClass.newInstance();
                Configuration subConf = c.subset(handle);
                dsf.initialize(subConf);

                Database database = getOrCreateDatabase(handle);
                database.setDataSourceFactory(dsf);

                // deprecated method of schema configuration
                // TODO: remove in Torque 4.1
                String schema = subConf.getString(Torque.SCHEMA_KEY, null);
                if (!StringUtils.isEmpty(schema)) {
                    log.warn("Defining the schema in the dsfactory " + "is deprecated, please configure it "
                            + "via the config key " + "torque.database.${databasename}.schema");
                }
                database.setSchema(schema);
            }
        }
    } catch (RuntimeException e) {
        log.error("Error reading DataSourceFactory configuration", e);
        throw new TorqueRuntimeException(e);
    } catch (Exception e) {
        log.error("Error reading DataSourceFactory configuration", e);
        throw new TorqueException(e);
    }

    Database defaultDatabase = databases.get(defaultDBName);
    if (defaultDatabase == null || defaultDatabase.getDataSourceFactory() == null) {
        String error = "Invalid configuration : " + "No DataSourceFactory definition for default DB found. "
                + "A DataSourceFactory must be defined under the key" + Torque.TORQUE_KEY + "."
                + DataSourceFactory.DSFACTORY_KEY + "." + defaultDBName + "." + DataSourceFactory.FACTORY_KEY;
        log.error(error);
        throw new TorqueException(error);
    }
}

From source file:org.apache.torque.TorqueInstance.java

/**
 * Reads the schema configuration from the database definitions in
 * the configuration and assigns the defined schemata to the databases.
 *
 * @param conf the Configuration representing the properties file.
 *
 * @throws TorqueException Any exceptions caught during processing will be
 *         rethrown wrapped into a TorqueException.
 *///  w  ww . j a v a  2s .com
private void initSchemata(Configuration conf) throws TorqueException {
    log.debug("initSchemata(" + conf + ")");

    // read schema configuration from database setting
    Configuration c = conf.subset(Torque.DATABASE_KEY);
    if (c == null || c.isEmpty()) {
        String error = "Invalid configuration: " + "No keys starting with " + Torque.TORQUE_KEY + "."
                + Torque.DATABASE_KEY + " found in configuration";
        log.error(error);
        throw new TorqueException(error);
    }
    try {
        for (Iterator<?> it = c.getKeys(); it.hasNext();) {
            String key = (String) it.next();
            int indexOfDot = key.indexOf('.');
            if (indexOfDot == -1) {
                continue;
            }
            String handle = key.substring(0, indexOfDot);

            log.debug("database handle: " + handle);
            Configuration subConf = c.subset(handle);

            Database database = getOrCreateDatabase(handle);

            String schema = subConf.getString(Torque.SCHEMA_KEY, null);
            // check database schema because schema may have already been
            // set via the dsfactory
            if (StringUtils.isEmpty(schema)) {
                schema = database.getSchema();
            }
            if (StringUtils.isEmpty(schema)) {
                schema = conf.getString(Torque.DEFAULT_SCHEMA_KEY, null);
            }
            database.setSchema(schema);
        }
    } catch (RuntimeException e) {
        log.error("Error reading DataSourceFactory configuration", e);
        throw new TorqueRuntimeException(e);
    } catch (Exception e) {
        log.error("Error reading DataSourceFactory configuration", e);
        throw new TorqueException(e);
    }

}

From source file:org.apache.torque.TorqueInstance.java

/**
 * Sets the configuration for Torque and all dependencies.
 * The prefix <code>TORQUE_KEY</code> will be removed from the
 * configuration keys for the provided configuration.
 *
 * @param conf the Configuration./*from   www . jav a2  s. c o m*/
 *
 * @throws TorqueException if the configuration does not contain
 *         any keys starting with <code>Torque.TORQUE_KEY</code>.
 */
public void setConfiguration(Configuration conf) throws TorqueException {
    log.debug("setConfiguration(" + conf + ")");

    Configuration subConf = conf.subset(Torque.TORQUE_KEY);
    if (subConf == null || subConf.isEmpty()) {
        String error = ("Invalid configuration. No keys starting with " + Torque.TORQUE_KEY
                + " found in configuration");
        log.error(error);
        throw new TorqueException(error);
    }
    this.conf = subConf;
}

From source file:org.apache.whirr.service.accumulo.AccumuloConfigurationBuilder.java

private static Configuration build(ClusterSpec clusterSpec, Cluster cluster, Configuration defaults,
        String prefix) throws ConfigurationException {
    CompositeConfiguration config = new CompositeConfiguration();
    Configuration sub = clusterSpec.getConfigurationForKeysWithPrefix(prefix);
    config.addConfiguration(sub.subset(prefix)); // remove prefix
    config.addConfiguration(defaults.subset(prefix));
    return config;
}

From source file:org.apache.whirr.service.elasticsearch.ElasticSearchConfigurationBuilder.java

private static Statement asFileStatement(String path, Configuration configuration) {
    return Statements.appendFile(path, asYamlLines(configuration.subset(ES_PREFIX)));
}

From source file:org.apache.whirr.service.elasticsearch.ElasticSearchConfigurationBuilder.java

private static List<String> asYamlLines(Configuration config, int depth) {
    List<String> lines = Lists.newArrayList();
    Set<String> prefixes = Sets.newHashSet();

    Iterator<String> keys = config.getKeys();
    while (keys.hasNext()) {
        String key = keys.next();

        String[] parts = key.split("\\.");
        String prefix = parts[0];

        if (prefixes.contains(prefix)) {
            continue; // skip parsed set of keys
        }//from   ww  w . j a  v a 2  s.  c o  m

        if (parts.length == 1) {
            lines.add(spaces(depth * 2) + key + ": " + config.getProperty(key));

        } else if (parts.length > 1) {
            lines.add(spaces(depth * 2) + prefix + ":");
            lines.addAll(asYamlLines(config.subset(prefix), depth + 1));
        }

        prefixes.add(prefix);
    }

    return lines;
}

From source file:org.apache.whirr.service.elasticsearch.ElasticSearchConfigurationBuilderTest.java

@Test
public void testDefaultUnicastConfig() throws Exception {
    Configuration baseConfig = new PropertiesConfiguration();
    baseConfig.addProperty("whirr.provider", "cloudservers-us");

    ClusterSpec spec = ClusterSpec.withTemporaryKeys(baseConfig);
    Cluster cluster = mock(Cluster.class);

    Set<Cluster.Instance> instances = Sets.newLinkedHashSet();
    for (String host : Lists.newArrayList("10.0.0.1", "10.0.0.2")) {
        Cluster.Instance instance = mock(Cluster.Instance.class);
        when(instance.getPrivateIp()).thenReturn(host);
        instances.add(instance);//ww w  . j  a  va 2 s.c om
    }
    when(cluster.getInstancesMatching((Predicate<Cluster.Instance>) any())).thenReturn(instances);

    Configuration config = ElasticSearchConfigurationBuilder.buildConfig(spec, cluster);
    String content = StringUtils.join(ElasticSearchConfigurationBuilder
            .asYamlLines(config.subset(ElasticSearchConfigurationBuilder.ES_PREFIX)), "\n");

    assertThat(content, is("index:\n" + "  store:\n" + "    type: memory\n" + "gateway:\n" + "  type: none\n"
            + "discovery:\n" + "  zen:\n" + "    ping:\n" + "      multicast:\n" + "        enabled: false\n"
            + "      unicast:\n" + "        hosts: [\"10.0.0.1:9300\", \"10.0.0.2:9300\"]"));
}

From source file:org.chenillekit.core.tests.TestConfigurationService.java

@Test(expectedExceptions = { RuntimeException.class }, enabled = false)
public void test4() {
    Resource configResource = new ClasspathResource("test.ini");
    Configuration configuration = service.getConfiguration(configResource);
    Configuration subConfiguration = configuration.subset("Mail");

    assertEquals(subConfiguration.getInt("MAPI"), 1);
}

From source file:org.eclipse.jubula.documentation.gen.ConfigGroup.java

/**
 * @param group//  w w  w  .j  ava2 s . co m
 *            The name of the group read from the properties file
 * @param conf
 *            The configuration source (the properties file)
 */
public ConfigGroup(String group, Configuration conf) {
    Configuration subset = conf.subset(group);
    m_template = subset.getString(TEMPLATE);
    m_output = subset.getString(OUTPUT);
    m_generatorClass = subset.getString(GENERATOR);
    m_name = group;

    subset = subset.subset(GENERATOR);
    for (Iterator it = subset.getKeys(); it.hasNext();) {
        String key = (String) it.next();
        if (!StringConstants.EMPTY.equals(key)) {
            m_generatorProps.put(key, subset.getString(key));
        }
    }
}

From source file:org.glite.slcs.shibclient.metadata.ShibbolethClientMetadata.java

/**
 * Parses the <ShibbolethClientMetadata> element and return a map of (id,idpObject)
 * @return a Map of (idpID,idpObject)/*ww  w .j  av a 2 s.  co m*/
 * @throws SLCSConfigurationException
 */
private Map<String, Provider> parseProviders() throws SLCSConfigurationException {
    Map<String, Provider> entities = new HashMap<String, Provider>();
    LOG.debug("get configuration subset: ShibbolethClientMetadata");
    Configuration metadata = getConfiguration().subset("ShibbolethClientMetadata");
    // external metadata defined with filename= attribute?
    String metadataFilename = metadata.getString("[@filename]");
    LOG.debug("metadata filename=" + metadataFilename);
    String metadataUrl = metadata.getString("[@url]");
    LOG.debug("metadata url=" + metadataUrl);
    if (metadataFilename != null) {
        // load external metadata file       
        try {
            LOG.info("load metadata from file: " + metadataFilename);
            FileConfiguration metadataFileConfiguration = loadConfiguration(metadataFilename);
            metadataSource_ = metadataFileConfiguration.getFile().getAbsolutePath();
            metadata = metadataFileConfiguration;
        } catch (SLCSConfigurationException e) {
            LOG.error("Failed to load external ShibbolethClientMetadata: " + metadataFilename, e);
            throw e;
        }
    }
    // check for metadata url and download
    else if (metadataUrl != null) {
        // download external metadata file
        try {
            URL url = new URL(metadataUrl);
            LOG.info("download metadata from url: " + url);
            // httpclient is used to download the config
            metadata = downloadConfiguration(url);
            metadataSource_ = metadataUrl;
        } catch (MalformedURLException mue) {
            LOG.error("Invalid URL for external ShibbolethClientMetadata: " + metadataUrl, mue);
            throw new SLCSConfigurationException(
                    "ShibbolethClientMetadata url=" + metadataUrl + " parameter is invalid", mue);
        } catch (SLCSConfigurationException sce) {
            LOG.error("Failed to download ShibbolethClientMetadata from: " + metadataUrl, sce);
            throw sce;
        }
    } else {
        LOG.info("inline metadata from: " + getFilename());
        metadataSource_ = getFilename();

    }
    // process metadata
    String name = null;
    String url = null;
    String id = null;
    Configuration config = null;
    // SLCS SP
    config = metadata.subset("ServiceProvider");
    if (!config.isEmpty()) {
        LOG.debug("ServiceProvider element found");
        id = config.getString("[@id]");
        if (id == null || id.equals("")) {
            id = DEFAULT_SLCS_PROVIDERID;
        }
        this.slcsProviderId_ = id;
        name = config.getString("name");
        url = config.getString("url");
        ServiceProvider sp = new ServiceProvider(id, name, url);
        LOG.debug("add " + sp);
        entities.put(id, sp);
    } else {
        throw new SLCSConfigurationException("ServiceProvider element not found in metadata");
    }
    // All IdPs
    Configuration idpsConfig = metadata.subset("IdentityProviders");
    if (idpsConfig.isEmpty()) {
        throw new SLCSConfigurationException("IdentityProviders element not found in metadata");
    }
    List<String> idps = idpsConfig.getList("IdentityProvider[@id]");
    int nIdp = idps.size();
    if (nIdp < 1) {
        throw new SLCSConfigurationException("No IdentityProvider element found in metadata");
    }
    LOG.debug(nIdp + " IdentityProvider elements found");
    for (int i = 0; i < nIdp; i++) {
        config = idpsConfig.subset("IdentityProvider(" + i + ")");
        id = config.getString("[@id]");
        name = config.getString("name");
        url = config.getString("url");
        String authTypeName = config.getString("authentication[@type]");
        String authUrl = config.getString("authentication.url");
        if (authUrl == null) {
            authUrl = url;
        }
        IdentityProvider idp = new IdentityProvider(id, name, url, authTypeName, authUrl);
        // optional entityID for SAML2 support
        String entityID = config.getString("[@entityID]");
        if (entityID != null) {
            idp.setEntityID(entityID);
        }
        if (idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_CAS
                || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_PUBCOOKIE
                || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_FORM) {
            // read form name and username and password field names
            String formName = config.getString("authentication.form[@name]", "");
            idp.setAuthFormName(formName);
            String formUsername = config.getString("authentication.form.username");
            idp.setAuthFormUsername(formUsername);
            String formPassword = config.getString("authentication.form.password");
            idp.setAuthFormPassword(formPassword);
        } else {
            // basic or ntlm
            String realm = config.getString("authentication.realm");
            idp.setAuthRealm(realm);
        }
        LOG.debug("add " + idp);
        entities.put(id, idp);
    }
    return entities;
}