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

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

Introduction

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

Prototype

public void setTestOnBorrow(boolean testOnBorrow) 

Source Link

Document

When true, objects will be PoolableObjectFactory#validateObject validated before being returned by the #borrowObject method.

Usage

From source file:org.idevlab.rjc.ds.PoolableDataSource.java

private synchronized GenericObjectPool createPool() {
    if (closed) {
        throw new RedisException("Data source is closed");
    }//from  ww w .  j  a  v  a2  s.c om

    if (connectionPool == null) {
        GenericObjectPool gop = new GenericObjectPool();
        gop.setMaxActive(maxActive);
        gop.setMaxIdle(maxIdle);
        gop.setMinIdle(minIdle);
        gop.setMaxWait(maxWait);
        gop.setTestOnBorrow(testOnBorrow);
        gop.setTestOnReturn(testOnReturn);
        gop.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        gop.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        gop.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        gop.setTestWhileIdle(testWhileIdle);
        connectionPool = gop;
        createConnectionFactory();
        try {
            for (int i = 0; i < initialSize; i++) {
                connectionPool.addObject();
            }
        } catch (Exception e) {
            throw new RedisException("Error preloading the connection pool", e);
        }
    }

    return connectionPool;
}

From source file:org.jaffa.persistence.engines.jdbcengine.datasource.DbcpDataSourceConnectionFactory.java

private void createDbcpDataSource() throws SQLException {
    try {//from   w w  w.  jav a  2s . c om
        synchronized (dataSourceLock) {
            if (c_dataSource == null) {
                // First we load the underlying JDBC driver.
                Class.forName(getDriverClass());

                // Next, we'll need a ObjectPool that serves as the actual pool of connections.
                // We'll use a GenericObjectPool instance
                GenericObjectPool connectionPool = new GenericObjectPool(null);
                if (getMaximumConnections() != null)
                    connectionPool.setMaxActive(getMaximumConnections());
                if (getMinimumConnections() != null)
                    connectionPool.setMaxIdle(getMinimumConnections());
                if (getMaxWait() != null)
                    connectionPool.setMaxWait(getMaxWait());
                if (getTestOnBorrow() != null)
                    connectionPool.setTestOnBorrow(getTestOnBorrow());
                if (getTestOnReturn() != null)
                    connectionPool.setTestOnReturn(getTestOnReturn());

                // Next, we'll create a ConnectionFactory that the pool will use to create Connections.
                // We'll use the DriverManagerConnectionFactory
                ConnectionFactory connectionFactory = null;
                if (m_driverProperties == null || m_driverProperties.isEmpty())
                    connectionFactory = new DriverManagerConnectionFactory(getUrl(), getUser(), getPassword());
                else
                    connectionFactory = new DriverManagerConnectionFactory(getUrl(), getDriverProperties());
                // Now we'll create the PoolableConnectionFactory, which wraps the "real" Connections created by the ConnectionFactory with the classes that implement the pooling functionality.
                KeyedObjectPoolFactory stmtPoolFactory = new StackKeyedObjectPoolFactory();
                String validationQuery = getValidationQuery();
                boolean defaultReadOnly = false;
                boolean defaultAutoCommit = false;
                PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                        connectionFactory, connectionPool, stmtPoolFactory, validationQuery, defaultReadOnly,
                        defaultAutoCommit);

                // Finally, we create the PoolingDriver itself, passing in the object pool we created.
                c_dataSource = new PoolingDataSource(connectionPool);

                // This will allow us to access the underlying Connection objects, required by the JdbcSecurityPlugin
                ((PoolingDataSource) c_dataSource).setAccessToUnderlyingConnectionAllowed(true);

                if (log.isDebugEnabled())
                    log.debug("Created the Dbcp DataSource");
            }
        }
    } catch (Exception e) {
        String str = "Error in creating the Dbcp DataSource";
        log.error(str, e);
        throw new SQLException(str);
    }
}

From source file:org.kchine.rpf.db.ServantProxyPoolSingletonDB.java

public static GenericObjectPool getInstance(String poolName, String driver, final String url, final String user,
        final String password) {
    String key = driver + "%" + poolName + "%" + url + "%" + user + "%" + password;
    if (_pool.get(key) != null)
        return _pool.get(key);
    synchronized (lock) {
        if (_pool.get(key) == null) {
            Connection conn = null;
            try {
                Class.forName(driver);
                final Vector<Object> borrowedObjects = new Vector<Object>();
                DBLayerInterface dbLayer = DBLayer.getLayer(getDBType(url), new ConnectionProvider() {
                    public Connection newConnection() throws SQLException {
                        return DriverManager.getConnection(url, user, password);
                    }//from www .  jav a 2  s . c  om
                });
                final GenericObjectPool p = new GenericObjectPool(
                        new ServantProxyFactoryDB(poolName, dbLayer)) {
                    @Override
                    public synchronized Object borrowObject() throws Exception {
                        if (_shuttingDown)
                            throw new NoSuchElementException();
                        Object result = super.borrowObject();
                        borrowedObjects.add(result);
                        return result;
                    }

                    @Override
                    public synchronized void returnObject(Object obj) throws Exception {
                        super.returnObject(obj);
                        borrowedObjects.remove(obj);
                    }
                };

                if (System.getProperty("pools.dbmode.shutdownhook.enabled") != null
                        && System.getProperty("pools.dbmode.shutdownhook.enabled").equalsIgnoreCase("false")) {

                } else {
                    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                        public void run() {
                            synchronized (p) {

                                final Vector<Object> bo = (Vector<Object>) borrowedObjects.clone();

                                _shuttingDown = true;
                                try {
                                    for (int i = 0; i < bo.size(); ++i)
                                        p.returnObject(bo.elementAt(i));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }));
                }

                _pool.put(key, p);
                p.setMaxIdle(0);
                p.setTestOnBorrow(true);
                p.setTestOnReturn(true);
            } catch (Exception e) {
                throw new RuntimeException(getStackTraceAsString(e));
            }

        }
        return _pool.get(key);
    }
}

From source file:org.kchine.rpf.db.ServantProxyPoolSingletonDB.java

public static GenericObjectPool getInstance(String poolName, DBLayerInterface dbLayer) {
    String key = poolName + "%" + dbLayer.toString();

    if (_pool.get(key) != null)
        return _pool.get(key);
    synchronized (lock) {
        if (_pool.get(key) == null) {
            Connection conn = null;
            try {
                final Vector<Object> borrowedObjects = new Vector<Object>();

                final GenericObjectPool p = new GenericObjectPool(
                        new ServantProxyFactoryDB(poolName, dbLayer)) {
                    @Override// w  ww  .j  a v a2 s  .  c om
                    public synchronized Object borrowObject() throws Exception {
                        if (_shuttingDown)
                            throw new NoSuchElementException();
                        Object result = super.borrowObject();
                        borrowedObjects.add(result);
                        return result;
                    }

                    @Override
                    public synchronized void returnObject(Object obj) throws Exception {
                        super.returnObject(obj);
                        borrowedObjects.remove(obj);
                    }
                };

                if (System.getProperty("pools.dbmode.shutdownhook.enabled") != null
                        && System.getProperty("pools.dbmode.shutdownhook.enabled").equalsIgnoreCase("false")) {

                } else {
                    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                        public void run() {
                            synchronized (p) {

                                final Vector<Object> bo = (Vector<Object>) borrowedObjects.clone();

                                _shuttingDown = true;
                                try {
                                    for (int i = 0; i < bo.size(); ++i)
                                        p.returnObject(bo.elementAt(i));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }));
                }

                _pool.put(key, p);
                p.setMaxIdle(0);
                p.setTestOnBorrow(true);
                p.setTestOnReturn(true);
            } catch (Exception e) {
                throw new RuntimeException(getStackTraceAsString(e));
            }

        }
        return _pool.get(key);
    }
}

From source file:org.kchine.rpf.reg.ServantProxyPoolSingletonReg.java

public static GenericObjectPool getInstance(String registryHost, int registryPort, String poolNamingPrefix) {

    String key = registryHost + '/' + registryPort + '/' + poolNamingPrefix;
    if (_pool.get(key) != null)
        return _pool.get(key);

    synchronized (lock) {

        if (_pool.get(key) == null) {
            GenericObjectPool p = new GenericObjectPool(
                    new ServantsProxyFactoryReg(registryHost, registryPort, poolNamingPrefix));
            _pool.put(key, p);//from ww  w.j a va  2 s. c om
            p.setTestOnBorrow(true);
            p.setTestOnReturn(true);
        }
        return _pool.get(key);
    }
}

From source file:org.mule.transport.ftp.FtpConnector.java

protected GenericObjectPool createPool(FtpConnectionFactory connectionFactory) {
    GenericObjectPool genericPool = new GenericObjectPool(connectionFactory);
    byte poolExhaustedAction = ThreadingProfile.DEFAULT_POOL_EXHAUST_ACTION;

    ThreadingProfile receiverThreadingProfile = this.getReceiverThreadingProfile();
    if (receiverThreadingProfile != null) {
        int threadingProfilePoolExhaustedAction = receiverThreadingProfile.getPoolExhaustedAction();
        if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_WAIT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_ABORT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_RUN) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
        }/*  ww w . j  ava  2 s . com*/
    }

    genericPool.setWhenExhaustedAction(poolExhaustedAction);
    genericPool.setTestOnBorrow(isValidateConnections());
    return genericPool;
}

From source file:org.mule.transport.ftps.FtpsConnector.java

protected GenericObjectPool createPool(FtpsConnectionFactory connectionFactory) {
    GenericObjectPool genericPool = new GenericObjectPool(connectionFactory);
    byte poolExhaustedAction = ThreadingProfile.DEFAULT_POOL_EXHAUST_ACTION;

    ThreadingProfile receiverThreadingProfile = this.getReceiverThreadingProfile();
    if (receiverThreadingProfile != null) {
        int threadingProfilePoolExhaustedAction = receiverThreadingProfile.getPoolExhaustedAction();
        if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_WAIT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_ABORT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_RUN) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
        }//  ww  w  . ja va 2s.  c om
    }

    genericPool.setWhenExhaustedAction(poolExhaustedAction);
    genericPool.setTestOnBorrow(isValidateConnections());
    return genericPool;
}

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 w  w .j a v a 2  s . c  om*/
        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.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Initialize a jdbc connection pool/*  www.  j  a  v  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.openbravo.database.ConnectionProviderImpl.java

public void addNewPool(String dbDriver, String dbServer, String dbLogin, String dbPassword, int minConns,
        int maxConns, double maxConnTime, String dbSessionConfig, String rdbms, String name) throws Exception {
    log4j.debug("Loading underlying JDBC driver.");
    try {/*from w  ww  . j a va  2  s . com*/
        Class.forName(dbDriver);
    } catch (ClassNotFoundException e) {
        throw new Exception(e);
    }
    log4j.debug("Done.");

    GenericObjectPool connectionPool = new GenericObjectPool(null);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    connectionPool.setMaxActive(maxConns);
    connectionPool.setTestOnBorrow(false);
    connectionPool.setTestOnReturn(false);
    connectionPool.setTestWhileIdle(false);

    KeyedObjectPoolFactory keyedObject = new StackKeyedObjectPoolFactory();
    ConnectionFactory connectionFactory = new OpenbravoDriverManagerConnectionFactory(dbServer, dbLogin,
            dbPassword, dbSessionConfig, rdbms);
    @SuppressWarnings("unused")
    // required by dbcp
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, keyedObject, null, false, true);

    Class.forName("org.apache.commons.dbcp.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    driver.registerPool(contextName + "_" + name, connectionPool);

    if (this.defaultPoolName == null || this.defaultPoolName.equals("")) {
        this.defaultPoolName = name;
        this.bbdd = dbServer;
        this.rdbms = rdbms;
    }
}