Search in sources :

Example 1 with PoolableConnection

use of org.apache.tomcat.dbcp.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 2 with PoolableConnection

use of org.apache.tomcat.dbcp.dbcp2.PoolableConnection in project tomee by apache.

the class BasicManagedDataSource method createDataSourceInstance.

@Override
protected DataSource createDataSourceInstance() throws SQLException {
    final TransactionRegistry transactionRegistry = getTransactionRegistry();
    if (transactionRegistry == null) {
        throw new IllegalStateException("TransactionRegistry has not been set");
    }
    if (getConnectionPool() == null) {
        throw new IllegalStateException("Pool has not been set");
    }
    final PoolingDataSource<PoolableConnection> pds = new ManagedDataSource<PoolableConnection>(getConnectionPool(), transactionRegistry) {

        @Override
        public Connection getConnection() throws SQLException {
            return new ManagedConnection<PoolableConnection>(getPool(), transactionRegistry, isAccessToUnderlyingConnectionAllowed()) {

                @Override
                public void close() throws SQLException {
                    if (!isClosedInternal()) {
                        try {
                            if (null != getDelegateInternal()) {
                                super.close();
                            }
                        } finally {
                            setClosedInternal(true);
                        }
                    }
                }

                @Override
                public boolean isClosed() throws SQLException {
                    return isClosedInternal() || null != getDelegateInternal() && getDelegateInternal().isClosed();
                }
            };
        }
    };
    pds.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    return pds;
}
Also used : PoolableConnection(org.apache.commons.dbcp2.PoolableConnection) TransactionRegistry(org.apache.commons.dbcp2.managed.TransactionRegistry) ManagedConnection(org.apache.commons.dbcp2.managed.ManagedConnection) ManagedDataSource(org.apache.commons.dbcp2.managed.ManagedDataSource)

Example 3 with PoolableConnection

use of org.apache.tomcat.dbcp.dbcp2.PoolableConnection in project tomcat by apache.

the class PoolableManagedConnectionFactory method makeObject.

/**
 * Uses the configured XAConnectionFactory to create a {@link PoolableManagedConnection}. Throws
 * <code>IllegalStateException</code> if the connection factory returns null. Also initializes the connection using
 * configured initialization SQL (if provided) and sets up a prepared statement pool associated with the
 * PoolableManagedConnection if statement pooling is enabled.
 */
@Override
public synchronized PooledObject<PoolableConnection> makeObject() throws Exception {
    Connection conn = getConnectionFactory().createConnection();
    if (conn == null) {
        throw new IllegalStateException("Connection factory returned null from createConnection");
    }
    initializeConnection(conn);
    if (getPoolStatements()) {
        conn = new PoolingConnection(conn);
        final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
        config.setMaxTotalPerKey(-1);
        config.setBlockWhenExhausted(false);
        config.setMaxWait(Duration.ZERO);
        config.setMaxIdlePerKey(1);
        config.setMaxTotal(getMaxOpenPreparedStatements());
        final ObjectName dataSourceJmxName = getDataSourceJmxName();
        final long connIndex = getConnectionIndex().getAndIncrement();
        if (dataSourceJmxName != null) {
            final StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
            base.append(Constants.JMX_CONNECTION_BASE_EXT);
            base.append(connIndex);
            config.setJmxNameBase(base.toString());
            config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
        } else {
            config.setJmxEnabled(false);
        }
        final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>((PoolingConnection) conn, config);
        ((PoolingConnection) conn).setStatementPool(stmtPool);
        ((PoolingConnection) conn).setCacheState(getCacheState());
    }
    final PoolableManagedConnection pmc = new PoolableManagedConnection(transactionRegistry, conn, getPool(), getDisconnectionSqlCodes(), isFastFailValidation());
    pmc.setCacheState(getCacheState());
    return new DefaultPooledObject<>(pmc);
}
Also used : GenericKeyedObjectPoolConfig(org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPoolConfig) DelegatingPreparedStatement(org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement) GenericKeyedObjectPool(org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPool) Connection(java.sql.Connection) PoolableConnection(org.apache.tomcat.dbcp.dbcp2.PoolableConnection) PoolingConnection(org.apache.tomcat.dbcp.dbcp2.PoolingConnection) PStmtKey(org.apache.tomcat.dbcp.dbcp2.PStmtKey) ObjectName(javax.management.ObjectName) PoolingConnection(org.apache.tomcat.dbcp.dbcp2.PoolingConnection) DefaultPooledObject(org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject)

Example 4 with PoolableConnection

use of org.apache.tomcat.dbcp.dbcp2.PoolableConnection in project athenz by yahoo.

the class DataSourceFactory method create.

static PoolableDataSource create(ConnectionFactory connectionFactory) {
    // setup our pool config object
    GenericObjectPoolConfig config = setupPoolConfig();
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    // Set max lifetime of a connection in milli-secs, after which it will
    // always fail activation, passivation, and validation.
    // Value of -1 means infinite life time. The default value
    // defined in this class is 10 minutes.
    long connTtlMillis = retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_TTL, MAX_TTL_CONN_MS);
    poolableConnectionFactory.setMaxConnLifetimeMillis(connTtlMillis);
    if (LOG.isInfoEnabled()) {
        LOG.info("Setting Time-To-Live interval for live connections ({}) msecs", connTtlMillis);
    }
    // set the validation query for our jdbc connector
    final String validationQuery = System.getProperty(ATHENZ_PROP_DBPOOL_VALIDATION_QUERY, MYSQL_VALIDATION_QUERY);
    poolableConnectionFactory.setValidationQuery(validationQuery);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config);
    poolableConnectionFactory.setPool(connectionPool);
    return new AthenzDataSource(connectionPool);
}
Also used : 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 5 with PoolableConnection

use of org.apache.tomcat.dbcp.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)9 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 Properties (java.util.Properties)3 DriverManagerConnectionFactory (org.apache.commons.dbcp2.DriverManagerConnectionFactory)3 Connection (java.sql.Connection)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 ObjectName (javax.management.ObjectName)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