Example usage for org.apache.commons.dbcp2 PoolableConnectionFactory setValidationQuery

List of usage examples for org.apache.commons.dbcp2 PoolableConnectionFactory setValidationQuery

Introduction

In this page you can find the example usage for org.apache.commons.dbcp2 PoolableConnectionFactory setValidationQuery.

Prototype

public void setValidationQuery(String validationQuery) 

Source Link

Document

Sets the query I use to #validateObject validate Connection s.

Usage

From source file:com.parallax.server.blocklyprop.db.utils.DataSourceSetup.java

public static PoolingDataSource connect(Configuration configuration) throws ClassNotFoundException {
    String driver = configuration.getString("database.driver");
    String url = configuration.getString("database.url");
    String username = configuration.getString("database.username");
    String password = configuration.getString("database.password");

    Class.forName(driver);/* ww  w .j  a va2  s .  c  o m*/

    //
    // First, we'll create a ConnectionFactory that the
    // pool will use to create Connections.
    // We'll use the DriverManagerConnectionFactory,
    // using the connect string passed in the command line
    // arguments.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password);

    //
    // Next we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    //
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);
    poolableConnectionFactory.setValidationQuery("SELECT 1");
    poolableConnectionFactory.setMaxConnLifetimeMillis(5000);

    //
    // Now 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.
    //
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);

    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

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

    for (NeedsDataSource dataSourceUser : dataSourceUsers) {
        dataSourceUser.setDataSource(dataSourceInstance);
    }
    DataSourceSetup.dataSource = dataSourceInstance;
    return dataSourceInstance;
}

From source file:kr.co.bitnine.octopus.frame.ConnectionManager.java

private ObjectPool<PoolableConnection> createPool(String connectionString) {
    // A ConnectionFactory that the pool will use to create Connections.
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectionString, null);
    // PoolableConnectionFactory wraps the real Connections with the
    // classes that implement the pooling functionality.
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);/*from  w w w.j  a  v a 2s.  c  om*/
    poolableConnectionFactory.setValidationQuery("SELECT 1");

    // Actual pool of connections.
    GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    int connMax = getConfig().getInt(OctopusConfiguration.MASTER_CONNECTION_POOL_MAX, 8);
    connectionPool.setMaxTotal(connMax);
    connectionPool.setTestOnBorrow(true);
    // Set the factory's pool property to the owning pool.
    poolableConnectionFactory.setPool(connectionPool);

    return connectionPool;
}

From source file:io.seldon.dbcp.DbcpFactory.java

private void createDbcp(DbcpConfig conf) {
    if (!dataSources.containsKey(conf.name)) {
        try {/*from  ww  w.  ja  v  a  2 s  .com*/

            Class.forName(conf.driverClassName);

            DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory(conf.jdbc, conf.user,
                    conf.password);

            PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);
            pcf.setValidationQuery(conf.validationQuery);
            //, pool, null, conf.validationQuery, false, true,abandondedConfig);

            logger.info("Creating pool " + conf.toString());
            // create a generic pool
            GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf);
            pool.setMaxTotal(conf.maxTotal);
            pool.setMaxIdle(conf.maxIdle);
            pool.setMinIdle(conf.minIdle);
            pool.setMaxWaitMillis(conf.maxWait);
            pool.setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
            pool.setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
            pool.setTestWhileIdle(conf.testWhileIdle);
            pool.setTestOnBorrow(conf.testOnBorrow);

            AbandonedConfig abandonedConfig = new AbandonedConfig();
            abandonedConfig.setRemoveAbandonedOnMaintenance(conf.removeAbanadoned);
            abandonedConfig.setRemoveAbandonedTimeout(conf.removeAbandonedTimeout);
            abandonedConfig.setLogAbandoned(conf.logAbandonded);

            pool.setAbandonedConfig(abandonedConfig);

            pcf.setPool(pool);
            DataSource ds = new PoolingDataSource(pool);
            dataSources.put(conf.name, ds);

        } catch (ClassNotFoundException e) {
            logger.error(
                    "Failed to create datasource for " + conf.name + " with class " + conf.driverClassName);
        }

    } else {
        logger.error("Pool " + conf.name + " already exists. Can't change existing datasource at present.");
    }
}

From source file:io.dockstore.common.BasicPostgreSQL.java

public BasicPostgreSQL(HierarchicalINIConfiguration settings) {
    if (dataSource == null) {
        try {/*ww w  .java 2s.  c  o  m*/
            String nullConfigs = "";
            String host = settings.getString(Constants.POSTGRES_HOST);
            if (host == null) {
                nullConfigs += "postgresHost ";
            }

            String user = settings.getString(Constants.POSTGRES_USERNAME);
            if (user == null) {
                nullConfigs += "postgresUser ";
            }

            String pass = settings.getString(Constants.POSTGRES_PASSWORD);
            if (pass == null) {
                nullConfigs += "postgresPass ";
            }

            String db = settings.getString(Constants.POSTGRES_DBNAME);
            if (db == null) {
                nullConfigs += "postgresDBName ";
            }

            String maxConnections = settings.getString(Constants.POSTGRES_MAX_CONNECTIONS, "5");

            if (!nullConfigs.trim().isEmpty()) {
                throw new NullPointerException("The following configuration values are null: " + nullConfigs
                        + ". Please check your configuration file.");
            }

            Class.forName("org.postgresql.Driver");

            String url = "jdbc:postgresql://" + host + "/" + db;
            LOG.debug("PostgreSQL URL is: " + url);
            Properties props = new Properties();
            props.setProperty("user", user);
            props.setProperty("password", pass);
            // props.setProperty("ssl","true");
            props.setProperty("initialSize", "5");
            props.setProperty("maxActive", maxConnections);

            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props);
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                    connectionFactory, null);
            poolableConnectionFactory.setValidationQuery("select count(*) from container;");
            ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
            poolableConnectionFactory.setPool(connectionPool);
            dataSource = new PoolingDataSource<>(connectionPool);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:de.alexandria.cms.config.SpringConfigBackendDatabase.java

private PoolableConnectionFactory getPoolableConnectionFactory() {
    DataSourceConnectionFactory dataSourceConnectionFactory = getDataSourceConnectionFactory();
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
            dataSourceConnectionFactory, null);
    poolableConnectionFactory.setValidationQuery("SELECT 1");
    long maxConnLifetimeMillis = 600000; // ten minutes
    poolableConnectionFactory.setMaxConnLifetimeMillis(maxConnLifetimeMillis);
    return poolableConnectionFactory;
}

From source file:com.zaxxer.hikari.benchmark.BenchBase.java

private void setupDBCP2() {
    org.apache.commons.pool2.impl.GenericObjectPool<org.apache.commons.dbcp2.PoolableConnection> connectionPool;
    DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcURL, "sa", "");

    // Wrap the connections and statements with pooled variants
    org.apache.commons.dbcp2.PoolableConnectionFactory poolableCF = null;
    poolableCF = new org.apache.commons.dbcp2.PoolableConnectionFactory(connectionFactory, null);

    poolableCF.setValidationQuery("VALUES 1");
    poolableCF.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    poolableCF.setDefaultAutoCommit(false);
    poolableCF.setRollbackOnReturn(true);

    // Create the actual pool of connections, and apply any properties
    connectionPool = new org.apache.commons.pool2.impl.GenericObjectPool(poolableCF);
    connectionPool.setTestOnBorrow(true);
    connectionPool.setMaxIdle(maxPoolSize);

    connectionPool.setMinIdle(MIN_POOL_SIZE);
    connectionPool.setMaxTotal(maxPoolSize);
    connectionPool.setMaxWaitMillis(8000);
    connectionPool.setMinEvictableIdleTimeMillis((int) TimeUnit.MINUTES.toMillis(30));
    poolableCF.setPool(connectionPool);//from ww w.j a v  a2 s .c om
    DS = new org.apache.commons.dbcp2.PoolingDataSource(connectionPool);
}

From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImpl.java

/**
 * Creates a DataSource with connection pooling as provided by Apache DBCP
 *
 * @return a DataSource//from www.ja  v a 2s.  com
 */
DataSource configureAndCreateDataSource(RepositoryConfiguration configuration) {

    log.debug("Configuring DataSource wrapped in a Database Connection Pool, using custom loader");

    String jdbcDriverClassPath = configuration.getJdbcDriverClassPath();

    log.debug("Loading JDBC Driver with custom class path: " + jdbcDriverClassPath);
    // Creates a new class loader, which will be used for loading our JDBC driver
    URLClassLoader urlClassLoader = getOxalisClassLoaderForJdbc(jdbcDriverClassPath);

    String className = configuration.getJdbcDriverClassName();
    String connectURI = configuration.getJdbcConnectionUri().toString();
    String userName = configuration.getJdbcUsername();
    String password = configuration.getJdbcPassword();

    log.debug("className=" + className);
    log.debug("connectURI=" + connectURI);
    log.debug("userName=" + userName);
    log.debug("password=" + password);

    // Loads the JDBC Driver in a separate class loader
    Driver driver = getJdbcDriver(jdbcDriverClassPath, urlClassLoader, className);

    Properties properties = new Properties();
    properties.put("user", userName);
    properties.put("password", password);

    // DBCP factory which will produce JDBC Driver instances
    ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectURI, properties);

    // DBCP Factory holding the pooled connection, which are created by the driver connection factory and held in the supplied pool
    ObjectName dataSourceJmxName = null;
    try {
        dataSourceJmxName = new ObjectName("no.difi.oxalis", "connectionPool", "OxalisDB");
    } catch (MalformedObjectNameException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
            dataSourceJmxName);

    String validationQuery = configuration.getValidationQuery();
    if (validationQuery != null) {
        poolableConnectionFactory.setValidationQuery(validationQuery);
    }
    // DBCP object pool holding our driver connections
    GenericObjectPool<PoolableConnection> genericObjectPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);
    poolableConnectionFactory.setPool(genericObjectPool);
    genericObjectPool.setMaxTotal(100);
    genericObjectPool.setMaxIdle(30);
    genericObjectPool.setMaxWaitMillis(10000);

    genericObjectPool.setTestOnBorrow(true); // Test the connection returned from the pool

    genericObjectPool.setTestWhileIdle(true); // Test idle instances visited by the pool maintenance thread and destroy any that fail validation
    genericObjectPool.setTimeBetweenEvictionRunsMillis(60 * 60 * 1000); // Test every hour

    // Creates the actual DataSource instance
    PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool);

    return poolingDataSource;

}

From source file:info.pancancer.arch3.persistence.PostgreSQL.java

public PostgreSQL(HierarchicalINIConfiguration settings) {
    if (dataSource == null) {
        try {//from w ww.ja  va 2 s.c om
            String nullConfigs = "";
            String host = settings.getString(Constants.POSTGRES_HOST);
            if (host == null) {
                nullConfigs += "postgresHost ";
            }

            String user = settings.getString(Constants.POSTGRES_USERNAME);
            if (user == null) {
                nullConfigs += "postgresUser ";
            }

            String pass = settings.getString(Constants.POSTGRES_PASSWORD);
            if (pass == null) {
                nullConfigs += "postgresPass ";
            }

            String db = settings.getString(Constants.POSTGRES_DBNAME);
            if (db == null) {
                nullConfigs += "postgresDBName ";
            }

            String maxConnections = settings.getString(Constants.POSTGRES_MAX_CONNECTIONS, "5");

            if (nullConfigs.trim().length() > 0) {
                throw new NullPointerException("The following configuration values are null: " + nullConfigs
                        + ". Please check your configuration file.");
            }

            Class.forName("org.postgresql.Driver");

            String url = "jdbc:postgresql://" + host + "/" + db;
            LOG.debug("PostgreSQL URL is: " + url);
            Properties props = new Properties();
            props.setProperty("user", user);
            props.setProperty("password", pass);
            // props.setProperty("ssl","true");
            props.setProperty("initialSize", "5");
            props.setProperty("maxActive", maxConnections);

            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props);
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                    connectionFactory, null);
            poolableConnectionFactory.setValidationQuery("select count(*) from job;");
            ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
            poolableConnectionFactory.setPool(connectionPool);
            dataSource = new PoolingDataSource<>(connectionPool);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

private PoolingDataSource createPoolingDataSource(ConnectionFactory driverConnectionFactory) {

    PoolableConnectionFactory poolableConnectionFactory = null;
    try {//from   w  w  w  . j  a v a2s  .co m

        poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
                new ObjectName("no.difi.oxalis", "connectionPool", "TestPool"));

        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(
                poolableConnectionFactory);
        poolableConnectionFactory.setPool(pool);
        poolableConnectionFactory.setValidationQuery("select 1");
        return new PoolingDataSource(pool);

    } catch (MalformedObjectNameException e) {
        throw new IllegalStateException("Unable to create poolable conneciton factory: " + e.getMessage(), e);
    }

}

From source file:JDBCPool.dbcp.demo.sourcecode.BasicDataSource.java

/**
 * Creates the PoolableConnectionFactory and attaches it to the connection pool.  This method only exists
 * so subclasses can replace the default implementation.
 *
 * @param driverConnectionFactory JDBC connection factory
 * @throws SQLException if an error occurs creating the PoolableConnectionFactory
 *///  w  w  w . j  a va  2  s.c  om
protected PoolableConnectionFactory createPoolableConnectionFactory(ConnectionFactory driverConnectionFactory)
        throws SQLException {
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, registeredJmxName);
        connectionFactory.setValidationQuery(validationQuery);
        connectionFactory.setValidationQueryTimeout(validationQueryTimeout);
        connectionFactory.setConnectionInitSql(connectionInitSqls); //?Connection?SQL?
        connectionFactory.setDefaultReadOnly(defaultReadOnly);
        connectionFactory.setDefaultAutoCommit(defaultAutoCommit);
        connectionFactory.setDefaultTransactionIsolation(defaultTransactionIsolation);
        connectionFactory.setDefaultCatalog(defaultCatalog);
        connectionFactory.setCacheState(cacheState);
        connectionFactory.setPoolStatements(poolPreparedStatements);
        connectionFactory.setMaxOpenPrepatedStatements(maxOpenPreparedStatements);
        connectionFactory.setMaxConnLifetimeMillis(maxConnLifetimeMillis);
        connectionFactory.setRollbackOnReturn(getRollbackOnReturn());
        connectionFactory.setEnableAutoCommitOnReturn(getEnableAutoCommitOnReturn());
        connectionFactory.setDefaultQueryTimeout(getDefaultQueryTimeout());
        validateConnectionFactory(connectionFactory); //??
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }
    return connectionFactory;
}