Example usage for org.apache.commons.dbcp BasicDataSource setValidationQuery

List of usage examples for org.apache.commons.dbcp BasicDataSource setValidationQuery

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource setValidationQuery.

Prototype

public synchronized void setValidationQuery(String validationQuery) 

Source Link

Document

Sets the #validationQuery .

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:org.geotools.jdbc.JDBCDataStoreFactory.java

/**
 * DataSource access allowing SQL use: intended to allow client code to query available schemas.
 * <p>//from  ww  w  .j a  v a  2s . co m
 * This DataSource is the clients responsibility to close() when they are finished using it.
 * </p> 
 * @param params Map of connection parameter.
 * @return DataSource for SQL use
 * @throws IOException
 */
public BasicDataSource createDataSource(Map params) throws IOException {
    //create a datasource
    BasicDataSource dataSource = new BasicDataSource();

    // driver
    dataSource.setDriverClassName(getDriverClassName());

    // url
    dataSource.setUrl(getJDBCUrl(params));

    // username
    String user = (String) USER.lookUp(params);
    dataSource.setUsername(user);

    // password
    String passwd = (String) PASSWD.lookUp(params);
    if (passwd != null) {
        dataSource.setPassword(passwd);
    }

    // max wait
    Integer maxWait = (Integer) MAXWAIT.lookUp(params);
    if (maxWait != null && maxWait != -1) {
        dataSource.setMaxWait(maxWait * 1000);
    }

    // connection pooling options
    Integer minConn = (Integer) MINCONN.lookUp(params);
    if (minConn != null) {
        dataSource.setMinIdle(minConn);
    }

    Integer maxConn = (Integer) MAXCONN.lookUp(params);
    if (maxConn != null) {
        dataSource.setMaxActive(maxConn);
    }

    Boolean validate = (Boolean) VALIDATECONN.lookUp(params);
    if (validate != null && validate && getValidationQuery() != null) {
        dataSource.setTestOnBorrow(true);
        dataSource.setValidationQuery(getValidationQuery());
    }

    // some datastores might need this
    dataSource.setAccessToUnderlyingConnectionAllowed(true);
    return dataSource;
}

From source file:org.geowebcache.diskquota.jdbc.JDBCQuotaStoreFactory.java

private DataSource getDataSource(JDBCConfiguration config) throws ConfigurationException {
    try {/* w  w w. jav  a2 s.  c  o m*/
        DataSource ds = null;
        if (config.getJNDISource() != null) {
            InitialContext context = new InitialContext();
            ds = (DataSource) context.lookup(config.getJNDISource());
        } else if (config.getConnectionPool() != null) {
            ConnectionPoolConfiguration cp = config.getConnectionPool();

            BasicDataSource bds = new BasicDataSource();
            bds.setDriverClassName(cp.getDriver());
            bds.setUrl(cp.getUrl());
            bds.setUsername(cp.getUsername());
            bds.setPassword(cp.getPassword());
            bds.setPoolPreparedStatements(true);
            bds.setMaxOpenPreparedStatements(cp.getMaxOpenPreparedStatements());
            bds.setMinIdle(cp.getMinConnections());
            bds.setMaxActive(cp.getMaxConnections());
            bds.setMaxWait(cp.getConnectionTimeout() * 1000);
            bds.setValidationQuery(cp.getValidationQuery());

            ds = bds;
        }

        // verify the datasource works
        Connection c = null;
        try {
            c = ds.getConnection();
        } catch (SQLException e) {
            throw new ConfigurationException("Failed to get a database connection: " + e.getMessage(), e);
        } finally {
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException e) {
                    // nothing we can do about it, but at least let the admin know
                    log.debug("An error occurred while closing the test JDBC connection: " + e.getMessage(), e);
                }
            }
        }

        return ds;
    } catch (NamingException e) {
        throw new ConfigurationException("Failed to locate the data source in JNDI", e);
    }
}

From source file:org.jxstar.dao.pool.PooledConnection.java

/**
 * ???/*from w  w  w  .j a  v  a2s . c  o  m*/
 * @param dsName
 * @return
 */
private DataSource createSelfDataSource(DataSourceConfig dsConfig) {
    String dsName = dsConfig.getDataSourceName();
    BasicDataSource ds = (BasicDataSource) _myDataSourceMap.get(dsName);
    if (ds != null)
        return ds;

    ds = new BasicDataSource();
    //???
    int iTranLevel = getTranLevelConstant(dsConfig.getTranLevel());
    int maxnum = Integer.parseInt(dsConfig.getMaxConNum());

    ds.setDriverClassName(dsConfig.getDriverClass());
    ds.setUrl(dsConfig.getJdbcUrl());
    ds.setUsername(dsConfig.getUserName());
    ds.setPassword(dsConfig.getPassWord());

    ds.setMaxIdle(maxnum);
    ds.setMaxActive(maxnum);
    ds.setMaxWait(Long.parseLong(dsConfig.getMaxWaitTime()));
    ds.setDefaultAutoCommit(false);
    ds.setDefaultTransactionIsolation(iTranLevel);

    //????SystemVarserver.xml?
    String validTest = dsConfig.getValidTest();
    String validQuery = dsConfig.getValidQuery();
    if (validTest.equalsIgnoreCase("true") && validQuery.length() > 0) {
        _log.showDebug("pool test use query...");
        ds.setTestOnBorrow(true);
        ds.setValidationQuery(validQuery);
        ds.setValidationQueryTimeout(3);
    }

    //?mysql???
    //?????
    if (dsConfig.getValidIdle().equalsIgnoreCase("true")) {
        _log.showDebug("pool idle valid thread started...");
        ds.setMinIdle(5);
        ds.setTestWhileIdle(true);

        //1030?5
        ds.setMinEvictableIdleTimeMillis(30 * 60 * 1000);//30 minus
        ds.setTimeBetweenEvictionRunsMillis(10 * 60 * 1000);//10 minus
    }

    //???
    _myDataSourceMap.put(dsName, ds);

    return ds;
}

From source file:org.nebula.service.core.DynamicDataSource.java

public void onChange(String dbUrl) {

    logger.info("Change target dbUrl to: " + dbUrl);

    Object oldDataSource = this.datasources.remove(LOOKUP_KEY);

    if (oldDataSource != null) {
        try {/*w  w  w . ja  v  a 2  s  . c o m*/
            ((BasicDataSource) oldDataSource).close();
        } catch (SQLException e) {
            //ignore
        }
    }

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setMaxActive(jdbcMaxActive);
    dataSource.setMaxIdle(jdbcMaxIdle);
    dataSource.setInitialSize(jdbcInitialSize);
    dataSource.setUrl(dbUrl);
    dataSource.setUsername(jdbcUsername);
    dataSource.setPassword(jdbcPassword);
    dataSource.setTestOnBorrow(true);
    dataSource.setValidationQuery("SELECT 1");

    this.datasources.put(LOOKUP_KEY, dataSource);
}

From source file:org.ngrinder.infra.config.Database.java

/**
 * Setup the database common features.// ww  w  .j  a  va  2s.com
 *
 * @param dataSource datasource
 */
protected void setupCommon(BasicDataSource dataSource) {
    dataSource.setDriverClassName(getJdbcDriverName());
    dataSource.setInitialSize(DB_INITIAL_SIZE);
    dataSource.setMaxActive(DB_MAX_ACTIVE);
    dataSource.setMinIdle(DB_MIN_IDLE);
    dataSource.setMaxWait(DB_MAX_WAIT);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setMaxOpenPreparedStatements(DB_MAX_OPEN_PREPARED_STATEMENTS);
    dataSource.setTestWhileIdle(true);
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(true);
    dataSource.setValidationQuery("SELECT 1");
}

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

private DataSource convert(IDatasource datasource) {
    BasicDataSource basicDatasource = new BasicDataSource();
    basicDatasource.setDriverClassName(datasource.getDriverClass());
    basicDatasource.setMaxActive(datasource.getMaxActConn());
    basicDatasource.setMaxIdle(datasource.getIdleConn());
    basicDatasource.setMaxWait(datasource.getWait());
    basicDatasource.setUrl(datasource.getUrl());
    basicDatasource.setUsername(datasource.getUserName());
    basicDatasource.setPassword(datasource.getPassword());
    basicDatasource.setValidationQuery(datasource.getQuery());
    return basicDatasource;
}

From source file:org.pinus4j.cluster.impl.AppDBClusterImpl.java

@Override
public void buildDataSource(DBInfo dbConnInfo) throws LoadConfigException {
    AppDBInfo appDbConnInfo = (AppDBInfo) dbConnInfo;

    LOG.info(dbConnInfo.toString());//from   ww  w . ja  va2s  .  com

    try {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(enumDb.getDriverClass());
        ds.setUsername(appDbConnInfo.getUsername());
        ds.setPassword(appDbConnInfo.getPassword());
        ds.setUrl(appDbConnInfo.getUrl());

        // ?
        Map<String, Object> dbConnPoolInfo = appDbConnInfo.getConnPoolInfo();
        ds.setValidationQuery("SELECT 1");
        ds.setMaxActive((Integer) dbConnPoolInfo.get(Const.PROP_MAXACTIVE));
        ds.setMinIdle((Integer) dbConnPoolInfo.get(Const.PROP_MINIDLE));
        ds.setMaxIdle((Integer) dbConnPoolInfo.get(Const.PROP_MAXIDLE));
        ds.setInitialSize((Integer) dbConnPoolInfo.get(Const.PROP_INITIALSIZE));
        ds.setRemoveAbandoned((Boolean) dbConnPoolInfo.get(Const.PROP_REMOVEABANDONED));
        ds.setRemoveAbandonedTimeout((Integer) dbConnPoolInfo.get(Const.PROP_REMOVEABANDONEDTIMEOUT));
        ds.setMaxWait((Integer) dbConnPoolInfo.get(Const.PROP_MAXWAIT));
        ds.setTimeBetweenEvictionRunsMillis(
                (Integer) dbConnPoolInfo.get(Const.PROP_TIMEBETWEENEVICTIONRUNSMILLIS));
        ds.setNumTestsPerEvictionRun((Integer) dbConnPoolInfo.get(Const.PROP_NUMTESTSPEREVICTIONRUN));
        ds.setMinEvictableIdleTimeMillis((Integer) dbConnPoolInfo.get(Const.PROP_MINEVICTABLEIDLETIMEMILLIS));

        dbConnInfo.setDatasource(ds);
    } catch (Exception e) {
        throw new LoadConfigException(e);
    }
}

From source file:org.plista.kornakapi.core.storage.MySqlStorage.java

public MySqlStorage(StorageConfiguration storageConf, String label, BasicDataSource dataSource) {

    dataSource.setDriverClassName(storageConf.getJdbcDriverClass());
    dataSource.setUrl(storageConf.getJdbcUrl());
    dataSource.setUsername(storageConf.getUsername());
    dataSource.setPassword(storageConf.getPassword());

    //TODO should be made configurable
    dataSource.setMaxActive(10);// w  w w . j  av  a 2  s .  c o m
    dataSource.setMinIdle(5);
    dataSource.setInitialSize(5);
    dataSource.setValidationQuery("SELECT 1;");
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setTimeBetweenEvictionRunsMillis(5000);

    dataModel = new LabeledMySQLJDBCDataModel(dataSource, "taste_preferences", "user_id", "item_id",
            "preference", "timestamp", "taste_candidates", "label", label);
    this.dataSource = dataSource;
    this.timeWindow = storageConf.getTimeWindow();
    if (timeWindow % 6 != 0 || timeWindow == 0) {
        timeWindow = 24;
    }

}

From source file:org.sbq.batch.configurations.DatabaseConfiguration.java

@Bean(destroyMethod = "close")
public DataSource dbcpDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/batch_db");
    dataSource.setUsername("root");
    dataSource.setPassword("");
    dataSource.setMaxActive(20);//from ww  w  .  jav a2  s .c  o m
    dataSource.setMaxIdle(20);
    dataSource.setMaxWait(10000);
    dataSource.setInitialSize(5);
    dataSource.setValidationQuery("SELECT 1");
    dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return dataSource;
}

From source file:org.shelloid.vpt.rms.util.Platform.java

private BasicDataSource configDbPool() {
    BasicDataSource ds = new BasicDataSource();
    ds.setTestOnBorrow(true);//from ww w  .j a  v a 2  s  .c om
    ds.setValidationQuery("SELECT 1");
    ds.setDriverClassName(get(Configurations.ConfigParams.JDBC_DRIVER));
    ds.setUrl(get(Configurations.ConfigParams.JDBC_URL));
    ds.setUsername(get(Configurations.ConfigParams.JDBC_USERNAME));
    ds.setPassword(get(Configurations.ConfigParams.JDBC_PASSWORD));
    ds.setMaxActive(Integer.parseInt(get(Configurations.ConfigParams.JDBC_MAX_ACTIVE)));
    ds.setMaxIdle(Integer.parseInt(get(Configurations.ConfigParams.JDBC_MIN_IDLE)));
    return ds;
}