Example usage for org.apache.commons.pool.impl GenericKeyedObjectPool WHEN_EXHAUSTED_GROW

List of usage examples for org.apache.commons.pool.impl GenericKeyedObjectPool WHEN_EXHAUSTED_GROW

Introduction

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

Prototype

byte WHEN_EXHAUSTED_GROW

To view the source code for org.apache.commons.pool.impl GenericKeyedObjectPool WHEN_EXHAUSTED_GROW.

Click Source Link

Document

A "when exhausted action" type indicating that when the pool is exhausted (i.e., the maximum number of active objects has been reached), the #borrowObject method should simply create a new object anyway.

Usage

From source file:net.ontopia.persistence.proxy.DBCPConnectionFactory.java

protected void initPool() {
    // Set up connection pool
    pool = new GenericObjectPool(null);

    // Read/Write by default
    boolean readonly = defaultReadOnly;
    // Auto-commit disabled by default
    boolean autocommit = readonly;
    log.debug("Creating new DBCP connection factory, readonly=" + readonly + ", autocommit=" + autocommit);

    // Set minimum pool size (default: 20)
    String _minsize = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.MinimumSize", false);
    int minsize = (_minsize == null ? 20 : Integer.parseInt(_minsize));
    log.debug("Setting ConnectionPool.MinimumSize '" + minsize + "'");
    pool.setMaxIdle(minsize); // 0 = no limit

    // Set maximum pool size (default: Integer.MAX_VALUE)
    String _maxsize = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.MaximumSize", false);
    int maxsize = (_maxsize == null ? 0 : Integer.parseInt(_maxsize));
    log.debug("Setting ConnectionPool.MaximumSize '" + maxsize + "'");
    pool.setMaxActive(maxsize); // 0 = no limit

    // Set user timeout (default: never)
    String _utimeout = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.UserTimeout", false);
    int utimeout = (_utimeout == null ? -1 : Integer.parseInt(_utimeout));
    pool.setMaxWait(utimeout); // -1 = never

    // Set soft maximum - emergency objects (default: true)
    boolean softmax = PropertyUtils.isTrue(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.SoftMaximum", true);
    log.debug("Setting ConnectionPool.SoftMaximum '" + softmax + "'");
    if (softmax)//from   w  w  w .  j  a v  a2 s .  co  m
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    else
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);

    // allow the user to overwrite exhausted options
    // warning: when set to fail, make sure Maximum and Minimum are set correctly
    // warning: when set to block, make sure a propper usertimeout is set, or pool will block
    //          forever
    String _whenExhaustedAction = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.WhenExhaustedAction", false);
    if (EXHAUSED_BLOCK.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK);
    if (EXHAUSED_GROW.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
    if (EXHAUSED_FAIL.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);

    if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK)
        log.debug("Pool is set to block on exhaused");
    if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW)
        log.debug("Pool is set to grow on exhaused");
    if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL)
        log.debug("Pool is set to fail on exhaused");

    // Statement pool
    GenericKeyedObjectPoolFactory stmpool = null;
    if (PropertyUtils.isTrue(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.PoolStatements",
            true)) {
        log.debug("Using prepared statement pool: Yes");
        stmpool = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key)
                GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait
                1, // maxIdle (per key) 
                GenericKeyedObjectPool.DEFAULT_MAX_TOTAL);
    } else {
        log.debug("Using prepared statement pool: No");
    }

    // Test on borrow
    pool.setTestOnBorrow(true);

    // Get validation query
    String vquery = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.ValidationQuery", false);
    if (vquery == null)
        vquery = "select seq_count from TM_ADMIN_SEQUENCE where seq_name = '<GLOBAL>'";

    try {
        // Make sure driver is registered
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Class.forName(getDriver(), true, classLoader);
        // Create connection factory
        ConnectionFactory cfactory;
        if (getUserName() == null || getPassword() == null) {
            Properties props = new Properties();
            props.putAll(properties);
            cfactory = new DriverManagerConnectionFactory(getConnectionString(), props);
        } else {
            cfactory = new DriverManagerConnectionFactory(getConnectionString(), getUserName(), getPassword());
        }

        // Create data source
        this.pcfactory = new TraceablePoolableConnectionFactory(cfactory, pool, stmpool, vquery, readonly,
                autocommit);

        // Set default transaction isolation level
        pcfactory.setDefaultTransactionIsolation(defaultTransactionIsolation);

        this.datasource = new PoolingDataSource(pool);
    } catch (Exception e) {
        throw new OntopiaRuntimeException("Problems occurred when setting up DBCP connection pool.", e);
    }
}

From source file:com.servoy.extensions.plugins.rest_ws.RestWSPlugin.java

synchronized KeyedObjectPool getClientPool() {
    if (clientPool == null) {
        byte exchaustedAction;
        int poolSize;
        if (ApplicationServerRegistry.get().isDeveloperStartup()) {
            // in developer multiple clients do not work well with debugger
            poolSize = 1;//from w w  w .j a va2 s  .co m
            exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else {
            try {
                poolSize = Integer.parseInt(application.getSettings()
                        .getProperty(CLIENT_POOL_SIZE_PROPERTY, "" + CLIENT_POOL_SIZE_DEFAULT).trim());
            } catch (NumberFormatException nfe) {
                poolSize = CLIENT_POOL_SIZE_DEFAULT;
            }
            String exchaustedActionCode = application.getSettings()
                    .getProperty(CLIENT_POOL_EXCHAUSTED_ACTION_PROPERTY);
            if (exchaustedActionCode != null)
                exchaustedActionCode = exchaustedActionCode.trim();
            if (ACTION_FAIL.equalsIgnoreCase(exchaustedActionCode)) {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_FAIL);
            } else if (ACTION_GROW.equalsIgnoreCase(exchaustedActionCode)) {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_GROW);
            } else {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_BLOCK);
            }
        }
        if (log.isDebugEnabled())
            log.debug("Creating client pool, maxSize=" + poolSize);
        clientPool = new GenericKeyedObjectPool(new BaseKeyedPoolableObjectFactory() {
            @Override
            public Object makeObject(Object key) throws Exception {
                if (log.isDebugEnabled())
                    log.debug("creating new session client for solution '" + key + '\'');
                String solutionName = (String) key;
                String[] solOpenArgs = SOLUTION_OPEN_METHOD_ARGS;

                String[] arr = solutionName.split(":");
                if (arr.length == 2) {
                    solutionName = arr[0];
                    solOpenArgs = Utils.arrayJoin(SOLUTION_OPEN_METHOD_ARGS, new String[] { "nodebug" });
                }
                return HeadlessClientFactory.createHeadlessClient(solutionName, solOpenArgs);
            }

            @Override
            public boolean validateObject(Object key, Object obj) {
                IHeadlessClient client = ((IHeadlessClient) obj);
                if (client.getPluginAccess().isInDeveloper()) {
                    String solutionName = (String) key;
                    if (solutionName.contains(":"))
                        solutionName = solutionName.split(":")[0];

                    if (!solutionName.equals(((IHeadlessClient) obj).getPluginAccess().getSolutionName())) {
                        try {
                            client.closeSolution(true);
                            client.loadSolution(solutionName);
                        } catch (Exception ex) {
                            return false;
                        }
                    }
                }
                boolean valid = client.isValid();
                if (log.isDebugEnabled())
                    log.debug("Validated session client for solution '" + key + "', valid = " + valid);
                return valid;
            }

            @Override
            public void destroyObject(Object key, Object obj) throws Exception {
                if (log.isDebugEnabled())
                    log.debug("Destroying session client for solution '" + key + "'");
                IHeadlessClient client = ((IHeadlessClient) obj);
                try {
                    client.shutDown(true);
                } catch (Exception e) {
                    Debug.error(e);
                }
            }
        }, poolSize);
        clientPool.setTestOnBorrow(true);
        clientPool.setWhenExhaustedAction(exchaustedAction);
        clientPool.setMaxIdle(poolSize); // destroy objects when pool has grown
    }
    return clientPool;
}

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

public void testSettersAndGetters() throws Exception {
    GenericKeyedObjectPool pool = new GenericKeyedObjectPool();
    {//w w  w  .j a  v  a 2s. c  o m
        pool.setFactory(new SimpleFactory());
    }
    {
        pool.setMaxActive(123);
        assertEquals(123, pool.getMaxActive());
    }
    {
        pool.setMaxIdle(12);
        assertEquals(12, pool.getMaxIdle());
    }
    {
        pool.setMaxWait(1234L);
        assertEquals(1234L, pool.getMaxWait());
    }
    {
        pool.setMinEvictableIdleTimeMillis(12345L);
        assertEquals(12345L, pool.getMinEvictableIdleTimeMillis());
    }
    {
        pool.setNumTestsPerEvictionRun(11);
        assertEquals(11, pool.getNumTestsPerEvictionRun());
    }
    {
        pool.setTestOnBorrow(true);
        assertTrue(pool.getTestOnBorrow());
        pool.setTestOnBorrow(false);
        assertTrue(!pool.getTestOnBorrow());
    }
    {
        pool.setTestOnReturn(true);
        assertTrue(pool.getTestOnReturn());
        pool.setTestOnReturn(false);
        assertTrue(!pool.getTestOnReturn());
    }
    {
        pool.setTestWhileIdle(true);
        assertTrue(pool.getTestWhileIdle());
        pool.setTestWhileIdle(false);
        assertTrue(!pool.getTestWhileIdle());
    }
    {
        pool.setTimeBetweenEvictionRunsMillis(11235L);
        assertEquals(11235L, pool.getTimeBetweenEvictionRunsMillis());
    }
    {
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_BLOCK, pool.getWhenExhaustedAction());
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_FAIL, pool.getWhenExhaustedAction());
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_GROW, pool.getWhenExhaustedAction());
    }
}

From source file:org.jahia.services.usermanager.ldap.JahiaLDAPConfig.java

/**
 * defines or update the context of the provider
 * @param context the Spring application context object
 * @param dictionary configuration parameters
 *//*  www  .java 2 s  .  c  o  m*/
public void setContext(ApplicationContext context, Dictionary<String, ?> dictionary) {
    Properties userLdapProperties = new Properties();
    Properties groupLdapProperties = new Properties();
    UserConfig userConfig = new UserConfig();
    GroupConfig groupConfig = new GroupConfig();
    Enumeration<String> keys = dictionary.keys();

    while (keys.hasMoreElements()) {
        String key = keys.nextElement();
        if (Constants.SERVICE_PID.equals(key) || ConfigurationAdmin.SERVICE_FACTORYPID.equals(key)
                || "felix.fileinstall.filename".equals(key)) {
            continue;
        }
        Object value = dictionary.get(key);
        if (key.startsWith("user.")) {
            buildConfig(userLdapProperties, userConfig, key, value, true);
        } else if (key.startsWith("group.")) {
            buildConfig(groupLdapProperties, groupConfig, key, value, false);
        } else {
            userLdapProperties.put(transformPropKeyToBeanAttr(key), value);
            groupLdapProperties.put(transformPropKeyToBeanAttr(key), value);
        }
    }
    try {
        // populate config beans
        BeanUtils.populate(userConfig, userLdapProperties);
        BeanUtils.populate(groupConfig, groupLdapProperties);

        // handle defaults values
        userConfig.handleDefaults();
        groupConfig.handleDefaults();

        // instantiate ldap context
        if (userConfig.isMinimalSettingsOk()) {
            LdapContextSource lcs = new LdapContextSource();
            lcs.setUrl(userConfig.getUrl());
            if (StringUtils.isNotEmpty(userConfig.getPublicBindDn())) {
                lcs.setUserDn(userConfig.getPublicBindDn());
            }
            if (StringUtils.isNotEmpty(userConfig.getPublicBindPassword())) {
                lcs.setPassword(userConfig.getPublicBindPassword());
            }

            Map<String, Object> publicEnv = new Hashtable<String, Object>(1);
            if (POOL_LDAP.equalsIgnoreCase(userConfig.getLdapConnectPool())) {
                lcs.setPooled(true);
                publicEnv.put("com.sun.jndi.ldap.connect.pool.authentication", "none simple");
                if (userConfig.getLdapConnectPoolTimeout() != null
                        && Long.valueOf(userConfig.getLdapConnectTimeout()) > 0) {
                    publicEnv.put("com.sun.jndi.ldap.connect.pool.timeout",
                            userConfig.getLdapConnectPoolTimeout());
                }
                if (userConfig.getLdapConnectPoolDebug() != null) {
                    publicEnv.put("com.sun.jndi.ldap.connect.pool.debug", userConfig.getLdapConnectPoolDebug());
                }
                if (userConfig.getLdapConnectPoolInitSize() != null) {
                    publicEnv.put("com.sun.jndi.ldap.connect.pool.initsize",
                            userConfig.getLdapConnectPoolInitSize());
                }
                if (userConfig.getLdapConnectPoolMaxSize() != null) {
                    publicEnv.put("com.sun.jndi.ldap.connect.pool.maxsize",
                            userConfig.getLdapConnectPoolMaxSize());
                }
                if (userConfig.getLdapConnectPoolPrefSize() != null) {
                    publicEnv.put("com.sun.jndi.ldap.connect.pool.prefsize",
                            userConfig.getLdapConnectPoolPrefSize());
                }
            }
            if (userConfig.getLdapReadTimeout() != null) {
                publicEnv.put("com.sun.jndi.ldap.read.timeout", userConfig.getLdapReadTimeout());
            }
            if (userConfig.getLdapConnectTimeout() != null) {
                publicEnv.put("com.sun.jndi.ldap.connect.timeout", userConfig.getLdapConnectTimeout());
            }
            lcs.setBaseEnvironmentProperties(publicEnv);

            lcs.setReferral(groupConfig.getRefferal());
            lcs.setDirObjectFactory(DefaultDirObjectFactory.class);
            lcs.afterPropertiesSet();

            LdapTemplate ldap;

            if (POOL_APACHE_COMMONS.equalsIgnoreCase(userConfig.getLdapConnectPool())) {
                PoolingContextSource poolingContextSource = new PoolingContextSource();
                poolingContextSource.setContextSource(lcs);
                if (userConfig.getLdapConnectPoolMaxActive() != null) {
                    poolingContextSource.setMaxActive(userConfig.getLdapConnectPoolMaxActive());
                }
                if (userConfig.getLdapConnectPoolMaxIdle() != null) {
                    poolingContextSource.setMaxIdle(userConfig.getLdapConnectPoolMaxIdle());
                }
                if (userConfig.getLdapConnectPoolMaxTotal() != null) {
                    poolingContextSource.setMaxTotal(userConfig.getLdapConnectPoolMaxTotal());
                }
                if (userConfig.getLdapConnectPoolMaxWait() != null) {
                    poolingContextSource.setMaxWait(userConfig.getLdapConnectPoolMaxWait());
                }
                if (userConfig.getLdapConnectPoolMinEvictableIdleTimeMillis() != null) {
                    poolingContextSource.setMinEvictableIdleTimeMillis(
                            userConfig.getLdapConnectPoolMinEvictableIdleTimeMillis());
                }
                if (userConfig.getLdapConnectPoolMinIdle() != null) {
                    poolingContextSource.setMinIdle(userConfig.getLdapConnectPoolMinIdle());
                }
                if (userConfig.getLdapConnectPoolNumTestsPerEvictionRun() != null) {
                    poolingContextSource
                            .setNumTestsPerEvictionRun(userConfig.getLdapConnectPoolNumTestsPerEvictionRun());
                }
                if (userConfig.getLdapConnectPoolTestOnBorrow() != null) {
                    poolingContextSource.setTestOnBorrow(userConfig.getLdapConnectPoolTestOnBorrow());
                }
                if (userConfig.getLdapConnectPoolTestOnReturn() != null) {
                    poolingContextSource.setTestOnReturn(userConfig.getLdapConnectPoolTestOnReturn());
                }
                if (userConfig.getLdapConnectPoolTestWhileIdle() != null) {
                    poolingContextSource.setTestWhileIdle(userConfig.getLdapConnectPoolTestWhileIdle());
                }
                if (userConfig.getLdapConnectPoolTimeBetweenEvictionRunsMillis() != null) {
                    poolingContextSource.setTimeBetweenEvictionRunsMillis(
                            userConfig.getLdapConnectPoolTimeBetweenEvictionRunsMillis());
                }
                if (WHEN_EXHAUSTED_BLOCK.equalsIgnoreCase(userConfig.getLdapConnectPoolWhenExhaustedAction())) {
                    poolingContextSource.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK);
                } else if (WHEN_EXHAUSTED_FAIL
                        .equalsIgnoreCase(userConfig.getLdapConnectPoolWhenExhaustedAction())) {
                    poolingContextSource.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);
                } else if (WHEN_EXHAUSTED_GROW
                        .equalsIgnoreCase(userConfig.getLdapConnectPoolWhenExhaustedAction())) {
                    poolingContextSource.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
                }

                ldap = new LdapTemplate(poolingContextSource);
            } else {
                ldap = new LdapTemplate(lcs);
            }

            // AD workaround to ignore Exceptions
            ldap.setIgnorePartialResultException(true);
            ldap.setIgnoreNameNotFoundException(true);

            if (ldapUserGroupProvider == null) {
                ldapUserGroupProvider = (LDAPUserGroupProvider) context.getBean("ldapUserGroupProvider");
            }

            ldapUserGroupProvider.setKey(providerKey);
            ldapUserGroupProvider.setUserConfig(userConfig);
            ldapUserGroupProvider.setGroupConfig(groupConfig);
            if (StringUtils.isNotEmpty(userConfig.getUidSearchName())
                    && StringUtils.isNotEmpty(groupConfig.getSearchName())) {
                ldapUserGroupProvider
                        .setDistinctBase(!userConfig.getUidSearchName().startsWith(groupConfig.getSearchName())
                                && !groupConfig.getSearchName().startsWith(userConfig.getUidSearchName()));
            }
            ldapUserGroupProvider.setLdapTemplateWrapper(new LdapTemplateWrapper(ldap));
            ldapUserGroupProvider.setContextSource(lcs);

            ldapUserGroupProvider.unregister();
            ldapUserGroupProvider.register();
            if (groupConfig.isPreload()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<String> l = ldapUserGroupProvider.searchGroups(new Properties(), 0, -1);
                        for (String s : l) {
                            List<Member> m = ldapUserGroupProvider.getGroupMembers(s);
                        }
                    }
                }, "LDAP Preload").start();
            }
        } else {
            unregister();
        }
    } catch (IllegalAccessException e) {
        logger.error("Config LDAP invalid, pls read the documentation on LDAP configuration", e);
    } catch (InvocationTargetException e) {
        logger.error("Config LDAP invalid, pls read the documentation on LDAP configuration", e);
    }
}

From source file:org.kuali.rice.core.framework.persistence.jdbc.datasource.RiceXADataSource.java

protected KeyedObjectPoolFactory createStatementPoolFactory() {
    return new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key)
            GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW, 0, // maxWait
            1, // maxIdle (per key) 
            getPreparedStatementCacheSize());
}

From source file:org.mule.transport.DispatcherPoolTestCase.java

@Test
public void testDispatcherPoolGrowExhaustedAction() throws Exception {
    final TestConnector connector = createConnectorWithSingleObjectDispatcherPool(
            ThreadingProfile.WHEN_EXHAUSTED_WAIT);
    connector.setDispatcherPoolWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);

    assertEquals(1, connector.dispatchers.getMaxActive());

    final OutboundEndpoint endpoint = getTestOutboundEndpoint("test", "test://test");

    connector.dispatchers.borrowObject(endpoint);
    connector.dispatchers.borrowObject(endpoint);
    assertEquals(2, connector.dispatchers.getNumActive());

}

From source file:org.opencms.db.CmsDbPool.java

/**
 * Creates a JDBC DriverManager based DBCP connection pool.<p>
 * /*from w w  w  . j  av  a 2 s .c o  m*/
 * @param config the configuration (opencms.properties)
 * @param key the key of the database pool in the configuration
 * @return String the URL to access the created DBCP pool
 * @throws Exception if the pool could not be initialized
 */
public static PoolingDriver createDriverManagerConnectionPool(CmsParameterConfiguration config, String key)
        throws Exception {

    // read the values of the pool configuration specified by the given key
    String jdbcDriver = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_DRIVER);
    String jdbcUrl = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_URL);
    String jdbcUrlParams = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_URL_PARAMS);
    int maxActive = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_ACTIVE, 10);
    int maxWait = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_WAIT, 2000);
    int maxIdle = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_IDLE, 5);
    int minEvictableIdleTime = config
            .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MIN_EVICTABLE_IDLE_TIME, 1800000);
    int minIdle = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MIN_IDLE, 0);
    int numTestsPerEvictionRun = config
            .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_NUM_TESTS_PER_EVICTION_RUN, 3);
    int timeBetweenEvictionRuns = config
            .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TIME_BETWEEN_EVICTION_RUNS, 3600000);
    String testQuery = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_QUERY);
    String username = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_USERNAME);
    String password = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_PASSWORD);
    String poolUrl = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_POOL_URL);
    String whenExhaustedActionValue = config
            .get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_WHEN_EXHAUSTED_ACTION).trim();
    byte whenExhaustedAction = 0;
    boolean testOnBorrow = Boolean
            .valueOf(config.getString(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_ON_BORROW, "false").trim())
            .booleanValue();
    boolean testWhileIdle = Boolean
            .valueOf(
                    config.getString(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_WHILE_IDLE, "false").trim())
            .booleanValue();

    if ("block".equalsIgnoreCase(whenExhaustedActionValue)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
    } else if ("fail".equalsIgnoreCase(whenExhaustedActionValue)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
    } else if ("grow".equalsIgnoreCase(whenExhaustedActionValue)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
    } else {
        whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
    }

    if ("".equals(testQuery)) {
        testQuery = null;
    }

    if (username == null) {
        username = "";
    }

    if (password == null) {
        password = "";
    }

    // read the values of the statement pool configuration specified by the given key
    boolean poolingStmts = Boolean.valueOf(config
            .getString(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_POOLING, CmsStringUtil.TRUE).trim())
            .booleanValue();
    int maxActiveStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_ACTIVE, 25);
    int maxWaitStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_WAIT, 250);
    int maxIdleStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_IDLE, 15);
    String whenStmtsExhaustedActionValue = config
            .get(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_WHEN_EXHAUSTED_ACTION);
    byte whenStmtsExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW;
    if (whenStmtsExhaustedActionValue != null) {
        whenStmtsExhaustedActionValue = whenStmtsExhaustedActionValue.trim();
        whenStmtsExhaustedAction = ("block".equalsIgnoreCase(whenStmtsExhaustedActionValue))
                ? GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK
                : ("fail".equalsIgnoreCase(whenStmtsExhaustedActionValue))
                        ? GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL
                        : GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW;
    }

    int connectionAttempts = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_CONNECT_ATTEMTS, 10);
    int connetionsWait = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_CONNECT_WAITS, 5000);

    // create an instance of the JDBC driver
    Class.forName(jdbcDriver).newInstance();

    // initialize a keyed object pool to store connections
    GenericObjectPool connectionPool = new GenericObjectPool(null);

    /* Abandoned pool configuration:
     *  
     * In case the systems encounters "pool exhaustion" (runs out of connections),
     * comment the above line with "new GenericObjectPool(null)" and uncomment the 
     * 5 lines below. This will generate an "abandoned pool" configuration that logs 
     * abandoned connections to the System.out. Unfortunatly this code is deprecated,
     * so to avoid code warnings it's also disabled here. 
     * Tested with commons-pool v 1.2.
     */

    //        AbandonedConfig abandonedConfig = new AbandonedConfig();
    //        abandonedConfig.setLogAbandoned(true);
    //        abandonedConfig.setRemoveAbandoned(true);
    //        abandonedConfig.setRemoveAbandonedTimeout(5);
    //        GenericObjectPool connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    // initialize an object pool to store connections
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setWhenExhaustedAction(whenExhaustedAction);

    if (testQuery != null) {
        connectionPool.setTestOnBorrow(testOnBorrow);
        connectionPool.setTestWhileIdle(testWhileIdle);
        connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns);
        connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTime);
    }

    // initialize a connection factory to make the DriverManager taking connections from the pool
    if (jdbcUrlParams != null) {
        jdbcUrl += jdbcUrlParams;
    }

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

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementFactory = null;
    if (poolingStmts) {
        statementFactory = new GenericKeyedObjectPoolFactory(null, maxActiveStmts, whenStmtsExhaustedAction,
                maxWaitStmts, maxIdleStmts);
    }

    // initialize a factory to obtain pooled connections and prepared statements
    new PoolableConnectionFactory(connectionFactory, connectionPool, statementFactory, testQuery, false, true);

    // initialize a new pooling driver using the pool
    PoolingDriver driver = new PoolingDriver();
    driver.registerPool(poolUrl, connectionPool);

    Connection con = null;
    boolean connect = false;
    int connectionTests = 0;

    // try to connect once to the database to ensure it can be connected to at all
    // if the conection cannot be established, multiple attempts will be done to connect
    // just in cast the database was not fast enough to start before OpenCms was started

    do {
        try {
            // try to connect
            con = connectionFactory.createConnection();
            connect = true;
        } catch (Exception e) {
            // connection failed, increase attempts, sleept for some seconds and log a message
            connectionTests++;
            if (CmsLog.INIT.isInfoEnabled()) {
                CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_WAIT_FOR_DB_4, new Object[] {
                        poolUrl, jdbcUrl, new Integer(connectionTests), new Integer(connetionsWait) }));
            }
            Thread.sleep(connetionsWait);
        } finally {
            if (con != null) {
                con.close();
            }
        }
    } while (!connect && (connectionTests < connectionAttempts));

    if (CmsLog.INIT.isInfoEnabled()) {
        CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_JDBC_POOL_2, poolUrl, jdbcUrl));
    }
    return driver;
}

From source file:org.wso2.carbon.databridge.agent.client.ClientPool.java

public GenericKeyedObjectPool getClientPool(AbstractClientPoolFactory factory, int maxActive, int maxIdle,
        boolean testOnBorrow, long timeBetweenEvictionRunsMillis, long minEvictableIdleTimeMillis) {
    if (socketPool == null) {
        synchronized (this) {
            if (socketPool == null) {
                socketPool = new GenericKeyedObjectPool();
                socketPool.setFactory(factory);
                socketPool.setMaxActive(maxActive);
                socketPool.setTestOnBorrow(testOnBorrow);
                socketPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
                socketPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
                socketPool.setMaxIdle(maxIdle);
                socketPool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
            }//w ww .  j  a v  a 2 s. c o  m
        }
    }
    return socketPool;
}

From source file:org.wso2.carbon.databridge.agent.internal.client.ClientPool.java

public GenericKeyedObjectPool getClientPool(AbstractClientPoolFactory factory, int maxActive, int maxIdle,
        boolean testOnBorrow, long timeBetweenEvictionRunsMillis, long minEvictableIdleTimeMillis) {
    if (socketPool == null) {
        synchronized (ClientPool.class) {
            if (socketPool == null) {
                socketPool = new GenericKeyedObjectPoolImpl();
                socketPool.setFactory(factory);
                socketPool.setMaxActive(maxActive);
                socketPool.setTestOnBorrow(testOnBorrow);
                socketPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
                socketPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
                socketPool.setMaxIdle(maxIdle);
                socketPool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
            }/*from ww  w.j  a v  a 2 s .  co m*/
        }
    }
    return socketPool;
}

From source file:org.wso2.carbon.databridge.agent.thrift.internal.pool.client.general.ClientPool.java

public GenericKeyedObjectPool getClientPool(KeyedPoolableObjectFactory factory, int maxActive, int maxIdle,
        boolean testOnBorrow, long timeBetweenEvictionRunsMillis, long minEvictableIdleTimeMillis) {
    if (socketPool == null) {
        synchronized (ClientPool.class) {
            if (socketPool == null) {
                socketPool = new GenericKeyedObjectPoolImpl();
                socketPool.setFactory(factory);
                socketPool.setMaxActive(maxActive);
                socketPool.setTestOnBorrow(testOnBorrow);
                socketPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
                socketPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
                socketPool.setMaxIdle(maxIdle);
                socketPool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
            }/*from  ww  w  .ja  v  a 2 s . co  m*/
        }
    }
    return socketPool;
}