Example usage for org.apache.commons.dbcp2 PoolableConnectionFactory setPool

List of usage examples for org.apache.commons.dbcp2 PoolableConnectionFactory setPool

Introduction

In this page you can find the example usage for org.apache.commons.dbcp2 PoolableConnectionFactory setPool.

Prototype

public synchronized void setPool(ObjectPool<PoolableConnection> pool) 

Source Link

Document

Sets the ObjectPool in which to pool Connection s.

Usage

From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

private PoolingDataSource createPoolingDataSource(ConnectionFactory driverConnectionFactory) {

    PoolableConnectionFactory poolableConnectionFactory = null;
    try {//from ww  w .  j  a v a 2s . c o m

        poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
                new ObjectName("no.difi.oxalis", "connectionPool", "TestPool"));

        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(
                poolableConnectionFactory);
        poolableConnectionFactory.setPool(pool);
        poolableConnectionFactory.setValidationQuery("select 1");
        return new PoolingDataSource(pool);

    } catch (MalformedObjectNameException e) {
        throw new IllegalStateException("Unable to create poolable conneciton factory: " + e.getMessage(), e);
    }

}

From source file:info.pancancer.arch3.persistence.PostgreSQL.java

public PostgreSQL(HierarchicalINIConfiguration settings) {
    if (dataSource == null) {
        try {//from   ww  w  .j av a2  s .c om
            String nullConfigs = "";
            String host = settings.getString(Constants.POSTGRES_HOST);
            if (host == null) {
                nullConfigs += "postgresHost ";
            }

            String user = settings.getString(Constants.POSTGRES_USERNAME);
            if (user == null) {
                nullConfigs += "postgresUser ";
            }

            String pass = settings.getString(Constants.POSTGRES_PASSWORD);
            if (pass == null) {
                nullConfigs += "postgresPass ";
            }

            String db = settings.getString(Constants.POSTGRES_DBNAME);
            if (db == null) {
                nullConfigs += "postgresDBName ";
            }

            String maxConnections = settings.getString(Constants.POSTGRES_MAX_CONNECTIONS, "5");

            if (nullConfigs.trim().length() > 0) {
                throw new NullPointerException("The following configuration values are null: " + nullConfigs
                        + ". Please check your configuration file.");
            }

            Class.forName("org.postgresql.Driver");

            String url = "jdbc:postgresql://" + host + "/" + db;
            LOG.debug("PostgreSQL URL is: " + url);
            Properties props = new Properties();
            props.setProperty("user", user);
            props.setProperty("password", pass);
            // props.setProperty("ssl","true");
            props.setProperty("initialSize", "5");
            props.setProperty("maxActive", maxConnections);

            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props);
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                    connectionFactory, null);
            poolableConnectionFactory.setValidationQuery("select count(*) from job;");
            ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
            poolableConnectionFactory.setPool(connectionPool);
            dataSource = new PoolingDataSource<>(connectionPool);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:ddc.commons.jdbc.PooledDatasourceFactory.java

public DataSource createDataSource(JdbcConnectionFactory conn) throws ClassNotFoundException {
    conn.loadDriver();// w  w w. j  a va  2  s. c  o  m
    //
    // First, we'll create a ConnectionFactory that the
    // pool will use to create Connections.
    // We'll use the DriverManagerConnectionFactory,
    // using the connect string passed in the command line
    // arguments.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(conn.getUrl(), conn.getUser(),
            conn.getPassword());

    //
    // Next we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    //
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);

    //
    // Now we'll need a ObjectPool that serves as the
    // actual pool of connections.
    //
    // We'll use a GenericObjectPool instance, although
    // any ObjectPool implementation will suffice.
    //
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);

    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

    //
    // Finally, we create the PoolingDriver itself,
    // passing in the object pool we created.
    //
    DataSource ds = new PoolingDataSource<PoolableConnection>(connectionPool);
    return ds;
}

From source file:kr.co.bitnine.octopus.frame.ConnectionManager.java

private ObjectPool<PoolableConnection> createPool(String connectionString) {
    // A ConnectionFactory that the pool will use to create Connections.
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectionString, null);
    // PoolableConnectionFactory wraps the real Connections with the
    // classes that implement the pooling functionality.
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);//  ww  w  .  j  av  a2  s.co m
    poolableConnectionFactory.setValidationQuery("SELECT 1");

    // Actual pool of connections.
    GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    int connMax = getConfig().getInt(OctopusConfiguration.MASTER_CONNECTION_POOL_MAX, 8);
    connectionPool.setMaxTotal(connMax);
    connectionPool.setTestOnBorrow(true);
    // Set the factory's pool property to the owning pool.
    poolableConnectionFactory.setPool(connectionPool);

    return connectionPool;
}

From source file:com.xtesoft.xtecuannet.framework.templater.filler.utils.SQLScanner.java

private DataSource setupDataSource() {
    //Loading driver
    loadDriver();//  w  ww  .  jav  a  2  s  .  c  o m
    //
    // First, we'll create a ConnectionFactory that the
    // pool will use to create Connections.
    // We'll use the DriverManagerConnectionFactory,
    // using the connect string passed in the command line
    // arguments.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, pass);

    //
    // Next we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    //
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);

    //
    // Now we'll need a ObjectPool that serves as the
    // actual pool of connections.
    //
    // We'll use a GenericObjectPool instance, although
    // any ObjectPool implementation will suffice.
    //
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);

    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

    //
    // Finally, we create the PoolingDriver itself,
    // passing in the object pool we created.
    //
    PoolingDataSource<PoolableConnection> dataSource1 = new PoolingDataSource<>(connectionPool);

    return dataSource1;
}

From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImpl.java

/**
 * Creates a DataSource with connection pooling as provided by Apache DBCP
 *
 * @return a DataSource/*from   w  w w  .j a v a2 s  . c o m*/
 */
DataSource configureAndCreateDataSource(RepositoryConfiguration configuration) {

    log.debug("Configuring DataSource wrapped in a Database Connection Pool, using custom loader");

    String jdbcDriverClassPath = configuration.getJdbcDriverClassPath();

    log.debug("Loading JDBC Driver with custom class path: " + jdbcDriverClassPath);
    // Creates a new class loader, which will be used for loading our JDBC driver
    URLClassLoader urlClassLoader = getOxalisClassLoaderForJdbc(jdbcDriverClassPath);

    String className = configuration.getJdbcDriverClassName();
    String connectURI = configuration.getJdbcConnectionUri().toString();
    String userName = configuration.getJdbcUsername();
    String password = configuration.getJdbcPassword();

    log.debug("className=" + className);
    log.debug("connectURI=" + connectURI);
    log.debug("userName=" + userName);
    log.debug("password=" + password);

    // Loads the JDBC Driver in a separate class loader
    Driver driver = getJdbcDriver(jdbcDriverClassPath, urlClassLoader, className);

    Properties properties = new Properties();
    properties.put("user", userName);
    properties.put("password", password);

    // DBCP factory which will produce JDBC Driver instances
    ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectURI, properties);

    // DBCP Factory holding the pooled connection, which are created by the driver connection factory and held in the supplied pool
    ObjectName dataSourceJmxName = null;
    try {
        dataSourceJmxName = new ObjectName("no.difi.oxalis", "connectionPool", "OxalisDB");
    } catch (MalformedObjectNameException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
            dataSourceJmxName);

    String validationQuery = configuration.getValidationQuery();
    if (validationQuery != null) {
        poolableConnectionFactory.setValidationQuery(validationQuery);
    }
    // DBCP object pool holding our driver connections
    GenericObjectPool<PoolableConnection> genericObjectPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);
    poolableConnectionFactory.setPool(genericObjectPool);
    genericObjectPool.setMaxTotal(100);
    genericObjectPool.setMaxIdle(30);
    genericObjectPool.setMaxWaitMillis(10000);

    genericObjectPool.setTestOnBorrow(true); // Test the connection returned from the pool

    genericObjectPool.setTestWhileIdle(true); // Test idle instances visited by the pool maintenance thread and destroy any that fail validation
    genericObjectPool.setTimeBetweenEvictionRunsMillis(60 * 60 * 1000); // Test every hour

    // Creates the actual DataSource instance
    PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool);

    return poolingDataSource;

}

From source file:com.threecrickets.prudence.cache.SqlCache.java

/**
 * Constructor.//from   w  w w. j a  v  a  2 s .com
 * 
 * @param dataSource
 *        The data source
 * @param maxSize
 *        The max entry count
 * @param poolSize
 *        The number of connections in the pool
 * @param lockSource
 *        The lock source
 */
public SqlCache(DataSource dataSource, int maxSize, int poolSize, LockSource lockSource) {
    this.maxSize = maxSize;
    this.lockSource = lockSource;

    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxTotal(poolSize);
    config.setMaxIdle(poolSize);
    config.setMinIdle(poolSize);
    DataSourceConnectionFactory connectionFactory = new DataSourceConnectionFactory(dataSource);
    PoolableConnectionFactory pooledObjectFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pooledObjectFactory,
            config);
    pooledObjectFactory.setPool(pool);
    this.dataSource = new PoolingDataSource<PoolableConnection>(pool);
}

From source file:com.zaxxer.hikari.benchmark.BenchBase.java

private void setupDBCP2() {
    org.apache.commons.pool2.impl.GenericObjectPool<org.apache.commons.dbcp2.PoolableConnection> connectionPool;
    DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcURL, "sa", "");

    // Wrap the connections and statements with pooled variants
    org.apache.commons.dbcp2.PoolableConnectionFactory poolableCF = null;
    poolableCF = new org.apache.commons.dbcp2.PoolableConnectionFactory(connectionFactory, null);

    poolableCF.setValidationQuery("VALUES 1");
    poolableCF.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    poolableCF.setDefaultAutoCommit(false);
    poolableCF.setRollbackOnReturn(true);

    // Create the actual pool of connections, and apply any properties
    connectionPool = new org.apache.commons.pool2.impl.GenericObjectPool(poolableCF);
    connectionPool.setTestOnBorrow(true);
    connectionPool.setMaxIdle(maxPoolSize);

    connectionPool.setMinIdle(MIN_POOL_SIZE);
    connectionPool.setMaxTotal(maxPoolSize);
    connectionPool.setMaxWaitMillis(8000);
    connectionPool.setMinEvictableIdleTimeMillis((int) TimeUnit.MINUTES.toMillis(30));
    poolableCF.setPool(connectionPool);
    DS = new org.apache.commons.dbcp2.PoolingDataSource(connectionPool);
}

From source file:io.seldon.dbcp.DbcpFactory.java

private void createDbcp(DbcpConfig conf) {
    if (!dataSources.containsKey(conf.name)) {
        try {// w  w w . j a v a 2s  . c  om

            Class.forName(conf.driverClassName);

            DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory(conf.jdbc, conf.user,
                    conf.password);

            PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);
            pcf.setValidationQuery(conf.validationQuery);
            //, pool, null, conf.validationQuery, false, true,abandondedConfig);

            logger.info("Creating pool " + conf.toString());
            // create a generic pool
            GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf);
            pool.setMaxTotal(conf.maxTotal);
            pool.setMaxIdle(conf.maxIdle);
            pool.setMinIdle(conf.minIdle);
            pool.setMaxWaitMillis(conf.maxWait);
            pool.setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
            pool.setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
            pool.setTestWhileIdle(conf.testWhileIdle);
            pool.setTestOnBorrow(conf.testOnBorrow);

            AbandonedConfig abandonedConfig = new AbandonedConfig();
            abandonedConfig.setRemoveAbandonedOnMaintenance(conf.removeAbanadoned);
            abandonedConfig.setRemoveAbandonedTimeout(conf.removeAbandonedTimeout);
            abandonedConfig.setLogAbandoned(conf.logAbandonded);

            pool.setAbandonedConfig(abandonedConfig);

            pcf.setPool(pool);
            DataSource ds = new PoolingDataSource(pool);
            dataSources.put(conf.name, ds);

        } catch (ClassNotFoundException e) {
            logger.error(
                    "Failed to create datasource for " + conf.name + " with class " + conf.driverClassName);
        }

    } else {
        logger.error("Pool " + conf.name + " already exists. Can't change existing datasource at present.");
    }
}

From source file:JDBCPool.dbcp.demo.sourcecode.BasicDataSource.java

/**
 * Creates a connection pool for this datasource.  This method only exists
 * so subclasses can replace the implementation class.
 *
 * This implementation configures all pool properties other than
 * timeBetweenEvictionRunsMillis.  Setting that property is deferred to
 * {@link #startPoolMaintenance()}, since setting timeBetweenEvictionRunsMillis
 * to a positive value causes {@link GenericObjectPool}'s eviction timer
 * to be started./*from   ww  w  .  j  a  v a2s  . c o m*/
 */
protected void createConnectionPool(PoolableConnectionFactory factory) {
    // Create an object pool to contain our active connections
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    updateJmxName(config);
    config.setJmxEnabled(registeredJmxName != null); // Disable JMX on the underlying pool if the DS is not registered.
    GenericObjectPool<PoolableConnection> gop;
    if (abandonedConfig != null && (abandonedConfig.getRemoveAbandonedOnBorrow()
            || abandonedConfig.getRemoveAbandonedOnMaintenance())) {
        gop = new GenericObjectPool<>(factory, config, abandonedConfig);
    } else {
        gop = new GenericObjectPool<>(factory, config);
    }
    gop.setMaxTotal(maxTotal);
    gop.setMaxIdle(maxIdle);
    gop.setMinIdle(minIdle);
    gop.setMaxWaitMillis(maxWaitMillis);
    gop.setTestOnCreate(testOnCreate);
    gop.setTestOnBorrow(testOnBorrow);
    gop.setTestOnReturn(testOnReturn);
    gop.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    gop.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    gop.setTestWhileIdle(testWhileIdle);
    gop.setLifo(lifo);
    gop.setSwallowedExceptionListener(new SwallowedExceptionLogger(log, logExpiredConnections));
    gop.setEvictionPolicyClassName(evictionPolicyClassName);
    factory.setPool(gop);
    connectionPool = gop;
}