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

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

Introduction

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

Prototype

public synchronized int getNumActive() 

Source Link

Document

Return the number of instances currently borrowed from this pool.

Usage

From source file:DBCPDemo.java

public static void main(String args[]) throws Exception {

    // create a generic pool
    GenericObjectPool pool = new GenericObjectPool(null);

    // use the connection factory which will wraped by
    // the PoolableConnectionFactory
    DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory(
            "jdbc:jtds:sqlserver://myserver:1433/tandem", "user", "pass");

    PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, pool, null, "SELECT * FROM mysql.db",
            false, true);// www.  j a v a 2s .  co  m

    // register our pool and give it a name
    new PoolingDriver().registerPool("myPool", pool);

    // get a connection and test it
    Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:myPool");

    // now we can use this pool the way we want.
    System.err.println("Are we connected? " + !conn.isClosed());

    System.err.println("Idle Connections: " + pool.getNumIdle() + ", out of " + pool.getNumActive());

}

From source file:ConnectionPoolBasics.java

public static void main(String args[]) throws Exception {

    GenericObjectPool gPool = new GenericObjectPool();

    /*Class.forName("com.mysql.jdbc.Driver");
            /*from   w  w  w  .  ja v a2  s. c o  m*/
    DriverManagerConnectionFactory cf =
       new DriverManagerConnectionFactory(
    "jdbc:mysql://localhost/commons", "root", "");*/

    Properties props = new Properties();
    props.setProperty("Username", "root");
    props.setProperty("Password", "");
    ConnectionFactory cf = new DriverConnectionFactory(new com.mysql.jdbc.Driver(),
            "jdbc:mysql://localhost/commons", props);

    KeyedObjectPoolFactory kopf = new GenericKeyedObjectPoolFactory(null, 8);

    PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, kopf, null, false, true);

    for (int i = 0; i < 5; i++) {
        gPool.addObject();
    }

    // PoolingDataSource pds = new PoolingDataSource(gPool);
    PoolingDriver pd = new PoolingDriver();
    pd.registerPool("example", gPool);

    for (int i = 0; i < 5; i++) {
        gPool.addObject();
    }

    Connection conn = java.sql.DriverManager.getConnection("jdbc:apache:commons:dbcp:example");

    System.err.println("Connection: " + conn); //": Delegate: " + ((org.apache.commons.dbcp.PoolingConnection)conn).getDelegate());

    // do some work with the connection
    PreparedStatement ps = conn.prepareStatement("Select * from customer where id = ?");

    System.err.println("Active: " + gPool.getNumActive() + ", Idle: " + gPool.getNumIdle());

    conn.close();

    System.err.println("Active: " + gPool.getNumActive() + ", Idle: " + gPool.getNumIdle());

}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testExceptionOnDestroyDuringReturn() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    factory.setThrowExceptionOnDestroy(true);
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setTestOnReturn(true);//  w  ww .  j a  v a 2s.co  m
    Object obj1 = pool.borrowObject();
    pool.borrowObject();
    factory.setValid(false); // Make validation fail
    pool.returnObject(obj1);
    assertEquals(1, pool.getNumActive());
    assertEquals(0, pool.getNumIdle());
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testExceptionOnDestroyDuringBorrow() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    factory.setThrowExceptionOnDestroy(true);
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setTestOnBorrow(true);/* www .j  a v a  2 s .  c o  m*/
    pool.borrowObject();
    factory.setValid(false); // Make validation fail on next borrow attempt
    try {
        pool.borrowObject();
        fail("Expecting NoSuchElementException");
    } catch (NoSuchElementException ex) {
        // expected
    }
    assertEquals(1, pool.getNumActive());
    assertEquals(0, pool.getNumIdle());
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testExceptionOnActivateDuringBorrow() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    Object obj1 = pool.borrowObject();
    Object obj2 = pool.borrowObject();
    pool.returnObject(obj1);/*from w w w.ja  va  2 s.  c o  m*/
    pool.returnObject(obj2);
    factory.setThrowExceptionOnActivate(true);
    factory.setEvenValid(false);
    // Activation will now throw every other time
    // First attempt throws, but loop continues and second succeeds
    Object obj = pool.borrowObject();
    assertEquals(1, pool.getNumActive());
    assertEquals(0, pool.getNumIdle());

    pool.returnObject(obj);
    factory.setValid(false);
    // Validation will now fail on activation when borrowObject returns
    // an idle instance, and then when attempting to create a new instance
    try {
        obj1 = pool.borrowObject();
        fail("Expecting NoSuchElementException");
    } catch (NoSuchElementException ex) {
        // expected
    }
    assertEquals(0, pool.getNumActive());
    assertEquals(0, pool.getNumIdle());
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

private void checkEvictorVisiting(boolean lifo) throws Exception {
    VisitTrackerFactory factory = new VisitTrackerFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setNumTestsPerEvictionRun(2);//from w  w w.j ava 2 s .  co m
    pool.setMinEvictableIdleTimeMillis(-1);
    pool.setTestWhileIdle(true);
    pool.setLifo(lifo);
    pool.setTestOnReturn(false);
    pool.setTestOnBorrow(false);
    for (int i = 0; i < 8; i++) {
        pool.addObject();
    }
    pool.evict(); // Visit oldest 2 - 0 and 1
    Object obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    // borrow, return, borrow, return
    // FIFO will move 0 and 1 to end
    // LIFO, 7 out, then in, then out, then in
    pool.evict(); // Should visit 2 and 3 in either case
    for (int i = 0; i < 8; i++) {
        VisitTracker tracker = (VisitTracker) pool.borrowObject();
        if (tracker.getId() >= 4) {
            assertEquals("Unexpected instance visited " + tracker.getId(), 0, tracker.getValidateCount());
        } else {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 1,
                    tracker.getValidateCount());
        }
    }

    factory = new VisitTrackerFactory();
    pool = new GenericObjectPool(factory);
    pool.setNumTestsPerEvictionRun(3);
    pool.setMinEvictableIdleTimeMillis(-1);
    pool.setTestWhileIdle(true);
    pool.setLifo(lifo);
    pool.setTestOnReturn(false);
    pool.setTestOnBorrow(false);
    for (int i = 0; i < 8; i++) {
        pool.addObject();
    }
    pool.evict(); // 0, 1, 2
    pool.evict(); // 3, 4, 5
    obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    // borrow, return, borrow, return
    // FIFO 3,4,5,6,7,0,1,2
    // LIFO 7,6,5,4,3,2,1,0
    // In either case, pointer should be at 6
    pool.evict();
    // Should hit 6,7,0 - 0 for second time
    for (int i = 0; i < 8; i++) {
        VisitTracker tracker = (VisitTracker) pool.borrowObject();
        if (tracker.getId() != 0) {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 1,
                    tracker.getValidateCount());
        } else {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 2,
                    tracker.getValidateCount());
        }
    }
    // Randomly generate a pools with random numTests
    // and make sure evictor cycles through elements appropriately
    int[] smallPrimes = { 2, 3, 5, 7 };
    Random random = new Random();
    random.setSeed(System.currentTimeMillis());
    for (int i = 0; i < 4; i++) {
        pool.setNumTestsPerEvictionRun(smallPrimes[i]);
        for (int j = 0; j < 5; j++) {
            pool = new GenericObjectPool(factory);
            pool.setNumTestsPerEvictionRun(3);
            pool.setMinEvictableIdleTimeMillis(-1);
            pool.setTestWhileIdle(true);
            pool.setLifo(lifo);
            pool.setTestOnReturn(false);
            pool.setTestOnBorrow(false);
            pool.setMaxIdle(-1);
            int instanceCount = 10 + random.nextInt(20);
            pool.setMaxActive(instanceCount);
            for (int k = 0; k < instanceCount; k++) {
                pool.addObject();
            }

            // Execute a random number of evictor runs
            int runs = 10 + random.nextInt(50);
            for (int k = 0; k < runs; k++) {
                pool.evict();
            }

            // Number of times evictor should have cycled through the pool
            int cycleCount = (runs * pool.getNumTestsPerEvictionRun()) / instanceCount;

            // Look at elements and make sure they are visited cycleCount
            // or cycleCount + 1 times
            VisitTracker tracker = null;
            int visitCount = 0;
            for (int k = 0; k < instanceCount; k++) {
                tracker = (VisitTracker) pool.borrowObject();
                assertTrue(pool.getNumActive() <= pool.getMaxActive());
                visitCount = tracker.getValidateCount();
                assertTrue(visitCount >= cycleCount && visitCount <= cycleCount + 1);
            }
        }
    }
}

From source file:org.cytobank.fcs_files.events.MemoryEvents.java

/**
 * Start the tracking monitor to list out opened events
 *//* ww w  .  java2s. co m*/
protected static void startMonitor() {
    if (cleanupThread != null)
        return;

    cleanupThread = new Thread("MemoryEventsArray Cleanup") {
        public void run() {
            logger.info(this.getName() + " Started");

            int lastNumberOfReferencedMemoryEventsArrays = -1;
            while (true) {
                try {
                    int numberOfReferencedMemoryEventsArrays = 0;
                    int numberOfCleanedUpMemoryEventsArrays = 0;

                    ////////////////////// Release no longer used memory referencedMemoryEventsArrays

                    MemoryEventsArray[] iHateThatConcurrentModificationExceptionsExist = new MemoryEventsArray[referencedMemoryEventsArrays
                            .size()];
                    iHateThatConcurrentModificationExceptionsExist = referencedMemoryEventsArrays
                            .toArray(iHateThatConcurrentModificationExceptionsExist);
                    for (MemoryEventsArray referencedMemoryEventsArray : iHateThatConcurrentModificationExceptionsExist) {

                        // Calling isReferenced returns the events array to their owning pools
                        if (!referencedMemoryEventsArray.releaseIfNotReferenced()) {
                            referencedMemoryEventsArrays.remove(referencedMemoryEventsArray);
                            numberOfCleanedUpMemoryEventsArrays++;
                        } else {
                            numberOfReferencedMemoryEventsArrays++;
                        }
                    }

                    if ((numberOfReferencedMemoryEventsArrays > 0
                            && numberOfReferencedMemoryEventsArrays != lastNumberOfReferencedMemoryEventsArrays)
                            || numberOfCleanedUpMemoryEventsArrays > 0) {
                        logger.info("::::: Number of active MemoryEventsArray: "
                                + numberOfReferencedMemoryEventsArrays + " Cleaned up: "
                                + numberOfCleanedUpMemoryEventsArrays + " :::::");
                    }

                    lastNumberOfReferencedMemoryEventsArrays = numberOfReferencedMemoryEventsArrays;

                    ////////////////////// Print pool status

                    for (String poolName : poolsByName.keySet()) {
                        GenericObjectPool pool = poolsByName.get(poolName);
                        int numberOfIdleEvents = pool.getNumIdle();
                        int numberOfActiveEvents = pool.getNumActive() - numberOfIdleEvents;
                        int numberOfMaxEvents = pool.getMaxActive();

                        if (numberOfActiveEvents > 0)
                            logger.info("::::: " + poolName + " Number of active memory event arrays: "
                                    + numberOfActiveEvents + "/" + numberOfMaxEvents + " Idle: "
                                    + numberOfIdleEvents + " :::::");
                    }
                } catch (Throwable t) {
                    logger.log(Level.INFO, "Problem in MemoryEventsArray Cleanup Thread loop", t);
                }

                try {
                    Thread.sleep(CLEANUP_INTERVAL);
                } catch (Throwable t) {
                    logger.log(Level.INFO, this.getName() + " exiting. " + t.toString());
                    break;
                }
            }
        }
    };

    cleanupThread.setDaemon(true);
    cleanupThread.start();
}

From source file:org.mule.transport.sftp.SftpConnector.java

protected synchronized ObjectPool getClientPool(ImmutableEndpoint endpoint) {
    GenericObjectPool pool = pools.get(endpoint.getEndpointURI());

    if (pool == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Pool is null - creating one for endpoint " + endpoint.getEndpointURI()
                    + " with max size " + getMaxConnectionPoolSize());
        }/*from   w ww .j a v  a 2 s  . c o m*/
        pool = new GenericObjectPool(new SftpConnectionFactory(endpoint), getMaxConnectionPoolSize());
        pool.setTestOnBorrow(isValidateConnections());
        pools.put(endpoint.getEndpointURI(), pool);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Using existing pool for endpoint " + endpoint.getEndpointURI() + ". Active: "
                    + pool.getNumActive() + ", Idle:" + pool.getNumIdle());
        }
    }

    return pool;
}

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 v a 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  v a2s  .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);
    }
}