Example usage for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool

List of usage examples for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool

Introduction

In this page you can find the example usage for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool.

Prototype

public GenericObjectPool(PoolableObjectFactory factory) 

Source Link

Document

Create a new GenericObjectPool using the specified factory.

Usage

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;/*from   w w  w. j a va  2s  . co m*/
    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);
    }
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.connections.PooledDatasourceHelper.java

public static PoolingDataSource setupPooledDataSource(final IDatabaseConnection databaseConnection)
        throws DatasourceServiceException {
    try {//from w ww.  j a  va2s.  c  o  m
        final DataSourceCacheManager cacheManager = ClassicEngineBoot.getInstance().getObjectFactory()
                .get(DataSourceCacheManager.class);
        final IDatabaseDialectService databaseDialectService = ClassicEngineBoot.getInstance()
                .getObjectFactory().get(IDatabaseDialectService.class);
        final IDatabaseDialect dialect = databaseDialectService.getDialect(databaseConnection);

        final String driverClass;
        if (GENERIC.equals(databaseConnection.getDatabaseType().getShortName())) { //$NON-NLS-1$
            driverClass = databaseConnection.getAttributes()
                    .get(GenericDatabaseDialect.ATTRIBUTE_CUSTOM_DRIVER_CLASS);
        } else {
            driverClass = dialect.getNativeDriver();
        }

        String url;
        try {
            url = dialect.getURLWithExtraOptions(databaseConnection);
        } catch (DatabaseDialectException e) {
            url = null;
        }

        // Read default connection pooling parameter
        final String maxdleConn = getSystemSetting("dbcp-defaults.max-idle-conn"); //$NON-NLS-1$
        final String minIdleConn = getSystemSetting("dbcp-defaults.min-idle-conn"); //$NON-NLS-1$
        final String maxActConn = getSystemSetting("dbcp-defaults.max-act-conn"); //$NON-NLS-1$
        String validQuery = null;
        final String whenExhaustedAction = getSystemSetting("dbcp-defaults.when-exhausted-action"); //$NON-NLS-1$
        final String wait = getSystemSetting("dbcp-defaults.wait"); //$NON-NLS-1$
        final String testWhileIdleValue = getSystemSetting("dbcp-defaults.test-while-idle"); //$NON-NLS-1$
        final String testOnBorrowValue = getSystemSetting("dbcp-defaults.test-on-borrow"); //$NON-NLS-1$
        final String testOnReturnValue = getSystemSetting("dbcp-defaults.test-on-return"); //$NON-NLS-1$
        final boolean testWhileIdle = !StringUtils.isEmpty(testWhileIdleValue)
                && Boolean.parseBoolean(testWhileIdleValue);
        final boolean testOnBorrow = !StringUtils.isEmpty(testOnBorrowValue)
                && Boolean.parseBoolean(testOnBorrowValue);
        final boolean testOnReturn = !StringUtils.isEmpty(testOnReturnValue)
                && Boolean.parseBoolean(testOnReturnValue);
        int maxActiveConnection = -1;
        long waitTime = -1;
        byte whenExhaustedActionType = -1;
        final int minIdleConnection = !StringUtils.isEmpty(minIdleConn) ? Integer.parseInt(minIdleConn) : -1;
        final int maxIdleConnection = !StringUtils.isEmpty(maxdleConn) ? Integer.parseInt(maxdleConn) : -1;

        final Map<String, String> attributes = databaseConnection.getAttributes();

        if (attributes.containsKey(DataBaseConnectionAttributes.MAX_ACTIVE_KEY)) {
            maxActiveConnection = Integer.parseInt(attributes.get(DataBaseConnectionAttributes.MAX_ACTIVE_KEY));
        } else {
            if (!StringUtils.isEmpty(maxActConn)) {
                maxActiveConnection = Integer.parseInt(maxActConn);
            }
        }
        if (attributes.containsKey(DataBaseConnectionAttributes.MAX_WAIT_KEY)) {
            waitTime = Integer.parseInt(attributes.get(DataBaseConnectionAttributes.MAX_WAIT_KEY));
        } else {
            if (!StringUtils.isEmpty(wait)) {
                waitTime = Long.parseLong(wait);
            }
        }
        if (attributes.containsKey(DataBaseConnectionAttributes.QUERY_KEY)) {
            validQuery = attributes.get(DataBaseConnectionAttributes.QUERY_KEY);
        }
        if (!StringUtils.isEmpty(whenExhaustedAction)) {
            whenExhaustedActionType = Byte.parseByte(whenExhaustedAction);
        } else {
            whenExhaustedActionType = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        }

        final PoolingDataSource poolingDataSource = new PoolingDataSource();

        // As the name says, this is a generic pool; it returns basic Object-class objects.
        final GenericObjectPool pool = new GenericObjectPool(null);
        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);
        /*
         * ConnectionFactory creates connections on behalf of the pool. Here, we use the DriverManagerConnectionFactory
         * because that essentially uses DriverManager as the source of connections.
         */
        final Properties properties = new Properties();
        properties.setProperty("user", databaseConnection.getUsername());
        properties.setProperty("password", databaseConnection.getPassword());
        final ConnectionFactory factory = new DriverConnectionFactory(getDriver(dialect, driverClass, url), url,
                properties);

        /*
         * Puts pool-specific wrappers on factory connections. For clarification: "[PoolableConnection]Factory," not
         * "Poolable[ConnectionFactory]."
         */
        // This declaration is used implicitly.
        // noinspection UnusedDeclaration
        final PoolableConnectionFactory pcf = new PoolableConnectionFactory(factory, // ConnectionFactory
                pool, // ObjectPool
                null, // KeyedObjectPoolFactory
                validQuery, // String (validation query)
                false, // boolean (default to read-only?)
                true // boolean (default to auto-commit statements?)
        );

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

        for (int i = 0; i < maxIdleConnection; ++i) {
            pool.addObject();
        }
        logger.debug(
                "Pool now has " + pool.getNumActive() + " active/" + pool.getNumIdle() + " idle connections."); //$NON-NLS-1$ //$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);

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

From source file:org.rapidcontext.core.type.Connection.java

/**
 * Initializes this connection after loading it from a storage.
 * Any object initialization that may fail or that causes the
 * object to interact with any other part of the system (or
 * external systems) should be implemented here.
 *
 * @throws StorageException if the initialization failed
 *//*from w  w w  . j a  v  a 2 s.  co m*/
protected void init() throws StorageException {
    int open = maxOpen();
    int idle = maxIdleSeconds();

    dict.setInt("_" + KEY_MAX_OPEN, open);
    dict.setInt("_" + KEY_MAX_IDLE_SECS, idle);
    channelPool = new GenericObjectPool(new ChannelFactory());
    channelPool.setMaxActive(open);
    channelPool.setMaxIdle(open);
    channelPool.setMinIdle(0);
    channelPool.setMaxWait(MAX_ACQUIRE_WAIT);
    channelPool.setMinEvictableIdleTimeMillis(idle * 1000L);
    channelPool.setLifo(false);
    channelPool.setTestOnBorrow(true);
    channelPool.setTestOnReturn(true);
    channelPool.setTestWhileIdle(true);
    channelPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
}

From source file:org.restlet.ext.jdbc.JdbcClientHelper.java

/**
 * Creates a connection pool for a given connection configuration.
 * /*from  w ww. j a va  2s.co m*/
 * @param uri
 *            The connection URI.
 * @param properties
 *            The connection properties.
 * @return The new connection pool.
 */
public static ObjectPool createConnectionPool(String uri, Properties properties) {
    // Create an ObjectPool that will serve as the actual pool of
    // connections
    ObjectPool result = new GenericObjectPool(null);

    // Create a ConnectionFactory that the pool will use to create
    // Connections
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri, properties);

    // 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,
            result, null, null, false, false);

    // To remove warnings
    poolableConnectionFactory.getPool();

    return result;
}

From source file:org.rimudb.pool.DBCPConnectionManager.java

public void connect(String user, String password) throws Exception {

    // Load the jdbc driver
    Class.forName(poolConfiguration.getJdbcDriver());

    // Create an ObjectPool that serves as the actual pool of connections.
    connectionPool = new GenericObjectPool(null);
    connectionPool.setMaxActive(99999);/*from  w ww  .  j av  a2  s  .  c o m*/

    connectionPool.setTimeBetweenEvictionRunsMillis(poolConfiguration.getTimeBetweenEvictionRunsSecs() * 1000L);
    connectionPool.setMaxActive(poolConfiguration.getMaxActive());
    connectionPool.setMinEvictableIdleTimeMillis(poolConfiguration.getMinEvictableIdleTimeSecs() * 1000L);
    connectionPool.setMinIdle(poolConfiguration.getMinIdle());
    connectionPool.setMaxIdle(poolConfiguration.getMaxIdle());
    connectionPool.setMaxWait(poolConfiguration.getMaxWaitSecs() * 1000L);

    // Create a Properties object for the connection factory
    Properties props = new Properties();
    // Pass all the properties from the configuration into the connection factory properties
    if (poolConfiguration.getProperties() != null) {
        props.putAll(poolConfiguration.getProperties());
    }
    // Set user and password 
    if (user != null && password != null) {
        props.setProperty("user", user);
        props.setProperty("pasword", password);
    }
    props.setProperty("poolPreparedStatements", "" + poolConfiguration.getStatementCaching());

    // Create a ConnectionFactory that the pool will use to create Connections.
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(poolConfiguration.getJdbcURL(),
            props);

    KeyedObjectPoolFactory stmtPoolFactory = null;
    if (poolConfiguration.getStatementCaching()) {
        stmtPoolFactory = new GenericKeyedObjectPoolFactory(null);
    }

    // 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,
            connectionPool, stmtPoolFactory, null, false, true);

    // Create the PoolingDriver itself
    Class.forName("org.apache.commons.dbcp.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");

    // Register the pool
    driver.registerPool(dbConfig.getDatabaseID(), connectionPool);
}

From source file:org.sakaiproject.kernel.persistence.dbcp.DataSourceServiceImpl.java

/**
 * Construct a DBCP data source service.
 *
 * @param driverClassName/* w ww. j  a v a  2  s.c  o m*/
 * @param url
 * @param username
 * @param password
 * @param validationQuery
 * @param defaultReadOnly
 * @param defaultAutoCommit
 * @param poolPreparedStatements
 * @throws ClassNotFoundException
 * @throws SQLException
 */
@Inject
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = {
        "URF_UNREAD_FIELD" }, justification = "The conection factory must be initialized before use")
public DataSourceServiceImpl(@Named(KernelConstants.JDBC_DRIVER_NAME) String driverClassName,
        @Named(KernelConstants.JDBC_URL) String url, @Named(KernelConstants.JDBC_USERNAME) String username,
        @Named(KernelConstants.JDBC_PASSWORD) String password,
        @Named(KernelConstants.JDBC_VALIDATION_QUERY) String validationQuery,
        @Named(KernelConstants.JDBC_DEFAULT_READ_ONLY) boolean defaultReadOnly,
        @Named(KernelConstants.JDBC_DEFAULT_AUTO_COMMIT) boolean defaultAutoCommit,
        @Named(KernelConstants.JDBC_DEFAULT_PREPARED_STATEMENTS) boolean poolPreparedStatements)
        throws ClassNotFoundException, SQLException {

    Class.forName(driverClassName);
    GenericObjectPool connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password);

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (poolPreparedStatements) {
        int maxActive = -1;
        byte whenExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL;
        long maxWait = 0L;
        int maxIdlePerKey = 1;
        int maxOpenPreparedStatements = 0;
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, maxActive, whenExhaustedAction, maxWait,
                maxIdlePerKey, maxOpenPreparedStatements);
    }

    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool,
            statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit);
    dataSource = new PoolingDataSource(connectionPool);
}

From source file:org.sakaiproject.nakamura.persistence.dbcp.DataSourceServiceImpl.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "URF_UNREAD_FIELD",
        "UWF_UNWRITTEN_FIELD" }, justification = "PoolableConnectionFactory injects itself into connectionPool, but we need a reference to it, ConfigurationService is OSgi managed.")
protected void activate(ComponentContext componentContext) throws ClassNotFoundException {
    String driverClassName = confurationService.getProperty(NakamuraConstants.JDBC_DRIVER_NAME);

    String url = confurationService.getProperty(NakamuraConstants.JDBC_URL);
    String username = confurationService.getProperty(NakamuraConstants.JDBC_USERNAME);
    String password = confurationService.getProperty(NakamuraConstants.JDBC_PASSWORD);
    String validationQuery = confurationService.getProperty(NakamuraConstants.JDBC_VALIDATION_QUERY);
    boolean defaultReadOnly = Boolean
            .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_READ_ONLY));
    boolean defaultAutoCommit = Boolean
            .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_AUTO_COMMIT));
    boolean poolPreparedStatements = Boolean
            .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_PREPARED_STATEMENTS));

    Class.forName(driverClassName);
    GenericObjectPool connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password);

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (poolPreparedStatements) {
        int maxActive = -1;
        byte whenExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL;
        long maxWait = 0L;
        int maxIdlePerKey = 1;
        int maxOpenPreparedStatements = 0;
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, maxActive, whenExhaustedAction, maxWait,
                maxIdlePerKey, maxOpenPreparedStatements);
    }/*from  w w  w  .  j a  va  2  s .  c om*/

    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool,
            statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit);
    dataSource = new PoolingDataSource(connectionPool);
}

From source file:org.siphon.db2js.jshttp.ServerUnitManager.java

public JsEngineHandlerContext getEngineContext(final String srcFile, final String aliasPath,
        final DataSource dataSource, final Map<String, Object> otherArgs) throws Exception {

    File file = null;/*ww w.  j  a  v  a2 s  . c  o  m*/
    if (contexts.containsKey(srcFile)) {
        ObjectPool<JsEngineHandlerContext> pool = contexts.get(srcFile);
        JsEngineHandlerContext ctxt = pool.borrowObject();
        ctxt.setPool(pool);
        return ctxt;
    } else if ((file = new File(srcFile)).exists()) {
        ObjectPool<JsEngineHandlerContext> enginePool;
        BasePoolableObjectFactory<JsEngineHandlerContext> factory = new BasePoolableObjectFactory<JsEngineHandlerContext>() {

            @Override
            public JsEngineHandlerContext makeObject() throws Exception {
                return createEngineContext(srcFile, aliasPath, dataSource, otherArgs);
            }
        };

        enginePool = new GenericObjectPool<JsEngineHandlerContext>(factory);

        JsEngineHandlerContext ctxt = enginePool.borrowObject();
        ctxt.setPool(enginePool);

        contexts.put(srcFile, enginePool);

        return ctxt;
    } else {
        throw new IOException("file not found " + srcFile);
    }
}

From source file:org.snipsnap.util.ConnectionManager.java

private void update(Configuration config) {
    if (null == dataSource) {
        try {/*ww  w . j  a  va 2  s.c  o m*/
            System.err.println("ConnectionManager: Registering JDBC driver: " + config.getJdbcDriver());
            Class.forName(config.getJdbcDriver());
        } catch (Exception e) {
            Logger.fatal("unable to register JDBC driver: " + config.getJdbcDriver(), e);
        }

        String jdbcUrl = config.getJdbcUrl();
        //      if (jdbcUrl.indexOf("?") != -1) {
        //        jdbcUrl = jdbcUrl.concat("&");
        //      } else {
        //        jdbcUrl = jdbcUrl.concat("?");
        //      }
        String jdbcPassword = config.getJdbcPassword();
        //      if (null == jdbcPassword) {
        //        jdbcPassword = "";
        //      }
        //      jdbcUrl = jdbcUrl.concat("user=" + config.getJdbcUser()).concat("&password=" + jdbcPassword);
        //      System.err.println("ConnectionManager: using: "+ jdbcUrl);
        ObjectPool connectionPool = new GenericObjectPool(null);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, config.getJdbcUser(),
                jdbcPassword);
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, null, false, true);
        dataSource = new PoolingDataSource(connectionPool);
    }
}

From source file:org.soulwing.oaq.CommonsServerSessionPool.java

/**
 * Constructs a new instance.//w ww. jav a2s.  c  om
 * @param endpoint
 */
public CommonsServerSessionPool(MessageEndpointDetails endpoint,
        PoolableObjectFactory<ServerSession> objectFactory) {
    this.pool = new GenericObjectPool<ServerSession>(objectFactory);
}