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:no.sr.ringo.persistence.jdbc.RingoDataSourceFactoryDbcpImpl.java

private PoolingDataSource getPoolingDataSource(JdbcConfiguration configuration, String connectURI,
        String userName, String password, Driver driver) {
    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;
    try {//from  w ww.j a va2 s .c  o m
        dataSourceJmxName = new ObjectName("no.difi.oxalis", "connectionPool", "OxalisDB");
    } catch (MalformedObjectNameException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
            dataSourceJmxName);

    if (configuration.getValidationQuery().isPresent()) {
        poolableConnectionFactory.setValidationQuery(configuration.getValidationQuery().get());
    }
    // 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
    return new PoolingDataSource(genericObjectPool);
}

From source file:org.apache.ofbiz.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    DebugManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }/*from  ww  w  .  jav a 2s. c  o  m*/
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    factory.setRollbackOnReturn(false);
    factory.setEnableAutoCommitOnReturn(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(factory, poolConfig);
    factory.setPool(pool);

    mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry());
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.apache.zeppelin.jdbc.JDBCInterpreter.java

private void createConnectionPool(String url, String user, String propertyKey, Properties properties)
        throws SQLException, ClassNotFoundException {
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, properties);

    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);// w  w w.j  a v a2s .  c o  m
    ObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory);

    poolableConnectionFactory.setPool(connectionPool);
    Class.forName(properties.getProperty(DRIVER_KEY));
    PoolingDriver driver = new PoolingDriver();
    driver.registerPool(propertyKey + user, connectionPool);
    getJDBCConfiguration(user).saveDBDriverPool(propertyKey, driver);
}

From source file:org.apdplat.superword.tools.MySQLUtils.java

private static DataSource setupDataSource(String connectUri, String uname, String passwd) {
    ////from   w w w.  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(connectUri, uname, passwd);

    //
    // 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> dataSource = new PoolingDataSource<>(connectionPool);

    return dataSource;
}

From source file:org.jboss.narayana.quickstart.spring.config.DatabaseConfig.java

@Bean
public DataSource dataSource() {
    DataSourceXAConnectionFactory dataSourceXAConnectionFactory = new DataSourceXAConnectionFactory(tm,
            h2DataSource());//from w  ww. j  a v  a  2 s.  c  o  m
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
            dataSourceXAConnectionFactory, null);
    GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    return new ManagedDataSource<>(connectionPool, dataSourceXAConnectionFactory.getTransactionRegistry());
}

From source file:org.kie.workbench.common.screens.datasource.management.backend.core.dbcp.DBCPDataSourceProvider.java

@Override
public DataSourceDeploymentInfo deploy(DataSourceDef dataSourceDef) throws Exception {

    DriverDef driverDef = null;/*from  w  w w  . j  av a  2  s. co m*/
    for (DriverDef _driverDef : driverProvider.getDeployments()) {
        if (_driverDef.getUuid().equals(dataSourceDef.getDriverUuid())) {
            driverDef = _driverDef;
            break;
        }
    }

    if (driverDef == null) {
        throw new Exception("Required driver: " + dataSourceDef.getDriverUuid() + " is not deployed");
    }

    final URI uri = artifactResolver.resolve(driverDef.getGroupId(), driverDef.getArtifactId(),
            driverDef.getVersion());
    if (uri == null) {
        throw new Exception("Unable to get driver library artifact for driver: " + driverDef);
    }

    final Properties properties = new Properties();
    properties.setProperty("user", dataSourceDef.getUser());
    properties.setProperty("password", dataSourceDef.getPassword());
    final URLConnectionFactory urlConnectionFactory = buildConnectionFactory(uri, driverDef.getDriverClass(),
            dataSourceDef.getConnectionURL(), properties);

    //Connection Factory that the pool will use for creating connections.
    ConnectionFactory connectionFactory = new DBCPConnectionFactory(urlConnectionFactory);

    //Poolable connection factory
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);

    //The pool to be used by the ConnectionFactory
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);

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

    //Finally create DataSource
    PoolingDataSource<PoolableConnection> dataSource = new PoolingDataSource<>(connectionPool);

    DataSourceDeploymentInfo deploymentInfo = new DataSourceDeploymentInfo(dataSourceDef.getUuid(), true,
            dataSourceDef.getUuid(), false);

    deploymentRegistry.put(deploymentInfo.getDeploymentId(), new DBCPDataSource(dataSource));
    deploymentInfos.put(deploymentInfo.getDeploymentId(), deploymentInfo);
    deployedDataSources.put(deploymentInfo.getDeploymentId(), dataSourceDef);

    return deploymentInfo;
}

From source file:org.moneta.config.ConnectionPoolFactory.java

public static ObjectPool<PoolableConnection> createConnectionPool(MonetaDataSource dataSourceType) {
    Validate.notNull(dataSourceType, "Null MonetaDataSource not allowed.");

    Validate.notEmpty(dataSourceType.getDataSourceName(), "Null or blank name not allowed");
    Validate.notEmpty(dataSourceType.getConnectionUrl(), "Null or blank url not allowed");
    Validate.notNull(dataSourceType.getDriver(), "Null driver not allowed");

    try {//from ww  w .  j  av a2s  . c om
        dataSourceType.getDriver().newInstance();
    } catch (Exception e) {
        throw new MonetaException("Data source JDBC driver can't be instantiated", e)
                .addContextValue("JDBC Driver class", dataSourceType.getDriver().getName());
    }

    Properties connectionProps = new Properties();
    connectionProps.putAll(dataSourceType.getJdbcConnectionProperties());
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(dataSourceType.getConnectionUrl(),
            connectionProps);

    ObjectName poolName = null;
    try {
        poolName = new ObjectName("org.moneta", "connectionPool", dataSourceType.getDataSourceName());
    } catch (MalformedObjectNameException e) {
        throw new MonetaException("Data source name not valid", e).addContextValue("Data source name",
                dataSourceType.getDataSourceName());
    }
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            poolName);

    Set<String> unusedConnectionPoolPropSet = new HashSet<String>();
    Map<String, String> propMap = new HashMap<String, String>(dataSourceType.getConnectionPoolProperties());

    PropertyDescriptor pDesc = null;
    for (String propName : propMap.keySet()) {
        pDesc = assignProperty(dataSourceType.getDataSourceName(), poolableConnectionFactory, propName,
                propMap.get(propName));
        if (pDesc == null) {
            unusedConnectionPoolPropSet.add(propName);
        }
    }

    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);
    poolableConnectionFactory.setPool(pool);

    for (String propName : new HashSet<String>(unusedConnectionPoolPropSet)) {
        pDesc = assignProperty(dataSourceType.getDataSourceName(), pool, propName, propMap.get(propName));
        if (pDesc != null) {
            unusedConnectionPoolPropSet.remove(propName);
        }
    }

    if (unusedConnectionPoolPropSet.size() > 0) {
        MonetaException me = new MonetaException("Invalid connection pool properties detected");
        for (String propName : unusedConnectionPoolPropSet) {
            me.addContextValue("pool property name", propName);
        }

        throw me;
    }
    return pool;
}

From source file:org.noerp.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    ManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }/*from   www .java  2s. c  o  m*/
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool pool = new GenericObjectPool(factory, poolConfig);
    factory.setPool(pool);

    mds = new ManagedDataSource(pool, xacf.getTransactionRegistry());
    //mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry()); // Useful to debug the usage of connections in the pool
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.ops4j.pax.jdbc.pool.dbcp2.impl.DbcpPooledDataSourceFactory.java

@Override
public DataSource create(DataSourceFactory dsf, Properties props) throws SQLException {
    try {// ww  w  .  j av a  2s .  c o  m
        DataSource ds = dsf.createDataSource(getNonPoolProps(props));
        DataSourceConnectionFactory connFactory = new DataSourceConnectionFactory((DataSource) ds);
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, null);
        GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
        BeanConfig.configure(conf, getPoolProps(props));
        BeanConfig.configure(pcf, getPrefixed(props, FACTORY_PREFIX));
        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf, conf);
        pcf.setPool(pool);
        return new PoolingDataSource<PoolableConnection>(pool);
    } catch (Throwable e) {
        LOG.error("Error creating pooled datasource" + e.getMessage(), e);
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:org.ops4j.pax.jdbc.pool.dbcp2.impl.ds.DbcpPooledDataSourceFactory.java

@Override
public DataSource createDataSource(Properties props) throws SQLException {
    try {//from ww  w .  j a v  a  2 s  .  co m
        DataSource ds = dsFactory.createDataSource(getNonPoolProps(props));
        DataSourceConnectionFactory connFactory = new DataSourceConnectionFactory((DataSource) ds);
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, null);
        GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
        BeanConfig.configure(conf, getPoolProps(props));
        BeanConfig.configure(pcf, getPrefixed(props, FACTORY_PREFIX));
        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf, conf);
        pcf.setPool(pool);
        return new PoolingDataSource<PoolableConnection>(pool);
    } catch (Throwable e) {
        LOG.error("Error creating pooled datasource" + e.getMessage(), e);
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}