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

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

Introduction

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

Prototype

byte WHEN_EXHAUSTED_BLOCK

To view the source code for org.apache.commons.pool.impl GenericObjectPool WHEN_EXHAUSTED_BLOCK.

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 block until a new object is available, or the #getMaxWait maximum wait time has been reached.

Usage

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Initialize a jdbc connection pool/*from   ww w. j av a 2  s .  c o  m*/
 * 
 * @param type
 *            either rw or query pool
 * @param maxActive
 *            maximum number of connections in pool
 * @param configuration
 *            configuration properties used for creating database connections
 * @return connection pool
 * @throws AnzoException
 *             {@link ExceptionConstants#RDB.DRIVER_NAME} if there was a problem loading class for database driver
 */
private GenericObjectPool initializeConnectionFactory(boolean write, int maxActive) throws AnzoException {
    // Will use in jndi
    // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties));
    try {
        Class.forName(configuration.getDriverClassName());
    } catch (ClassNotFoundException e1) {
        throw new AnzoException(ExceptionConstants.RDB.DRIVER_NAME, e1, configuration.getDriverClassName());
    }
    Properties props = new Properties();
    props.put("user", configuration.getUser());
    props.put("password", configuration.getPassword());
    props.put("SetBigStringTryClob", "true");
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(), props);
    GenericObjectPool connectionPool = new GenericObjectPool();
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(Math.max(1, maxActive / 2));
    connectionPool.setMinIdle(0);
    connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 10);
    connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 10);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    connectionPool.setMaxWait(GenericKeyedObjectPool.DEFAULT_MAX_WAIT);
    connectionPool.setTestOnBorrow(true);
    GenericKeyedObjectPoolFactory statementPool = new GenericKeyedObjectPoolFactory(null, PS_CACHE_SIZE,
            GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK, GenericKeyedObjectPool.DEFAULT_MAX_WAIT, PS_CACHE_SIZE,
            PS_CACHE_SIZE, GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW,
            GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN,
            GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
            GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
            GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
            GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE);
    PoolableConnectionFactory pcf = new PoolableConnectionFactory(connectionFactory, connectionPool,
            statementPool, configuration.getValidationQuery(), false, true) {
        @Override
        public synchronized Object makeObject() throws Exception {
            Connection connection = (Connection) super.makeObject();
            initializeConnection(connection);
            return connection;
        }
    };

    if (configuration.getSupportsIsolation() && write)
        pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    else if (configuration.getSupportsIsolation() && !write)
        pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    return connectionPool;
}

From source file:org.openanzo.jdbc.container.RDBQuadStoreFactory.java

private PoolableConnectionFactory initializeConnectionFactory(boolean write, int maxActive,
        CoreDBConfiguration configuration) {
    // Will use in jndi
    // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties));
    try {//from   w  w w .  ja v  a  2  s.  c  om
        Class.forName(configuration.getDriverClassName());
    } catch (ClassNotFoundException e1) {
        throw new AnzoRuntimeException(ExceptionConstants.RDB.DRIVER_NAME, e1,
                configuration.getDriverClassName());
    }
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(),
            configuration.getUser(), configuration.getPassword());
    connectionPool = new GenericObjectPool();
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMinIdle(1);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    connectionPool.setMaxWait(30000);
    connectionPool.setMaxActive(maxActive);
    pcf = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
    if ((!write && configuration.getSupportsIsolation()))
        pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    return pcf;
}

From source file:org.openanzo.jdbc.container.RDBQuadStorePool.java

private void setupPool(GenericObjectPool pool, RDBQuadStoreFactory factory, int maxActive, int maxIdle,
        long blockWait) {
    pool.setFactory(factory);//from w  w w .j  a v a2 s.com
    pool.setMaxActive(maxActive);
    pool.setMaxIdle(maxIdle);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxWait(blockWait);
}

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

/**
 * Creates a JDBC DriverManager based DBCP connection pool.<p>
 * /* w  w  w . j a v  a 2  s  .  com*/
 * @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.openconcerto.sql.model.SQLDataSource.java

public synchronized void setBlockWhenExhausted(boolean block) {
    this.blockWhenExhausted = block;
    if (this.connectionPool != null) {
        this.connectionPool.setWhenExhaustedAction(
                block ? GenericObjectPool.WHEN_EXHAUSTED_BLOCK : GenericObjectPool.WHEN_EXHAUSTED_GROW);
    }/*w  ww .java  2  s  .c  o m*/
}

From source file:org.opendedup.sdfs.network.HashClientPool.java

public HashClientPool(HCServer server, String name, int size, byte id) throws IOException {
    super(new HashClientPoolFactory(server, id));
    this.setMaxIdle(size); // Maximum idle threads.
    this.setMaxActive(size); // Maximum active threads.
    this.setMinEvictableIdleTimeMillis(30000); // Evictor runs every 30
    // secs./*  w w  w .  java  2  s  .c om*/
    this.setTestOnBorrow(true); // Check if the thread is still valid.
    this.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    SDFSLogger.getLog().info("Server id=" + id + " name=" + name + " hn=" + server.getHostName() + " port="
            + server.getPort() + " size=" + size);
}

From source file:org.opensubsystems.core.persist.jdbc.connectionpool.dbcp.DBCPDatabaseConnectionFactoryImpl.java

/**
 * {@inheritDoc}//  www . ja  va  2  s .c om
 */
@Override
protected Object createConnectionPool(String strConnectionPoolName, Database database, String strDriverName,
        String strUrl, String strUser, String strPassword, int iTransactionIsolation) throws OSSException {
    // I am using here the PoolingDriver instead of PoolingDataSource because
    // in DBCP version 1.1 the PoolingDriver has clear way how to shutdown
    // the pool and PoolingDataSource doesn't.
    // This code was inspired by method setupDriver from 
    // ManualPoolingDriverExample.java in commons-dbcp package v 1.6
    ObjectPool connectionPool;
    ConnectionFactory connectionFactory;
    PoolableConnectionFactory poolableConnectionFactory;

    PooledDatabaseConnectionFactorySetupReader setupReader = new PooledDatabaseConnectionFactorySetupReader(
            strConnectionPoolName, database.getDatabaseTypeIdentifier());

    int iInitialPoolSize = setupReader
            .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_INITIAL_SIZE)
            .intValue();
    int iMinimalPoolSize = setupReader
            .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_MIN_SIZE).intValue();
    int iMaximalPoolSize = setupReader
            .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_MAX_SIZE).intValue();
    boolean bCanGrow = setupReader
            .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_CAN_GROW)
            .booleanValue();
    long lMaxWaitTimeForConnection = setupReader
            .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_WAIT_PERIOD).longValue();
    boolean bValidateOnBorrow = setupReader
            .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_BORROW)
            .booleanValue();
    boolean bValidateOnReturn = setupReader
            .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_RETURN)
            .booleanValue();
    boolean bValidateOnIdle = setupReader
            .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_IDLE)
            .booleanValue();
    long lTimeBetweenEvictionRunsMillis = setupReader
            .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_CHECK_PERIOD)
            .longValue();
    int iNumTestsPerEvictionRun = setupReader
            .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_CHECK_SIZE)
            .intValue();
    long lMinEvictableIdleTimeMillis = setupReader
            .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_PERIOD).longValue();
    int iPreparedStatementCacheSize = setupReader.getIntegerParameterValue(
            PooledDatabaseConnectionFactorySetupReader.DBPOOL_PREPSTATEMENT_CACHE_SIZE).intValue();

    // First, we'll need a ObjectPool that serves as the actual pool of 
    // connections. We'll use a GenericObjectPool instance, although
    // any ObjectPool implementation will suffice.
    connectionPool = new GenericObjectPool(null, // factory will be specified below
            iMaximalPoolSize,
            bCanGrow ? GenericObjectPool.WHEN_EXHAUSTED_GROW : GenericObjectPool.WHEN_EXHAUSTED_BLOCK,
            lMaxWaitTimeForConnection, iMaximalPoolSize, // max idle - if no connections are used
            // the pool should not fall under this size
            iMinimalPoolSize, // min idle - if connection count falls 
            // under this limit (e.g. closed connections)
            // new connections will be created
            bValidateOnBorrow, bValidateOnReturn, lTimeBetweenEvictionRunsMillis, iNumTestsPerEvictionRun,
            lMinEvictableIdleTimeMillis, bValidateOnIdle);

    // Next, we'll create a ConnectionFactory that the pool will use to 
    // create Connections. I am using DriverManagerConnectionFactory instead 
    // of DriverConnectionFactory because it allows me to specify user name 
    // and password directly
    connectionFactory = new DriverManagerConnectionFactory(strUrl, strUser, strPassword);

    // This configuration of prepared statement caching is inspired by
    // Commons-DBCP Wiki available at http://wiki.apache.org/jakarta-commons/DBCP
    // null can be used as parameter because this parameter is set in 
    // PoolableConnectionFactory when creating a new PoolableConnection
    // 0 according to documentation should mean no limit
    KeyedObjectPoolFactory statementPool = null;
    if (iPreparedStatementCacheSize >= 0) {
        statementPool = new GenericKeyedObjectPoolFactory(null, iPreparedStatementCacheSize);
    }

    // Now we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPool,
            DatabaseImpl.getInstance().getConnectionTestStatement(), false, // not read-only connection
            false, // Default auto commit is false
            iTransactionIsolation);

    // PoolableConnectionFactory doesn't support the initialSize attribute of
    // DBCP so I have replicated the code from BasicDataSource v1.37 here
    try {
        for (int iIndex = 0; iIndex < iInitialPoolSize; iIndex++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new OSSDatabaseAccessException("Error preloading the connection pool", e);
    }

    if (GlobalConstants.ERROR_CHECKING) {
        // Put this check here to trick checkstyle
        assert poolableConnectionFactory != null : "Poolable connection factory cannot be null.";
    }

    return connectionPool;
}

From source file:org.ow2.petals.binding.soap.SoapComponentContext.java

/**
 * <p>//  ww w.j  a v a 2s .c o  m
 * Get a service client associated to an axis service set with the good
 * operation. It is taken from a pool object.
 * </p>
 * <p>
 * <b>This service client must be returned to the pool after usage using
 * API:
 * <code>{@link #returnServiceClient(String, QName, URI, ServiceClient)}</code>
 * .</b>
 * </p>
 * 
 * @param address
 *            the address of the service, mainly used as key to retrieve the
 *            associated SU.
 * @param operation
 *            the target operation QName. Non null
 * @param mep
 *            the message exchange pattern used. Non null
 * @param cdkExtensions
 *            SU extensions used by the service client pool when the
 *            creation of a service client is needed
 * @param provides
 *            the provides block of the endpoint which is creating the
 *            external WS call
 * @param ramprtUserName 
 * @return a ServiceClient. Not null. Must be returned to the pool after
 *         usage using API:
 *         <code>{@link #returnServiceClient(String, QName, URI, ServiceClient)}</code>
 * @throws HandlingException
 */
public ServiceClient borrowServiceClient(final String address, final QName operation, final String soapAction,
        final URI mep, final ConfigurationExtensions cdkExtensions, final Provides provides,
        String rampartUserName) throws MessagingException {

    try {

        String resolvedOp;
        if (operation != null) {
            resolvedOp = operation.toString();
        } else if (soapAction != null) {
            resolvedOp = soapAction;
        } else {
            throw new MessagingException(
                    "Unable to resolve the operation. Set it in the Jbi exchange or SoapAction.");
        }

        final ServiceClientKey key = new ServiceClientKey(address, resolvedOp, mep);
        ObjectPool pool = this.serviceClientPools.get(key);
        if (pool == null) {
            // TODO: The pool max size should be limited by the JBI worker
            // number
            pool = new GenericObjectPool(
                    // object factory
                    new ServiceClientPoolObjectFactory(address, operation, mep, cdkExtensions, this, provides,
                            this.logger, soapAction, rampartUserName),

                    // max number of borrowed object sized to the number of
                    // JBI message processors
                    this.componentConfiguration.getProcessorPoolSize().getValue(),

                    // getting an object blocks until a new or idle object
                    // is available
                    GenericObjectPool.WHEN_EXHAUSTED_BLOCK,

                    // if getting an object is blocked for at most this
                    // delay, a NoSuchElementException will be thrown. In
                    // case of a synchronous call the delay is sized to the
                    // value of the SU's parameter "synchronous-timeout",
                    // otherwise it sized to 5 minutes.
                    MEPConstants.IN_OUT_PATTERN.equals(mep) || MEPConstants.IN_OPTIONAL_OUT_PATTERN.equals(mep)
                            ? SUPropertiesHelper.retrieveTimeout(cdkExtensions)
                            : 300000l,

                    // max number of idle object in the pool. Sized to the
                    // number of JBI acceptors.
                    this.componentConfiguration.getAcceptorPoolSize().getValue(),

                    // min number of idle object in the pool. Sized to 0
                    // (ie when no activity no object in pool)
                    GenericObjectPool.DEFAULT_MIN_IDLE,

                    // no validation test of the borrowed object
                    false,

                    // no validation test of the returned object
                    false,

                    // how long the eviction thread should sleep before
                    // "runs" of examining idle objects. Sized to 5min.
                    300000l,

                    // the number of objects examined in each run of the
                    // idle object evictor. Size to the default value (ie.
                    // 3)
                    GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,

                    // the minimum amount of time that an object may sit
                    // idle in the pool before it is eligible for eviction
                    // due to idle time. Sized to 30min
                    GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,

                    // no validation test of the idle object
                    false,

                    // the minimum amount of time an object may sit idle in
                    // the pool before it is eligible for eviction by the
                    // idle object evictor (if any), with the extra
                    // condition that at least "minIdle" amount of object
                    // remain in the pool.
                    GenericObjectPool.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS,

                    // the pool returns idle objects in last-in-first-out
                    // order
                    true);

            this.serviceClientPools.put(key, pool);
        }

        return (ServiceClient) pool.borrowObject();

    } catch (final Exception e) {
        throw new MessagingException("Can't create get an Axis service client from the pool", e);
    }
}

From source file:org.ow2.petals.binding.soapproxy.SoapComponentContext.java

/**
 * <p>/*from ww w  .  j av  a  2 s .  c om*/
 * Get a service client associated to an axis service set with the good
 * operation. It is taken from a pool object.
 * </p>
 * <p>
 * <b>This service client must be returned to the pool after usage using
 * API:
 * <code>{@link #returnServiceClient(String, QName, URI, ServiceClient)}</code>
 * .</b>
 * </p>
 * 
 * @param address
 *            the address of the service, mainly used as key to retrieve the
 *            associated SU.
 * @param operation
 *            the target operation QName. Non null
 * @param mep
 *            the message exchange pattern used. Non null
 * @param cdkExtensions
 *            SU extensions used by the service client pool when the
 *            creation of a service client is needed
 * @param provides
 *            the provides block of the endpoint which is creating the
 *            external WS call
 * @param ramprtUserName
 * @return a ServiceClient. Not null. Must be returned to the pool after
 *         usage using API:
 *         <code>{@link #returnServiceClient(String, QName, URI, ServiceClient)}</code>
 * @throws HandlingException
 */
public ServiceClient borrowServiceClient(final String address, final QName operation, final String soapAction,
        final URI mep) throws MessagingException {

    try {

        String resolvedOp;
        if (operation != null) {
            resolvedOp = operation.toString();
        } else if (soapAction != null) {
            resolvedOp = soapAction;
        } else {
            throw new MessagingException(
                    "Unable to resolve the operation. Set it in the Jbi exchange or SoapAction.");
        }

        final ServiceClientKey key = new ServiceClientKey(address, resolvedOp, mep);
        ObjectPool pool = this.serviceClientPools.get(key);
        if (pool == null) {
            // TODO: The pool max size should be limited by the JBI worker
            // number
            pool = new GenericObjectPool(
                    // object factory
                    new ServiceClientPoolObjectFactory(address, operation, mep, this, this.logger, soapAction),

                    // max number of borrowed object sized to the number of
                    // JBI message processors
                    this.componentConfiguration.getProcessorPoolSize().getValue(),

                    // getting an object blocks until a new or idle object
                    // is available
                    GenericObjectPool.WHEN_EXHAUSTED_BLOCK,

                    // if getting an object is blocked for at most this
                    // delay, a NoSuchElementException will be thrown. In
                    // case of a synchronous call the delay is sized to the
                    // value of the SU's parameter "synchronous-timeout",
                    // otherwise it sized to 5 minutes.
                    MEPConstants.IN_OUT_PATTERN.equals(mep) || MEPConstants.IN_OPTIONAL_OUT_PATTERN.equals(mep)
                            ? 300000l
                            : 300000l,

                    // max number of idle object in the pool. Sized to the
                    // number of JBI acceptors.
                    this.componentConfiguration.getAcceptorPoolSize().getValue(),

                    // min number of idle object in the pool. Sized to 0
                    // (ie when no activity no object in pool)
                    GenericObjectPool.DEFAULT_MIN_IDLE,

                    // no validation test of the borrowed object
                    false,

                    // no validation test of the returned object
                    false,

                    // how long the eviction thread should sleep before
                    // "runs" of examining idle objects. Sized to 5min.
                    300000l,

                    // the number of objects examined in each run of the
                    // idle object evictor. Size to the default value (ie.
                    // 3)
                    GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,

                    // the minimum amount of time that an object may sit
                    // idle in the pool before it is eligible for eviction
                    // due to idle time. Sized to 30min
                    GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,

                    // no validation test of the idle object
                    false,

                    // the minimum amount of time an object may sit idle in
                    // the pool before it is eligible for eviction by the
                    // idle object evictor (if any), with the extra
                    // condition that at least "minIdle" amount of object
                    // remain in the pool.
                    GenericObjectPool.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS,

                    // the pool returns idle objects in last-in-first-out
                    // order
                    true);

            this.serviceClientPools.put(key, pool);
        }

        return (ServiceClient) pool.borrowObject();

    } catch (final Exception e) {
        throw new MessagingException("Can't create get an Axis service client from the pool", e);
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

            pool = new AbandonedObjectPool(null, config);
        }

        pool.setWhenExhaustedAction(whenExhaustedActionType);

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

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

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

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

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

        KeyedObjectPoolFactory kopf = null;

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

            int maxOpenPreparedStatements = -1; // unlimited

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

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

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

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

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

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

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

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

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

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

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