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.dsfactory.AbstractDataSourceFactory.java

/**
 * Encapsulates setting configuration properties on
 * <code>DataSource</code> objects.
 *
 * @param property the property to read from the configuration
 * @param c the configuration to read the property from
 * @param ds the <code>DataSource</code> instance to write the property to
 * @throws Exception if anything goes wrong
 *//*  w w  w.  j  av  a2 s  . co m*/
protected void setProperty(String property, Configuration c, Object ds) throws Exception {
    if (c == null || c.isEmpty()) {
        return;
    }

    String key = property;
    Class<?> dsClass = ds.getClass();
    int dot = property.indexOf('.');
    try {
        if (dot > 0) {
            property = property.substring(0, dot);

            MappedPropertyDescriptor mappedPD = new MappedPropertyDescriptor(property, dsClass);
            Class<?> propertyType = mappedPD.getMappedPropertyType();
            Configuration subProps = c.subset(property);
            // use reflection to set properties
            Iterator<?> j = subProps.getKeys();
            while (j.hasNext()) {
                String subProp = (String) j.next();
                String propVal = subProps.getString(subProp);
                Object value = ConvertUtils.convert(propVal, propertyType);
                PropertyUtils.setMappedProperty(ds, property, subProp, value);

                if (log.isDebugEnabled()) {
                    log.debug(
                            "setMappedProperty(" + ds + ", " + property + ", " + subProp + ", " + value + ")");
                }
            }
        } else {
            if ("password".equals(key)) {
                // do not log value of password
                // for this, ConvertUtils.convert cannot be used
                // as it also logs the value of the converted property
                // so it is assumed here that the password is a String
                String value = c.getString(property);
                PropertyUtils.setSimpleProperty(ds, property, value);
                if (log.isDebugEnabled()) {
                    log.debug("setSimpleProperty(" + ds + ", " + property + ", " + " (value not logged)" + ")");
                }
            } else {
                Class<?> propertyType = PropertyUtils.getPropertyType(ds, property);
                Object value = ConvertUtils.convert(c.getString(property), propertyType);
                PropertyUtils.setSimpleProperty(ds, property, value);

                if (log.isDebugEnabled()) {
                    log.debug("setSimpleProperty(" + ds + ", " + property + ", " + value + ")");
                }
            }
        }
    } catch (RuntimeException e) {
        throw new TorqueRuntimeException("Runtime error setting property " + property, e);
    } catch (Exception e) {
        log.error("Property: " + property + " value: " + c.getString(key) + " is not supported by DataSource: "
                + ds.getClass().getName());
    }
}

From source file:org.apache.torque.dsfactory.AbstractDataSourceFactory.java

/**
 * Initializes the ConnectionPoolDataSource.
 *
 * @param configuration where to read the settings from
 * @throws TorqueException if a property set fails
 * @return a configured <code>ConnectionPoolDataSource</code>
 *//*  w w w.  ja v a  2s .com*/
protected ConnectionPoolDataSource initCPDS(Configuration configuration) throws TorqueException {
    log.debug("Starting initCPDS");
    ConnectionPoolDataSource cpds = new DriverAdapterCPDS();
    Configuration c = Torque.getConfiguration();

    if (c == null || c.isEmpty()) {
        log.warn("Global Configuration not set," + " no Default connection pool data source configured!");
    } else {
        Configuration conf = c.subset(DEFAULT_CONNECTION_KEY);
        applyConfiguration(conf, cpds);
    }

    Configuration conf = configuration.subset(CONNECTION_KEY);
    applyConfiguration(conf, cpds);

    return cpds;
}

From source file:org.apache.torque.dsfactory.JndiDataSourceFactory.java

/**
 * Initializes JNDI./*  w  w  w .j  a  v a2  s  .c  om*/
 *
 * @param configuration where to read the settings from
 * @throws TorqueException if a property set fails
 */
private void initJNDI(Configuration configuration) throws TorqueException {
    log.debug("Starting initJNDI");

    Configuration c = configuration.subset(JNDI_KEY);
    if (c == null || c.isEmpty()) {
        throw new TorqueException(
                "JndiDataSourceFactory requires a jndi " + "path property to lookup the DataSource in JNDI.");
    }

    try {
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        for (Iterator<?> i = c.getKeys(); i.hasNext();) {
            String key = (String) i.next();
            if (key.equals(PATH_KEY)) {
                path = c.getString(key);
                if (log.isDebugEnabled()) {
                    log.debug("JNDI path: " + path);
                }
            } else if (key.equals(TIME_BETWEEN_LOOKUPS_KEY)) {
                ttl = c.getLong(key, ttl);
                if (log.isDebugEnabled()) {
                    log.debug("Time between context lookups: " + ttl);
                }
            } else {
                String value = c.getString(key);
                env.put(key, value);
                if (log.isDebugEnabled()) {
                    log.debug("Set jndi property: " + key + "=" + value);
                }
            }
        }

        ctx = new InitialContext(env);
        log.debug("Created new InitialContext");
        debugCtx(ctx);
    } catch (Exception e) {
        log.error("", e);
        throw new TorqueException(e);
    }
}

From source file:org.apache.torque.dsfactory.JndiDataSourceFactory.java

/**
 * Initializes the DataSource.//from w  ww  .  j ava2  s .co  m
 *
 * @param configuration where to read the settings from
 * @throws TorqueException if a property set fails
 */
private void initDataSource(Configuration configuration) throws TorqueException {
    log.debug("Starting initDataSource");
    try {
        Object dataSource = null;

        Configuration c = configuration.subset(DATASOURCE_KEY);
        if (c != null) {
            for (Iterator<?> i = c.getKeys(); i.hasNext();) {
                String key = (String) i.next();
                if (key.equals(CLASSNAME_KEY)) {
                    String classname = c.getString(key);
                    if (log.isDebugEnabled()) {
                        log.debug("Datasource class: " + classname);
                    }

                    Class<?> dsClass = Class.forName(classname);
                    dataSource = dsClass.newInstance();
                } else {
                    if (dataSource != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Setting datasource property: " + key);
                        }
                        setProperty(key, c, dataSource);
                    } else {
                        log.error("Tried to set property " + key + " without Datasource definition!");
                    }
                }
            }
        }

        if (dataSource != null) {
            synchronized (ctx) {
                bindDStoJndi(ctx, path, dataSource);
            }
        }
    } catch (Exception e) {
        log.error("", e);
        throw new TorqueException(e);
    }
}

From source file:org.apache.torque.dsfactory.PerUserPoolDataSourceFactory.java

/**
 * Initializes the Jdbc2PoolDataSource./* w  w w  .ja  v  a2 s.  c  o m*/
 *
 * @param configuration where to read the settings from
 * @throws TorqueException if a property set fails
 * @return a configured <code>Jdbc2PoolDataSource</code>
 */
private PerUserPoolDataSource initJdbc2Pool(Configuration configuration) throws TorqueException {
    log.debug("Starting initJdbc2Pool");
    PerUserPoolDataSource dataSource = new PerUserPoolDataSource();
    Configuration c = Torque.getConfiguration();

    if (c == null || c.isEmpty()) {
        log.warn("Global Configuration not set," + " no Default pool data source configured!");
    } else {
        Configuration conf = c.subset(DEFAULT_POOL_KEY);
        applyConfiguration(conf, dataSource);
    }

    Configuration conf = configuration.subset(POOL_KEY);
    applyConfiguration(conf, dataSource);
    return dataSource;
}

From source file:org.apache.torque.dsfactory.SharedPoolDataSourceFactory.java

/**
 * Initializes the Jdbc2PoolDataSource./* w w  w  .  jav  a2 s  .  c o  m*/
 *
 * @param configuration where to read the settings from
 * @throws TorqueException if a property set fails
 * @return a configured <code>Jdbc2PoolDataSource</code>
 */
private SharedPoolDataSource initJdbc2Pool(Configuration configuration) throws TorqueException {
    log.debug("Starting initJdbc2Pool");
    SharedPoolDataSource dataSource = new SharedPoolDataSource();
    Configuration c = Torque.getConfiguration();

    if (c == null || c.isEmpty()) {
        log.warn("Global Configuration not set," + " no Default pool data source configured!");
    } else {
        Configuration conf = c.subset(DEFAULT_POOL_KEY);
        applyConfiguration(conf, dataSource);
    }

    Configuration conf = configuration.subset(POOL_KEY);
    applyConfiguration(conf, dataSource);
    return dataSource;
}

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 testExternalBindTorqueLookup() throws Exception {
    // compose the correct configuration
    Configuration torqueConfiguration = getTorqueConfiguraton();
    String defaultDatabase = getDefaultDatabase(torqueConfiguration);

    // remove the dsfactory configuration from the configuration
    {
        Configuration dsfactoryConfiguration = torqueConfiguration
                .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase);
        dsfactoryConfiguration.clear();
    }

    // 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());

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

    try {
        // bind datasource and check bind.
        bindDataSource();
        BasicDataSource dataSource = retrieveDataSource();
        dataSourceConnect(dataSource);

        if (Torque.isInit()) {
            Torque.shutdown();
        }
        // 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

/**
 * 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 w  ww .j  a va 2s . 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  .  ja  v  a2  s .  com
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.TorqueInstance.java

/**
 * Reads the adapter settings from the configuration and
 * assigns the appropriate database adapters and Id Generators
 * to the databases.//from   www  .  ja  v a2s .  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);
    }
}