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

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

Introduction

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

Prototype

Iterator getKeys();

Source Link

Document

Get the list of the keys contained in the configuration.

Usage

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

/**
 * Binds a DataSource to the jndi and checks that we have successfully
 * bound it. Then Torque is configured to lookup the DataSource in jndi,
 * and it is checked if Torque can read from the database. Finally,
 * the DataSource is closed and unbound.
 * @throws Exception if the test fails/*from  ww w . ja v a  2 s .  c o  m*/
 */
public void testTorqueBindTorqueLookup() throws Exception {
    // compose the correct configuration
    Configuration torqueConfiguration = getTorqueConfiguraton();
    String defaultDatabase = getDefaultDatabase(torqueConfiguration);

    // add the jndi configuration to the configuration
    torqueConfiguration.setProperty(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "."
            + defaultDatabase + "." + DataSourceFactory.FACTORY_KEY, JndiDataSourceFactory.class.getName());
    torqueConfiguration.setProperty(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "."
            + defaultDatabase + "." + JndiDataSourceFactory.JNDI_KEY + "." + JndiDataSourceFactory.PATH_KEY,
            JNDI_PATH);
    torqueConfiguration.setProperty(
            Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                    + JndiDataSourceFactory.JNDI_KEY + "." + Context.INITIAL_CONTEXT_FACTORY,
            org.apache.naming.java.javaURLContextFactory.class.getName());

    // add the datasource configuration
    torqueConfiguration.setProperty(
            Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                    + JndiDataSourceFactory.DATASOURCE_KEY + "." + JndiDataSourceFactory.CLASSNAME_KEY,
            BasicDataSource.class.getName());
    {
        Map tempStore = new HashMap();
        Configuration connectionConfiguration = torqueConfiguration
                .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                        + AbstractDataSourceFactory.CONNECTION_KEY);
        for (Iterator keyIt = connectionConfiguration.getKeys(); keyIt.hasNext();) {
            String key = (String) keyIt.next();
            String value = connectionConfiguration.getString(key);

            if ("user".equals(key)) {
                // setUser() in SharedPoolDataSouce corresponds to
                // setUsername() in BasicDataSourceFactory
                key = "username";
            } else if ("driver".equals(key)) {
                // setDriver() in SharedPoolDataSouce corresponds to
                // setDriverClassName() in BasicDataSourceFactory
                key = "driverClassName";
            }
            tempStore.put(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase
                    + "." + JndiDataSourceFactory.DATASOURCE_KEY + "." + key, value);
        }
        // add the new keys
        for (Iterator keyIt = tempStore.keySet().iterator(); keyIt.hasNext();) {
            String key = (String) keyIt.next();
            String value = (String) tempStore.get(key);
            torqueConfiguration.setProperty(key, value);
        }

        // remove the configuration for the original datasource
        connectionConfiguration.clear();
        Configuration poolConfiguration = torqueConfiguration
                .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                        + AbstractDataSourceFactory.POOL_KEY);
        poolConfiguration.clear();
    }

    //System.out.println("Configuration for testTorqueBindTorqueLookup:");
    //debugConfiguration(torqueConfiguration);
    //System.out.println();

    try {
        // initialize torque with the created configuration
        // and check that we can connect to the database.
        try {
            Torque.init(torqueConfiguration);
            torqueConnect();
        } finally {
            Torque.shutdown();
        }
    } finally {
        unbindDataSource();
    }
}

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

/**
 * Creates a Data Source from the Torque configuration without using Torque.
 * @return a SharedPoolDataSource source.
 * @throws Exception if we cannot create a Data source.
 *///from w w  w. j a v  a  2s . c  o  m
protected BasicDataSource getDataSource() throws Exception {
    Configuration torqueConfiguration = getTorqueConfiguraton();
    String defaultDatabase = getDefaultDatabase(torqueConfiguration);
    Configuration dsfactoryConfiguration = torqueConfiguration
            .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                    + AbstractDataSourceFactory.CONNECTION_KEY);

    BasicDataSource dataSource = new BasicDataSource();
    for (Iterator i = dsfactoryConfiguration.getKeys(); i.hasNext();) {
        String key = (String) i.next();
        String stringValue = dsfactoryConfiguration.getString(key);

        if ("user".equals(key)) {
            // setUser() in SharedPoolDataSouce corresponds to
            // setUsername() in BasicDataSourceFactory
            key = "username";
        } else if ("driver".equals(key)) {
            // setDriver() in SharedPoolDataSouce corresponds to
            // setDriverClassName() in BasicDataSourceFactory
            key = "driverClassName";
        }

        Class propertyType = PropertyUtils.getPropertyType(dataSource, key);
        Object value = ConvertUtils.convert(stringValue, propertyType);
        PropertyUtils.setSimpleProperty(dataSource, key, value);
    }

    return dataSource;
}

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

/**
 * Prints the contents of the configuration to System.out
 * @param configuration the configuration to be debugged.
 *//*from w  w w.  j a  v  a2  s  .c o  m*/
public static void debugConfiguration(Configuration configuration) {
    for (Iterator dsKeyIt = configuration.getKeys(); dsKeyIt.hasNext();) {

        String key = (String) dsKeyIt.next();
        System.out.println(key + " = " + configuration.getString(key));
    }
}

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

/**
 * Reads the adapter settings from the configuration and
 * assigns the appropriate database adapters and Id Generators
 * to the databases./*  w w w .  j a va 2  s. c  o  m*/
 *
 * @param conf the Configuration representing the torque section of the
 *        properties file.
 *
 * @throws TorqueException Any exceptions caught during processing will be
 *         rethrown wrapped into a TorqueException.
 */
private void initAdapters(Configuration conf) throws TorqueException {
    log.debug("initAdapters(" + conf + ")");

    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();
            if (key.endsWith(Adapter.ADAPTER_KEY) || key.endsWith(Adapter.DRIVER_KEY)) {
                String adapterKey = c.getString(key);
                String handle = key.substring(0, key.indexOf('.'));

                Database database = getOrCreateDatabase(handle);
                Adapter adapter = null;

                if (StringUtils.equals(Adapter.AUTODETECT_ADAPTER, adapterKey)) {
                    Connection con = null;
                    try {
                        con = database.getDataSourceFactory().getDataSource().getConnection();
                        adapter = AdapterFactory.autoDetectAdapter(con);
                    } catch (SQLException e) {
                        log.error("Could not get product information from JDBC", e);
                    } finally {
                        closeConnection(con);
                    }
                } else {
                    adapter = AdapterFactory.create(adapterKey);
                }

                // Not supported, try manually defined adapter class
                if (adapter == null) {
                    String adapterClassName = c.getString(key + "." + adapterKey + ".className", null);
                    adapter = AdapterFactory.create(adapterKey, adapterClassName);
                }

                // register the adapter for this name
                database.setAdapter(adapter);
                log.debug("Adding " + adapterKey + " -> " + handle + " as Adapter");

                // add Id generators
                for (IDMethod idMethod : IDGeneratorFactory.ID_GENERATOR_METHODS) {
                    database.addIdGenerator(idMethod, IDGeneratorFactory.create(adapter, handle));
                }
            }
        }
    } catch (InstantiationException e) {
        log.error("Error creating a database adapter instance", e);
        throw new TorqueException(e);
    }

    // check that at least the default database has got an adapter.
    Database defaultDatabase = databases.get(getDefaultDB());
    if (defaultDatabase == null || defaultDatabase.getAdapter() == null) {
        String error = "Invalid configuration : " + "No adapter definition found for default DB "
                + "An adapter must be defined under " + Torque.TORQUE_KEY + "." + Torque.DATABASE_KEY + "."
                + getDefaultDB() + "." + Adapter.ADAPTER_KEY;
        log.error(error);
        throw new TorqueException(error);
    }
}

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  a v  a  2  s  . c  om
 * 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.
 *///from w ww  . ja  v a 2 s  .  c  o m
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

/**
 * Creates a mapping between classes and their manager classes.
 *
 * The mapping is built according to settings present in
 * properties file.  The entries should have the
 * following form:// w  ww .  j  a  v  a  2  s .  co m
 *
 * <pre>
 * torque.managed_class.com.mycompany.Myclass.manager= \
 *          com.mycompany.MyManagerImpl
 * services.managed_class.com.mycompany.Myotherclass.manager= \
 *          com.mycompany.MyOtherManagerImpl
 * </pre>
 *
 * <br>
 *
 * Generic ServiceBroker provides no Services.
 *
 * @param conf the Configuration representing the properties file
 * @throws TorqueException Any exceptions caught during processing will be
 *         rethrown wrapped into a TorqueException.
 */
protected synchronized void initManagerMappings(Configuration conf) throws TorqueException {
    int pref = Torque.MANAGER_PREFIX.length();
    int suff = Torque.MANAGER_SUFFIX.length();

    for (Iterator<?> it = conf.getKeys(); it.hasNext();) {
        String key = (String) it.next();

        if (key.startsWith(Torque.MANAGER_PREFIX) && key.endsWith(Torque.MANAGER_SUFFIX)) {
            String managedClassKey = key.substring(pref, key.length() - suff);
            if (!managers.containsKey(managedClassKey)) {
                String managerClass = conf.getString(key);
                log.info("Added Manager for Class: " + managedClassKey + " -> " + managerClass);
                try {
                    initManager(managedClassKey, managerClass);
                } catch (TorqueException e) {
                    // the exception thrown here seems to disappear.
                    // At least when initialized by Turbine, should find
                    // out why, but for now make sure it is noticed.
                    log.error("", e);
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }
}

From source file:org.apache.whirr.ClusterSpecTest.java

@Test
public void testGetConfigurationForKeysWithPrefix() throws ConfigurationException, JSchException, IOException {
    Configuration conf = new PropertiesConfiguration();
    conf.setProperty("a.b", 1);
    conf.setProperty("b.a", 2);
    conf.setProperty("a.c", 3);

    ClusterSpec spec = ClusterSpec.withNoDefaults(conf);
    Configuration prefixConf = spec.getConfigurationForKeysWithPrefix("a");

    List<String> prefixKeys = Lists.newArrayList();
    Iterators.addAll(prefixKeys, prefixConf.getKeys());

    assertThat(prefixKeys.size(), is(2));
    assertThat(prefixKeys.get(0), is("a.b"));
    assertThat(prefixKeys.get(1), is("a.c"));
}

From source file:org.apache.whirr.service.chef.Recipe.java

/**
 * Package protected to be used only by {@link ChefClusterActionHandler}.
 * /*from  w  ww  .  ja  v  a 2  s .c  o  m*/
 * @param config
 */
Recipe(String cookbook, String recipe, Configuration config) {
    this(cookbook, recipe);
    for (Iterator<?> iter = config.getKeys(); iter.hasNext();) {
        String key = (String) iter.next();
        String attribute = key.substring(cookbook.length() + 1, key.length());
        if (attribute.equals("url")) {
            this.url = config.getString(key);
        } else {
            attribs.put(attribute, config.getProperty(key));
        }
    }
}

From source file:org.apache.whirr.service.cinderella.CommonsConfigurationToCinderellaConfig.java

@SuppressWarnings("unchecked")
static String getPropertyOrThrowReasonableNPE(String propertyKey, Configuration config) {
    return checkNotNull(config.getString(propertyKey), "%s not in %s", propertyKey,
            ImmutableSet.copyOf(config.getKeys()));
}