Example usage for org.apache.commons.dbcp AbandonedObjectPool AbandonedObjectPool

List of usage examples for org.apache.commons.dbcp AbandonedObjectPool AbandonedObjectPool

Introduction

In this page you can find the example usage for org.apache.commons.dbcp AbandonedObjectPool AbandonedObjectPool.

Prototype

public AbandonedObjectPool(PoolableObjectFactory factory, AbandonedConfig config) 

Source Link

Document

Create an ObjectPool which tracks db connections.

Usage

From source file:com.haulmont.yarg.loaders.factory.DefaultLoaderFactory.java

public static DataSource setupDataSource(String driver, String connectURI, String username, String password,
        Integer maxActive, Integer maxIdle, Integer maxWait) {
    try {/*w  w  w.java  2s  .c  o  m*/
        Class.forName(driver);
        final AbandonedConfig config = new AbandonedConfig();
        config.setLogAbandoned(true);

        AbandonedObjectPool connectionPool = new AbandonedObjectPool(null, config);

        connectionPool.setMaxIdle(maxIdle);
        connectionPool.setMaxActive(maxActive);
        if (maxWait != null) {
            connectionPool.setMaxWait(maxWait);
        }

        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, username,
                password);

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, null, false, true);

        connectionPool.setFactory(poolableConnectionFactory);
        PoolingDataSource dataSource = new PoolingDataSource(connectionPool);

        return dataSource;
    } catch (ClassNotFoundException e) {
        throw new InitializationException("An error occurred during creation of new datasource object", e);
    }
}

From source file:com.haulmont.yarg.console.PropertiesSqlLoaderFactory.java

protected DataSource setupDataSource(String driver, String connectURI, String username, String password,
        Integer maxActive, Integer maxIdle, Integer maxWait) {
    try {//from   w  w  w.  ja  v a2 s.  c  o  m
        Class.forName(driver);
        final AbandonedConfig config = new AbandonedConfig();
        config.setLogAbandoned(true);

        AbandonedObjectPool connectionPool = new AbandonedObjectPool(null, config);

        connectionPool.setMaxIdle(maxIdle);
        connectionPool.setMaxActive(maxActive);
        if (maxWait != null) {
            connectionPool.setMaxWait(maxWait);
        }

        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, username,
                password);

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, null, false, true);

        connectionPool.setFactory(poolableConnectionFactory);
        return new PoolingDataSource(connectionPool);
    } catch (ClassNotFoundException e) {
        throw new InitializationException("An error occurred during creation of new datasource object", e);
    }
}

From source file:com.naver.timetable.jdbc.CubridDataManager.java

/**
 * jdbc?  ??  ./*from  w w w.ja  v  a2 s .  c  o  m*/
 * @param strDriver
 * @param strDBConn
 * @param strUserID
 * @param strUserPW
 */
public void initDriver() {
    try {
        Class.forName(strDriver);
        Connection objConn = DriverManager.getConnection(strDBConn, strUserID, strUserPW);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    // ?  ? .
    AbandonedConfig abandonedConfig = new AbandonedConfig();
    abandonedConfig.setRemoveAbandoned(true);

    AbandonedObjectPool connectionPool = new AbandonedObjectPool(null, abandonedConfig);

    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    //      connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

    ConnectionFactory driverConnFactory = new DriverManagerConnectionFactory(strDBConn, strUserID, strUserPW);
    PoolableConnectionFactory connFactory = new PoolableConnectionFactory(driverConnFactory, connectionPool,
            null, null, defaultReadOnly, defaultAutoCommit);

    PoolingDataSource pds = new PoolingDataSource(connectionPool);
    dataSource = pds;

    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl.java

protected ObjectPool createConnectionPool(GenericObjectPool.Config config, AbandonedConfig ac) {
    final GenericObjectPool connectionPool;
    final boolean doRemoveAbandoned = ac != null && ac.getRemoveAbandoned();

    if (doRemoveAbandoned) {
        connectionPool = new AbandonedObjectPool(null, ac);
    } else {//from  www  . ja  v a  2s.  c  om
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(config.maxActive);
    connectionPool.setMaxIdle(config.maxIdle);
    connectionPool.setMinIdle(config.minIdle);
    connectionPool.setMaxWait(config.maxWait);
    connectionPool.setTestOnBorrow(config.testOnBorrow);
    connectionPool.setTestOnReturn(config.testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(config.timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(config.numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(config.minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(config.testWhileIdle);
    return connectionPool;
}

From source file:org.eclipse.osee.jdbc.internal.PooledDataSourceFetcher.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private ObjectPool<Connection> createConnectionPool() throws Exception {
    MetaData metadata = manager.getMetaData(dbInfo);

    JdbcConnectionFactory proxiedFactory = manager.getFactory(dbInfo.getDriver());
    ConnectionFactory connectionFactory = new ConnectionFactoryProxy(proxiedFactory, dbInfo,
            metadata.isTxIsolationLevelSupported());

    AbandonedObjectPool connectionPool = new AbandonedObjectPool(null,
            getAbandonedConnectionConfig(poolConfig));
    connectionPool.setConfig(getPoolConfig(poolConfig));

    GenericKeyedObjectPoolFactory statementPool = null;
    if (poolConfig.isPoolPreparedStatementsAllowed()) {
        statementPool = new GenericKeyedObjectPoolFactory(null, getStatementPoolConfig(poolConfig));
    }/*  ww w.java  2 s. com*/
    AbandonedConfig abandoned = new AbandonedConfig();
    abandoned.setLogAbandoned(true);
    abandoned.setLogWriter(new PrintWriter(System.out));

    String validationQuery = metadata.getValidationQuery();
    int validationQueryTimeoutSecs = poolConfig.getPoolValidationQueryTimeoutSecs();
    boolean defaultReadOnly = false;
    boolean defaultAutoCommit = true;
    new PoolableConnectionFactory(connectionFactory, connectionPool, statementPool, validationQuery,
            validationQueryTimeoutSecs, defaultReadOnly, defaultAutoCommit);
    return connectionPool;
}

From source file:org.onecmdb.core.utils.transform.jdbc.ClassLoaderBasicDataSource.java

/**
 * <p>Create (if necessary) and return the internal data source we are
 * using to manage our connections.</p>
 *
 * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the
 * "double checked locking" idiom in an attempt to avoid synchronizing
 * on every single call to this method.  However, this idiom fails to
 * work correctly in the face of some optimizations that are legal for
 * a JVM to perform.</p>//from ww  w .j  a va2s . c o  m
 *
 * @throws SQLException if the object pool cannot be created.
 */
protected synchronized DataSource createDataSource() throws SQLException {

    // Return the pool if we have already created it
    if (dataSource != null) {
        return (dataSource);
    }

    // Load the JDBC driver class
    Driver driver = null;
    if (driverClassName != null) {
        try {
            Class driverClass = Class.forName(driverClassName, true, driverLoader);
            driver = (Driver) driverClass.newInstance();
            //Class.forName(driverClassName);
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }

    // Create a JDBC driver instance
    if (driver == null) {
        try {
            driver = DriverManager.getDriver(url);
        } catch (Throwable t) {
            String message = "Cannot create JDBC driver of class '"
                    + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }

    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }

    // Create an object pool to contain our active connections
    if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) {
        connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    } else {
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key)
                GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait
                1, // maxIdle (per key) 
                maxOpenPreparedStatements);
    }

    // Set up the driver connection factory we will use
    if (username != null) {
        connectionProperties.put("user", username);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }

    if (password != null) {
        connectionProperties.put("password", password);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }

    DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url,
            connectionProperties);

    // Set up the poolable connection factory we will use
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool,
                statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit,
                defaultTransactionIsolation, defaultCatalog, abandonedConfig);
        if (connectionFactory == null) {
            throw new SQLException("Cannot create PoolableConnectionFactory");
        }
        validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }

    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource)
            .setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);

    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }

    return dataSource;
}

From source file:org.openspaces.jdbc.datasource.DbcpBasicDataSource.java

/**
 * <p>Create (if necessary) and return the internal data source we are
 * using to manage our connections.</p>
 *
 * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the
 * "double checked locking" idiom in an attempt to avoid synchronizing
 * on every single call to this method.  However, this idiom fails to
 * work correctly in the face of some optimizations that are legal for
 * a JVM to perform.</p>//  w  w w . j  av  a2  s.  c om
 *
 * @throws SQLException if the object pool cannot be created.
 */
protected void createDataSource() throws SQLException {

    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }

    // Create an object pool to contain our active connections
    if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned() == true)) {
        connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    } else {
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key)
                GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait
                1, // maxIdle (per key)
                maxOpenPreparedStatements);
    }

    DataSourceConnectionFactory dataSourceConnectionFactory = new DataSourceConnectionFactory(
            new SpaceDriverManagerDataSource(space));

    // Set up the poolable connection factory we will use
    try {
        PoolableConnectionFactory connectionFactory = new PoolableConnectionFactory(dataSourceConnectionFactory,
                connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit,
                defaultTransactionIsolation, defaultCatalog, abandonedConfig);
        validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }

    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource)
            .setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);

    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }
}

From source file:org.pentaho.platform.engine.services.connection.datasource.dbcp.PooledDatasourceHelper.java

public static PoolingDataSource setupPooledDataSource(IDatabaseConnection databaseConnection)
        throws DBDatasourceServiceException {
    PoolingDataSource poolingDataSource = null;
    String driverClass = null;//  ww w . j a v a 2  s  .  c  om
    String url = null;
    try {
        if (databaseConnection.getAccessType().equals(DatabaseAccessType.JNDI)) {
            throw new DBDatasourceServiceException(Messages.getInstance().getErrorString(
                    "PooledDatasourceHelper.ERROR_0008_UNABLE_TO_POOL_DATASOURCE_IT_IS_JNDI",
                    databaseConnection.getName()));
        }
        ICacheManager cacheManager = PentahoSystem.getCacheManager(null);
        IDatabaseDialectService databaseDialectService = PentahoSystem.get(IDatabaseDialectService.class);
        if (databaseDialectService == null) {
            throw new DBDatasourceServiceException(Messages.getInstance().getErrorString(
                    "PooledDatasourceHelper.ERROR_0005_UNABLE_TO_POOL_DATASOURCE_NO_DIALECT_SERVICE",
                    databaseConnection.getName()));
        }
        IDatabaseDialect dialect = databaseDialectService.getDialect(databaseConnection);
        if (dialect == null || dialect.getDatabaseType() == null) {
            throw new DBDatasourceServiceException(Messages.getInstance().getErrorString(
                    "PooledDatasourceHelper.ERROR_0004_UNABLE_TO_POOL_DATASOURCE_NO_DIALECT",
                    databaseConnection.getName()));
        }
        if (databaseConnection.getDatabaseType().getShortName().equals("GENERIC")) { //$NON-NLS-1$
            driverClass = databaseConnection.getAttributes()
                    .get(GenericDatabaseDialect.ATTRIBUTE_CUSTOM_DRIVER_CLASS);
            if (StringUtils.isEmpty(driverClass)) {
                throw new DBDatasourceServiceException(Messages.getInstance().getErrorString(
                        "PooledDatasourceHelper.ERROR_0006_UNABLE_TO_POOL_DATASOURCE_NO_CLASSNAME",
                        databaseConnection.getName()));
            }

        } else {
            driverClass = dialect.getNativeDriver();
            if (StringUtils.isEmpty(driverClass)) {
                throw new DBDatasourceServiceException(Messages.getInstance().getErrorString(
                        "PooledDatasourceHelper.ERROR_0007_UNABLE_TO_POOL_DATASOURCE_NO_DRIVER",
                        databaseConnection.getName()));
            }
        }
        try {
            url = dialect.getURLWithExtraOptions(databaseConnection);
        } catch (DatabaseDialectException e) {
            url = null;
        }

        // Read default connection pooling parameter
        String maxdleConn = PentahoSystem.getSystemSetting("dbcp-defaults/max-idle-conn", null); //$NON-NLS-1$ 
        String minIdleConn = PentahoSystem.getSystemSetting("dbcp-defaults/min-idle-conn", null); //$NON-NLS-1$    
        String maxActConn = PentahoSystem.getSystemSetting("dbcp-defaults/max-act-conn", null); //$NON-NLS-1$
        String validQuery = null;
        String whenExhaustedAction = PentahoSystem.getSystemSetting("dbcp-defaults/when-exhausted-action", //$NON-NLS-1$
                null);
        String wait = PentahoSystem.getSystemSetting("dbcp-defaults/wait", null); //$NON-NLS-1$
        String testWhileIdleValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-while-idle", null); //$NON-NLS-1$
        String testOnBorrowValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-on-borrow", null); //$NON-NLS-1$
        String testOnReturnValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-on-return", null); //$NON-NLS-1$

        // property initialization
        boolean testWhileIdle = !StringUtil.isEmpty(testWhileIdleValue)
                ? Boolean.parseBoolean(testWhileIdleValue)
                : false;
        boolean testOnBorrow = !StringUtil.isEmpty(testOnBorrowValue) ? Boolean.parseBoolean(testOnBorrowValue)
                : false;
        boolean testOnReturn = !StringUtil.isEmpty(testOnReturnValue) ? Boolean.parseBoolean(testOnReturnValue)
                : false;
        int maxActiveConnection = !StringUtil.isEmpty(maxActConn) ? Integer.parseInt(maxActConn) : -1;
        long waitTime = !StringUtil.isEmpty(wait) ? Integer.parseInt(wait) : -1;
        byte whenExhaustedActionType = !StringUtil.isEmpty(whenExhaustedAction)
                ? Byte.parseByte(whenExhaustedAction)
                : GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        int minIdleConnection = !StringUtil.isEmpty(minIdleConn) ? Integer.parseInt(minIdleConn) : -1;
        int maxIdleConnection = !StringUtil.isEmpty(maxdleConn) ? Integer.parseInt(maxdleConn) : -1;

        // setting properties according to user specifications
        Map<String, String> attributes = databaseConnection.getConnectionPoolingProperties();

        if (attributes.containsKey(IDBDatasourceService.MAX_ACTIVE_KEY)
                && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_ACTIVE_KEY))) {
            maxActiveConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_ACTIVE_KEY));
        }
        if (attributes.containsKey(IDBDatasourceService.MAX_WAIT_KEY)
                && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_WAIT_KEY))) {
            waitTime = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_WAIT_KEY));
        }
        if (attributes.containsKey(IDBDatasourceService.MIN_IDLE_KEY)
                && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MIN_IDLE_KEY))) {
            minIdleConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MIN_IDLE_KEY));
        }
        if (attributes.containsKey(IDBDatasourceService.MAX_IDLE_KEY)
                && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_IDLE_KEY))) {
            maxIdleConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_IDLE_KEY));
        }
        if (attributes.containsKey(IDBDatasourceService.QUERY_KEY)) {
            validQuery = attributes.get(IDBDatasourceService.QUERY_KEY);
        }
        if (attributes.containsKey(IDBDatasourceService.TEST_ON_BORROW)) {
            testOnBorrow = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_ON_BORROW));
        }
        if (attributes.containsKey(IDBDatasourceService.TEST_ON_RETURN)) {
            testOnReturn = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_ON_RETURN));
        }
        if (attributes.containsKey(IDBDatasourceService.TEST_WHILE_IDLE)) {
            testWhileIdle = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_WHILE_IDLE));
        }

        poolingDataSource = new PoolingDataSource();
        Class.forName(driverClass);
        // As the name says, this is a generic pool; it returns basic Object-class objects.
        GenericObjectPool pool = new GenericObjectPool(null);

        // if removedAbandoned = true, then an AbandonedObjectPool object will take GenericObjectPool's place
        if (attributes.containsKey(IDBDatasourceService.REMOVE_ABANDONED)
                && true == Boolean.parseBoolean(attributes.get(IDBDatasourceService.REMOVE_ABANDONED))) {

            AbandonedConfig config = new AbandonedConfig();
            config.setRemoveAbandoned(
                    Boolean.parseBoolean(attributes.get(IDBDatasourceService.REMOVE_ABANDONED)));

            if (attributes.containsKey(IDBDatasourceService.LOG_ABANDONED)) {
                config.setLogAbandoned(
                        Boolean.parseBoolean(attributes.get(IDBDatasourceService.LOG_ABANDONED)));
            }

            if (attributes.containsKey(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT)
                    && NumberUtils.isNumber(attributes.get(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT))) {
                config.setRemoveAbandonedTimeout(
                        Integer.parseInt(attributes.get(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT)));
            }

            pool = new AbandonedObjectPool(null, config);
        }

        pool.setWhenExhaustedAction(whenExhaustedActionType);

        // Tuning the connection pool
        pool.setMaxActive(maxActiveConnection);
        pool.setMaxIdle(maxIdleConnection);
        pool.setMaxWait(waitTime);
        pool.setMinIdle(minIdleConnection);
        pool.setTestWhileIdle(testWhileIdle);
        pool.setTestOnReturn(testOnReturn);
        pool.setTestOnBorrow(testOnBorrow);
        pool.setTestWhileIdle(testWhileIdle);

        if (attributes.containsKey(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS) && NumberUtils
                .isNumber(attributes.get(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS))) {
            pool.setTimeBetweenEvictionRunsMillis(
                    Long.parseLong(attributes.get(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS)));
        }

        /*
         * ConnectionFactory creates connections on behalf of the pool. Here, we use the DriverManagerConnectionFactory
         * because that essentially uses DriverManager as the source of connections.
         */
        ConnectionFactory factory = null;
        if (url.startsWith("jdbc:mysql:")) {
            Properties props = new Properties();
            props.put("user", databaseConnection.getUsername());
            props.put("password", databaseConnection.getPassword());
            props.put("socketTimeout", "0");
            props.put("connectTimeout", "5000");
            factory = new DriverManagerConnectionFactory(url, props);
        } else {
            factory = new DriverManagerConnectionFactory(url, databaseConnection.getUsername(),
                    databaseConnection.getPassword());
        }

        boolean defaultReadOnly = attributes.containsKey(IDBDatasourceService.DEFAULT_READ_ONLY)
                ? Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_WHILE_IDLE))
                : false; // default to false

        boolean defaultAutoCommit = attributes.containsKey(IDBDatasourceService.DEFAULT_AUTO_COMMIT)
                ? Boolean.parseBoolean(attributes.get(IDBDatasourceService.DEFAULT_AUTO_COMMIT))
                : true; // default to true

        KeyedObjectPoolFactory kopf = null;

        if (attributes.containsKey(IDBDatasourceService.POOL_PREPARED_STATEMENTS) && true == Boolean
                .parseBoolean(attributes.get(IDBDatasourceService.POOL_PREPARED_STATEMENTS))) {

            int maxOpenPreparedStatements = -1; // unlimited

            if (attributes.containsKey(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS) && NumberUtils
                    .isNumber(attributes.get(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS))) {

                maxOpenPreparedStatements = Integer
                        .parseInt(attributes.get(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS));
            }

            kopf = new GenericKeyedObjectPoolFactory(null, pool.getMaxActive(), pool.getWhenExhaustedAction(),
                    pool.getMaxWait(), pool.getMaxIdle(), maxOpenPreparedStatements);
        }

        /*
         * Puts pool-specific wrappers on factory connections. For clarification: "[PoolableConnection]Factory," not
         * "Poolable[ConnectionFactory]."
         */
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(factory, // ConnectionFactory
                pool, // ObjectPool
                kopf, // KeyedObjectPoolFactory
                validQuery, // String (validation query)
                defaultReadOnly, // boolean (default to read-only?)
                defaultAutoCommit // boolean (default to auto-commit statements?)
        );

        if (attributes.containsKey(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION)
                && !IDBDatasourceService.TRANSACTION_ISOLATION_NONE_VALUE
                        .equalsIgnoreCase(attributes.get(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION))) {
            Isolation isolationLevel = Isolation
                    .valueOf(attributes.get(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION));

            if (isolationLevel != null) {
                pcf.setDefaultTransactionIsolation(isolationLevel.value());
            }
        }

        if (attributes.containsKey(IDBDatasourceService.DEFAULT_CATALOG)) {
            pcf.setDefaultCatalog(attributes.get(IDBDatasourceService.DEFAULT_CATALOG));
        }

        /*
         * initialize the pool to X connections
         */
        Logger.debug(PooledDatasourceHelper.class,
                "Pool defaults to " + maxActiveConnection + " max active/" + maxIdleConnection + "max idle" //$NON-NLS-3$
                        + "with " + waitTime + "wait time"//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-4$ //$NON-NLS-5$
                        + " idle connections."); //$NON-NLS-1$

        for (int i = 0; i < maxIdleConnection; ++i) {
            pool.addObject();
        }
        Logger.debug(PooledDatasourceHelper.class,
                "Pool now has " + pool.getNumActive() + " active/" + pool.getNumIdle() + " idle connections."); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-3$
        /*
         * All of this is wrapped in a DataSource, which client code should already know how to handle (since it's the
         * same class of object they'd fetch via the container's JNDI tree
         */
        poolingDataSource.setPool(pool);

        if (attributes.containsKey(IDBDatasourceService.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED)) {
            poolingDataSource.setAccessToUnderlyingConnectionAllowed(Boolean.parseBoolean(
                    attributes.get(IDBDatasourceService.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED)));
        }

        // store the pool, so we can get to it later
        cacheManager.putInRegionCache(IDBDatasourceService.JDBC_POOL, databaseConnection.getName(), pool);
        return (poolingDataSource);
    } catch (Exception e) {
        throw new DBDatasourceServiceException(e);
    }
}