Search in sources :

Example 6 with PoolableConnection

use of org.datanucleus.store.rdbms.datasource.dbcp2.PoolableConnection in project cloudstack by apache.

the class TransactionLegacy method createDataSource.

/**
 * Creates a data source
 */
private static DataSource createDataSource(String uri, String username, String password, Integer maxActive, Integer maxIdle, Long maxWait, Long timeBtwnEvictionRuns, Long minEvictableIdleTime, Boolean testWhileIdle, Boolean testOnBorrow, String validationQuery, Integer isolationLevel) {
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri, username, password);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPoolConfig config = createPoolConfig(maxActive, maxIdle, maxWait, timeBtwnEvictionRuns, minEvictableIdleTime, testWhileIdle, testOnBorrow);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config);
    poolableConnectionFactory.setPool(connectionPool);
    if (validationQuery != null) {
        poolableConnectionFactory.setValidationQuery(validationQuery);
    }
    if (isolationLevel != null) {
        poolableConnectionFactory.setDefaultTransactionIsolation(isolationLevel);
    }
    return new PoolingDataSource<>(connectionPool);
}
Also used : ConnectionFactory(org.apache.commons.dbcp2.ConnectionFactory) DriverManagerConnectionFactory(org.apache.commons.dbcp2.DriverManagerConnectionFactory) PoolableConnectionFactory(org.apache.commons.dbcp2.PoolableConnectionFactory) PoolingDataSource(org.apache.commons.dbcp2.PoolingDataSource) DriverManagerConnectionFactory(org.apache.commons.dbcp2.DriverManagerConnectionFactory) GenericObjectPoolConfig(org.apache.commons.pool2.impl.GenericObjectPoolConfig) PoolableConnection(org.apache.commons.dbcp2.PoolableConnection) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) PoolableConnectionFactory(org.apache.commons.dbcp2.PoolableConnectionFactory)

Example 7 with PoolableConnection

use of org.datanucleus.store.rdbms.datasource.dbcp2.PoolableConnection in project kie-wb-common by kiegroup.

the class DBCPDataSourceProvider method deploy.

@Override
public DataSourceDeploymentInfo deploy(DataSourceDef dataSourceDef) throws Exception {
    DriverDef driverDef = null;
    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;
}
Also used : URLConnectionFactory(org.kie.workbench.common.screens.datasource.management.util.URLConnectionFactory) PoolingDataSource(org.apache.commons.dbcp2.PoolingDataSource) Properties(java.util.Properties) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) URI(java.net.URI) DataSourceDeploymentInfo(org.kie.workbench.common.screens.datasource.management.model.DataSourceDeploymentInfo) SQLException(java.sql.SQLException) ConnectionFactory(org.apache.commons.dbcp2.ConnectionFactory) PoolableConnectionFactory(org.apache.commons.dbcp2.PoolableConnectionFactory) URLConnectionFactory(org.kie.workbench.common.screens.datasource.management.util.URLConnectionFactory) PoolableConnection(org.apache.commons.dbcp2.PoolableConnection) DriverDef(org.kie.workbench.common.screens.datasource.management.model.DriverDef) PoolableConnectionFactory(org.apache.commons.dbcp2.PoolableConnectionFactory)

Example 8 with PoolableConnection

use of org.datanucleus.store.rdbms.datasource.dbcp2.PoolableConnection in project datanucleus-rdbms by datanucleus.

the class DBCP2BuiltinConnectionPoolFactory method createConnectionPool.

/* (non-Javadoc)
     * @see org.datanucleus.store.rdbms.datasource.ConnectionPoolFactory#createConnectionPool(org.datanucleus.store.StoreManager)
     */
public ConnectionPool createConnectionPool(StoreManager storeMgr) {
    // Load the database driver
    String dbDriver = storeMgr.getConnectionDriverName();
    if (!StringUtils.isWhitespace(dbDriver)) {
        loadDriver(dbDriver, storeMgr.getNucleusContext().getClassLoaderResolver(null));
    }
    String dbURL = storeMgr.getConnectionURL();
    PoolingDataSource ds = null;
    GenericObjectPool<PoolableConnection> connectionPool;
    try {
        // Create a factory to be used by the pool to create the connections
        Properties dbProps = getPropertiesForDriver(storeMgr);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(dbURL, dbProps);
        // Wrap the connections and statements with pooled variants
        PoolableConnectionFactory poolableCF = null;
        poolableCF = new PoolableConnectionFactory(connectionFactory, null);
        String testSQL = null;
        if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_TEST_SQL)) {
            testSQL = storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_TEST_SQL);
            poolableCF.setValidationQuery(testSQL);
        }
        // Create the actual pool of connections, and apply any properties
        connectionPool = new GenericObjectPool(poolableCF);
        poolableCF.setPool(connectionPool);
        if (testSQL != null) {
            connectionPool.setTestOnBorrow(true);
        }
        if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_IDLE)) {
            int value = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_IDLE);
            if (value > 0) {
                connectionPool.setMaxIdle(value);
            }
        }
        if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MIN_IDLE)) {
            int value = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MIN_IDLE);
            if (value > 0) {
                connectionPool.setMinIdle(value);
            }
        }
        if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_ACTIVE)) {
            int value = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_ACTIVE);
            if (value > 0) {
                connectionPool.setMaxTotal(value);
            }
        }
        if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_WAIT)) {
            int value = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_WAIT);
            if (value > 0) {
                connectionPool.setMaxWaitMillis(value);
            }
        }
        if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_TIME_BETWEEN_EVICTOR_RUNS_MILLIS)) {
            // how often should the evictor run (if ever, default is -1 = off)
            int value = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_TIME_BETWEEN_EVICTOR_RUNS_MILLIS);
            if (value > 0) {
                connectionPool.setTimeBetweenEvictionRunsMillis(value);
                // in each eviction run, evict at least a quarter of "maxIdle" connections
                int maxIdle = connectionPool.getMaxIdle();
                int numTestsPerEvictionRun = (int) Math.ceil((double) maxIdle / 4);
                connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
            }
        }
        if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME_MILLIS)) {
            // how long may a connection sit idle in the pool before it may be evicted
            int value = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME_MILLIS);
            if (value > 0) {
                connectionPool.setMinEvictableIdleTimeMillis(value);
            }
        }
        // Create the datasource
        ds = new org.datanucleus.store.rdbms.datasource.dbcp2.PoolingDataSource(connectionPool);
    } catch (Exception e) {
        throw new DatastorePoolException("DBCP2", dbDriver, dbURL, e);
    }
    return new DBCPConnectionPool(ds, connectionPool);
}
Also used : PoolingDataSource(org.datanucleus.store.rdbms.datasource.dbcp2.PoolingDataSource) DriverManagerConnectionFactory(org.datanucleus.store.rdbms.datasource.dbcp2.DriverManagerConnectionFactory) Properties(java.util.Properties) GenericObjectPool(org.datanucleus.store.rdbms.datasource.dbcp2.pool2.impl.GenericObjectPool) DriverManagerConnectionFactory(org.datanucleus.store.rdbms.datasource.dbcp2.DriverManagerConnectionFactory) PoolableConnectionFactory(org.datanucleus.store.rdbms.datasource.dbcp2.PoolableConnectionFactory) ConnectionFactory(org.datanucleus.store.rdbms.datasource.dbcp2.ConnectionFactory) PoolableConnection(org.datanucleus.store.rdbms.datasource.dbcp2.PoolableConnection) PoolingDataSource(org.datanucleus.store.rdbms.datasource.dbcp2.PoolingDataSource) PoolableConnectionFactory(org.datanucleus.store.rdbms.datasource.dbcp2.PoolableConnectionFactory)

Example 9 with PoolableConnection

use of org.datanucleus.store.rdbms.datasource.dbcp2.PoolableConnection in project tomee by apache.

the class DbcpNPEXAConnectionTest method check.

@Test
public void check() throws SQLException {
    final Connection con = ejb.newConn();
    // no NPE
    con.close();
    Assert.assertTrue("Connection was not closed", con.isClosed());
    final GenericObjectPool<PoolableConnection> pool = GenericObjectPool.class.cast(Reflections.get(ds, "connectionPool"));
    assertEquals(0, pool.getNumActive());
}
Also used : PoolableConnection(org.apache.commons.dbcp2.PoolableConnection) Connection(java.sql.Connection) PoolableConnection(org.apache.commons.dbcp2.PoolableConnection) Test(org.junit.Test)

Example 10 with PoolableConnection

use of org.datanucleus.store.rdbms.datasource.dbcp2.PoolableConnection in project ofbiz-framework by apache.

the class DBCPConnectionFactory method getConnection.

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());
    }
    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());
    // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setMinEvictableIdleTimeMillis(-1);
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    // test all the idle connections
    poolConfig.setNumTestsPerEvictionRun(maxSize);
    // settings for when the pool is exhausted
    // the thread requesting the connection waits if no connection is available
    poolConfig.setBlockWhenExhausted(true);
    // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime());
    // 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());
}
Also used : GenericEntityConfException(org.apache.ofbiz.entity.GenericEntityConfException) Driver(java.sql.Driver) Properties(java.util.Properties) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) PoolableManagedConnectionFactory(org.apache.commons.dbcp2.managed.PoolableManagedConnectionFactory) GenericEntityConfException(org.apache.ofbiz.entity.GenericEntityConfException) SQLException(java.sql.SQLException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericObjectPoolConfig(org.apache.commons.pool2.impl.GenericObjectPoolConfig) TransactionManager(javax.transaction.TransactionManager) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) PoolableConnection(org.apache.commons.dbcp2.PoolableConnection) InlineJdbc(org.apache.ofbiz.entity.config.model.InlineJdbc) DriverConnectionFactory(org.apache.commons.dbcp2.DriverConnectionFactory) XAConnectionFactory(org.apache.commons.dbcp2.managed.XAConnectionFactory) LocalXAConnectionFactory(org.apache.commons.dbcp2.managed.LocalXAConnectionFactory) LocalXAConnectionFactory(org.apache.commons.dbcp2.managed.LocalXAConnectionFactory) PoolableConnectionFactory(org.apache.commons.dbcp2.PoolableConnectionFactory)

Aggregations

PoolableConnection (org.apache.commons.dbcp2.PoolableConnection)8 PoolableConnectionFactory (org.apache.commons.dbcp2.PoolableConnectionFactory)6 GenericObjectPool (org.apache.commons.pool2.impl.GenericObjectPool)6 SQLException (java.sql.SQLException)4 ConnectionFactory (org.apache.commons.dbcp2.ConnectionFactory)4 GenericObjectPoolConfig (org.apache.commons.pool2.impl.GenericObjectPoolConfig)4 Connection (java.sql.Connection)3 Properties (java.util.Properties)3 DriverManagerConnectionFactory (org.apache.commons.dbcp2.DriverManagerConnectionFactory)3 ObjectName (javax.management.ObjectName)2 PoolingDataSource (org.apache.commons.dbcp2.PoolingDataSource)2 File (java.io.File)1 IOException (java.io.IOException)1 URI (java.net.URI)1 Driver (java.sql.Driver)1 TransactionManager (javax.transaction.TransactionManager)1 DriverConnectionFactory (org.apache.commons.dbcp2.DriverConnectionFactory)1 PoolingDriver (org.apache.commons.dbcp2.PoolingDriver)1 LocalXAConnectionFactory (org.apache.commons.dbcp2.managed.LocalXAConnectionFactory)1 ManagedConnection (org.apache.commons.dbcp2.managed.ManagedConnection)1