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, int maxActive, byte whenExhaustedAction, long maxWait,
        int maxIdle, boolean testOnBorrow, boolean testOnReturn) 

Source Link

Document

Create a new GenericObjectPool using the specified values.

Usage

From source file:edu.amc.sakai.user.GenericObjectPoolTest.java

protected void setUp() throws Exception {

    mockFactory = new Mock(PoolableObjectFactory.class);
    factory = (PoolableObjectFactory) mockFactory.proxy();

    pool = new GenericObjectPool(factory, 1, // maxActive
            GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // whenExhaustedAction
            60000, // maxWait (millis)
            1, // maxIdle
            true, // testOnBorrow
            false // testOnReturn
    );/*from  w  w  w  .  j ava  2 s  .c om*/

    super.setUp();
}

From source file:org.dspace.storage.rdbms.DataSourceInit.java

public static DataSource getDatasource() throws SQLException {
    if (dataSource != null) {
        return dataSource;
    }/*from w w w .  j ava 2 s . c  o  m*/

    try {
        // Register basic JDBC driver
        Class driverClass = Class.forName(ConfigurationManager.getProperty("db.driver"));
        Driver basicDriver = (Driver) driverClass.newInstance();
        DriverManager.registerDriver(basicDriver);

        // Read pool configuration parameter or use defaults
        // Note we check to see if property is null; getIntProperty returns
        // '0' if the property is not set OR if it is actually set to zero.
        // But 0 is a valid option...
        int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections");

        if (ConfigurationManager.getProperty("db.maxconnections") == null) {
            maxConnections = 30;
        }

        int maxWait = ConfigurationManager.getIntProperty("db.maxwait");

        if (ConfigurationManager.getProperty("db.maxwait") == null) {
            maxWait = 5000;
        }

        int maxIdle = ConfigurationManager.getIntProperty("db.maxidle");

        if (ConfigurationManager.getProperty("db.maxidle") == null) {
            maxIdle = -1;
        }

        boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true);

        // Create object pool
        ObjectPool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory
                // - set below
                maxConnections, // max connections
                GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't
                // block
                // more than 5
                // seconds
                maxIdle, // max idle connections (unlimited)
                true, // validate when we borrow connections from pool
                false // don't bother validation returned connections
        );

        // ConnectionFactory the pool will use to create connections.
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"),
                ConfigurationManager.getProperty("db.password"));

        //
        // Now we'll create the PoolableConnectionFactory, which wraps
        // the "real" Connections created by the ConnectionFactory with
        // the classes that implement the pooling functionality.
        //
        String validationQuery = "SELECT 1";

        // Oracle has a slightly different validation query
        if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) {
            validationQuery = "SELECT 1 FROM DUAL";
        }

        GenericKeyedObjectPoolFactory statementFactory = null;
        if (useStatementPool) {
            // The statement Pool is used to pool prepared statements.
            GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config();
            // Just grow the pool size when needed.
            //
            // This means we will never block when attempting to
            // create a query. The problem is unclosed statements,
            // they can never be reused. So if we place a maximum
            // cap on them, then we might reach a condition where
            // a page can only be viewed X number of times. The
            // downside of GROW_WHEN_EXHAUSTED is that this may
            // allow a memory leak to exist. Both options are bad,
            // but I'd prefer a memory leak over a failure.
            //
            // FIXME: Perhaps this decision should be derived from config parameters?
            statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;

            statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig);
        }

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, statementFactory, validationQuery, // validation query
                false, // read only is not default for now
                false); // Autocommit defaults to none

        //
        // Finally, we create the PoolingDataSource itself...
        //
        PoolingDataSource poolingDataSource = new PoolingDataSource();

        //
        // ...and register our pool with it.
        //
        poolingDataSource.setPool(connectionPool);

        dataSource = poolingDataSource;
        return poolingDataSource;
    } catch (Exception e) {
        // Need to be able to catch other exceptions. Pretend they are
        // SQLExceptions, but do log
        log.warn("Exception initializing DB pool", e);
        throw new SQLException(e.toString(), e);
    }
}

From source file:org.dspace.storage.rdbms.MockDatabaseManager.java

/**
 * Initialize the DatabaseManager.//from   w ww . j  a  v a  2s  . c  o  m
 */
@Mock
private static synchronized void initialize() throws SQLException {
    if (initialized) {
        return;
    }

    try {
        // Register basic JDBC driver
        Class.forName(ConfigurationManager.getProperty("db.driver"));

        // Register the DBCP driver
        Class.forName("org.apache.commons.dbcp.PoolingDriver");

        // Read pool configuration parameter or use defaults
        // Note we check to see if property is null; getIntProperty returns
        // '0' if the property is not set OR if it is actually set to zero.
        // But 0 is a valid option...
        int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections");

        if (ConfigurationManager.getProperty("db.maxconnections") == null) {
            maxConnections = 30;
        }

        int maxWait = ConfigurationManager.getIntProperty("db.maxwait");

        if (ConfigurationManager.getProperty("db.maxwait") == null) {
            maxWait = 5000;
        }

        int maxIdle = ConfigurationManager.getIntProperty("db.maxidle");

        if (ConfigurationManager.getProperty("db.maxidle") == null) {
            maxIdle = -1;
        }

        boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true);

        // Create object pool
        connectionPool = new GenericObjectPool(null, // PoolableObjectFactory
                // - set below
                maxConnections, // max connections
                GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't
                // block
                // more than 5
                // seconds
                maxIdle, // max idle connections (unlimited)
                true, // validate when we borrow connections from pool
                false // don't bother validation returned connections
        );

        // ConnectionFactory the pool will use to create connections.
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"),
                ConfigurationManager.getProperty("db.password"));

        //
        // Now we'll create the PoolableConnectionFactory, which wraps
        // the "real" Connections created by the ConnectionFactory with
        // the classes that implement the pooling functionality.
        //
        String validationQuery = "SELECT 1";

        // Oracle has a slightly different validation query
        if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) {
            validationQuery = "SELECT 1 FROM DUAL";
        }

        GenericKeyedObjectPoolFactory statementFactory = null;
        if (useStatementPool) {
            // The statement Pool is used to pool prepared statements.
            GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config();
            // Just grow the pool size when needed.
            //
            // This means we will never block when attempting to
            // create a query. The problem is unclosed statements,
            // they can never be reused. So if we place a maximum
            // cap on them, then we might reach a condition where
            // a page can only be viewed X number of times. The
            // downside of GROW_WHEN_EXHAUSTED is that this may
            // allow a memory leak to exist. Both options are bad,
            // but I'd prefer a memory leak over a failure.
            //
            // Perhaps this decision should be derived from config parameters?
            statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;

            statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig);
        }

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, statementFactory, validationQuery, // validation query
                false, // read only is not default for now
                false); // Autocommit defaults to none

        // Obtain a poolName from the config, default is "dspacepool"
        if (ConfigurationManager.getProperty("db.poolname") != null) {
            poolName = ConfigurationManager.getProperty("db.poolname");
        }

        //
        // Finally, we get the PoolingDriver itself...
        //
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");

        //
        // ...and register our pool with it.
        //
        if (driver != null)
            driver.registerPool(poolName, connectionPool);

        //preload the contents of the database
        String s = new String();
        StringBuilder sb = new StringBuilder();

        String schemaPath = System.getProperty("db.schema.path");
        if (null == schemaPath)
            throw new IllegalArgumentException("System property db.schema.path must be defined");

        FileReader fr = new FileReader(new File(schemaPath));
        BufferedReader br = new BufferedReader(fr);

        while ((s = br.readLine()) != null) {
            //we skip white lines and comments
            if (!"".equals(s.trim()) && !s.trim().startsWith("--")) {
                sb.append(s);
            }
        }
        br.close();

        //we use ";" as a delimiter for each request. This assumes no triggers
        //nor other calls besides CREATE TABLE, CREATE SEQUENCE and INSERT
        //exist in the file
        String[] stmts = sb.toString().split(";");

        //stablish the connection using the pool
        Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + poolName);
        Statement st = con.createStatement();

        for (int i = 0; i < stmts.length; i++) {
            // we ensure that there is no spaces before or after the request string
            // in order to not execute empty statements
            if (!stmts[i].trim().equals("")) {
                st.executeUpdate(stmts[i]);
                log.debug("Loading into database: " + stmts[i]);
            }
        }

        //commit changes
        con.commit();
        con.close();

        // Old SimplePool init
        //DriverManager.registerDriver(new SimplePool());
        initialized = true;
    } catch (SQLException se) {
        // Simply throw up SQLExceptions
        throw se;
    } catch (Exception e) {
        // Need to be able to catch other exceptions. Pretend they are
        // SQLExceptions, but do log
        log.warn("Exception initializing DB pool", e);
        throw new SQLException(e.toString());
    }
}

From source file:org.sakaiproject.kernel.ldap.GenericObjectPoolTest.java

@Before
public void setUp() throws Exception {

    factory = createMock(PoolableObjectFactory.class);

    pool = new GenericObjectPool(factory, 1, // maxActive
            GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // whenExhaustedAction
            60000, // maxWait (millis)
            1, // maxIdle
            true, // testOnBorrow
            false // testOnReturn
    );//www.j av  a  2s  . c  o m
}

From source file:org.sakaiproject.kernel.ldap.PoolingLdapConnectionManager.java

/**
 * {@inheritDoc}/*www  . jav a 2s  . c  o m*/
 */
@Override
public void init() throws LdapException {
    super.init();

    if (pool != null) {
        return;
    }

    if (factory == null) {
        factory = new PooledLDAPConnectionFactory();
    }
    factory.setConnectionManager(this);

    pool = new GenericObjectPool(factory, getConfig().getPoolMaxConns(), // maxActive
            GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // whenExhaustedAction
            POOL_MAX_WAIT, // maxWait (millis)
            getConfig().getPoolMaxConns(), // maxIdle
            true, // testOnBorrow
            false // testOnReturn
    );
}

From source file:org.sakaiproject.nakamura.ldap.PoolingLdapConnectionManager.java

/**
 * Creates a new {@link GenericObjectPool}. Provided to be overridden when testing.
 *
 * @param factory// w w w  .j a v a2 s  . c  o  m
 * @param maxConns
 * @param whenExhausted
 * @param maxWait
 * @param maxIdle
 * @param testOnBorrow
 * @param testOnReturn
 * @return
 */
ObjectPool newConnectionPool(PoolableObjectFactory factory, int maxConns, byte whenExhausted, int maxWait,
        int maxIdle, boolean testOnBorrow, boolean testOnReturn) {
    GenericObjectPool gpool = new GenericObjectPool(factory, maxConns, // maxActive
            whenExhausted, // whenExhaustedAction
            maxWait, // maxWait (millis)
            maxIdle, // maxIdle
            testOnBorrow, // testOnBorrow
            testOnReturn // testOnReturn
    );
    return gpool;
}