FileDocCategorySizeDatePackage
JdbcDataSource.javaAPI DocApache James 2.3.111945Fri Jan 12 12:56:34 GMT 2007org.apache.james.util.dbcp

JdbcDataSource

public class JdbcDataSource extends org.apache.avalon.framework.logger.AbstractLogEnabled implements org.apache.avalon.framework.activity.Disposable, org.apache.avalon.excalibur.datasource.DataSourceComponent, org.apache.avalon.framework.configuration.Configurable

This is a reliable DataSource implementation, based on the pooling logic provided by DBCP and the configuration found in Avalon's excalibur code.

This uses the normal java.sql.Connection object and java.sql.DriverManager. The Configuration is like this:

<jdbc>

<pool-controller min="5" max="10" connection-class="my.overrided.ConnectionClass">
<keep-alive>select 1</keep-alive>
</pool-controller>

<driver>com.database.jdbc.JdbcDriver</driver>
<dburl>jdbc:driver://host/mydb</dburl>
<user>username</user>
<password>password</password>
</jdbc>

These configuration settings are available:

  • driver - The class name of the JDBC driver
  • dburl - The JDBC URL for this connection
  • user - The username to use for this connection
  • password - The password to use for this connection
  • keep-alive - The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query MUST be an SQL SELECT statement that returns at least one row.
  • max - The maximum number of active connections allowed in the pool. 0 means no limit. (default 2)
  • max_idle - The maximum number of idle connections. 0 means no limit. (default 0)
  • initial_size - The initial number of connections that are created when the pool is started. (default 0)
  • min_idle - The minimum number of active connections that can remain idle in the pool, without extra ones being created, or zero to create none. (default 0)
  • max_wait - The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely. (default -1)
  • testOnBorrow - The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. (default true)
  • testOnReturn - The indication of whether objects will be validated before being returned to the pool. (default false)
  • testWhileIdle - The indication of whether objects will be validated by the idle object evictor (if any). If an object fails to validate, it will be dropped from the pool. (default false)
  • timeBetweenEvictionRunsMillis - The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run. (default -1)
  • numTestsPerEvictionRun - The number of objects to examine during each run of the idle object evictor thread (if any). (default 3)
  • minEvictableIdleTimeMillis - The minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any). (default 1000 * 60 * 30)
version
CVS $Revision: 494012 $

Fields Summary
org.apache.commons.dbcp.BasicDataSource
source
Constructors Summary
Methods Summary
public voidconfigure(org.apache.avalon.framework.configuration.Configuration configuration)

see
org.apache.avalon.framework.configuration.Configurable#configure(Configuration)

    //Jdbc2PoolDataSource source = null;
    //PoolingDataSource source = null;

           
        
                     
        //Configure the DBCP
        try {
            String driver = configuration.getChild("driver").getValue(null);
            Class.forName(driver);

            String dburl = configuration.getChild("dburl").getValue(null);
            String user = configuration.getChild("user").getValue(null);
            String password = configuration.getChild("password").getValue(null);

            // This inner class extends DBCP's BasicDataSource, and
            // turns on validation (using Connection.isClosed()), so
            // that the pool can recover from a server outage.
            source = new BasicDataSource() {
                protected synchronized javax.sql.DataSource createDataSource()
                        throws SQLException {
                    if (dataSource != null) {
                        return (dataSource);
                    } else {
                        javax.sql.DataSource ds = super.createDataSource();
                        connectionPool.setTestOnBorrow(true);
                        connectionPool.setTestOnReturn(true);
                        return ds;
                    }
                }
            };

            source.setDriverClassName(driver);
            source.setUrl(dburl);
            source.setUsername(user);
            source.setPassword(password);
            source.setMaxActive(configuration.getChild("max").getValueAsInteger(2));
            source.setMaxIdle(configuration.getChild("max_idle").getValueAsInteger(0));
            source.setInitialSize(configuration.getChild("initial_size").getValueAsInteger(0));
            source.setMinIdle(configuration.getChild("min_idle").getValueAsInteger(0));
            //This is necessary, otherwise a connection could hang forever
            source.setMaxWait(configuration.getChild("max_wait").getValueAsInteger(5000));
            source.setValidationQuery(configuration.getChild("keep-alive").getValue(null));
            source.setTestOnBorrow(configuration.getChild("testOnBorrow").getValueAsBoolean(true));
            source.setTestOnReturn(configuration.getChild("testOnReturn").getValueAsBoolean(false));
            source.setTestWhileIdle(configuration.getChild("testWhileIdle").getValueAsBoolean(false));
            source.setTimeBetweenEvictionRunsMillis(configuration.getChild("timeBetweenEvictionRunsMillis").getValueAsInteger(-1));
            source.setNumTestsPerEvictionRun(configuration.getChild("numTestsPerEvictionRun").getValueAsInteger(3));
            source.setMinEvictableIdleTimeMillis(configuration.getChild("minEvictableIdleTimeMillis").getValueAsInteger(1000 * 30 * 60));

            //Unsupported
            //source.setLoginTimeout(configuration.getChild("login_timeout").getValueAsInteger(0));


            // DBCP uses a PrintWriter approach to logging.  This
            // Writer class will bridge between DBCP and Avalon
            // Logging. Unfortunately, DBCP 1.0 is clueless about the
            // concept of a log level.
            final java.io.Writer writer = new java.io.CharArrayWriter() {
                public void flush() {
                    // flush the stream to the log
                    if (JdbcDataSource.this.getLogger().isErrorEnabled()) {
                        JdbcDataSource.this.getLogger().error(toString());
                    }
                    reset();    // reset the contents for the next message
                }
            };

            source.setLogWriter(new PrintWriter(writer, true));

            // Extra debug for first cut
            getLogger().debug("max wait: " + source.getMaxWait());
            getLogger().debug("max idle: " + source.getMaxIdle());
            getLogger().debug("max active: " + source.getMaxActive());
            getLogger().debug("initial size: " + source.getInitialSize());
            getLogger().debug("TestOnBorrow: " + source.getTestOnBorrow());
            getLogger().debug("TestOnReturn: " + source.getTestOnReturn());
            getLogger().debug("TestWhileIdle: " + source.getTestWhileIdle());
            getLogger().debug("NumTestsPerEvictionRun(): " + source.getNumTestsPerEvictionRun());
            getLogger().debug("MinEvictableIdleTimeMillis(): " + source.getMinEvictableIdleTimeMillis());
            getLogger().debug("TimeBetweenEvictionRunsMillis(): " + source.getTimeBetweenEvictionRunsMillis());

            /*
            //Another sample that doesn't work
            GenericObjectPool connectionPool = new GenericObjectPool(null);
            ConnectionFactory connectionFactory =
                    new DriverManagerConnectionFactory(dburl, user, password);
            PoolableConnectionFactory poolableConnectionFactory =
                    new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
            PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
            source = dataSource;
            */

            /*
             As documented on the DBCP website, which is wrong
            DriverAdapterCPDS cpds = new DriverAdapterCPDS();
            cpds.setDriver(configuration.getChild("driver").getValue(null));
            cpds.setUrl(configuration.getChild("dburl").getValue(null));
            cpds.setUsername(configuration.getChild("user").getValue(null));
            cpds.setPassword(configuration.getChild("password").getValue(null));

            source = new Jdbc2PoolDataSource();
            source.setConnectionPoolDataSource(cpds);
            source.setDefaultMaxActive(10);
            source.setDefaultMaxWait(50);
            */


            //Get a connection and close it, just to test that we connected.
            source.getConnection().close();
        } catch (Exception e) {
            throw new ConfigurationException("Error configurable datasource", e);
        }
    
public voiddispose()

see
org.apache.avalon.framework.configuration.Configurable#dispose()

        //Close all database connections
        try {
            source.close();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    
public java.sql.ConnectiongetConnection()

        return source.getConnection();