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

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

Introduction

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

Prototype

public 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:de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService.java

private static DataSource setupDataSource(String dbUrl, String dbUserName, String dbPassword) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl(dbUrl);/*ww  w. j av  a 2s  .com*/
    dataSource.setUsername(dbUserName);
    dataSource.setPassword(dbPassword);
    dataSource.setValidationQuery("SELECT 1;");
    dataSource.setTestOnBorrow(true); // test each connection when borrowing from the pool with the validation query
    dataSource.setMaxConnLifetimeMillis(1000 * 60 * 60); // max connection life time 1h. mysql drops connection after 8h.
    return dataSource;
}

From source file:de.anycook.db.mysql.DBHandler.java

private static BasicDataSource setupDataSource(String server, int port, String dbName, String username,
        String password, int maxActive, int maxIdle) {
    Preconditions.checkNotNull(server);/*from ww w  . j  a v a  2 s  .  c  o m*/
    Preconditions.checkNotNull(dbName);
    Preconditions.checkNotNull(username);

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUsername(username);

    if (password.length() > 0) {
        ds.setPassword(password);
    }

    String url = String.format("jdbc:mysql://%s:%d/%s?useConfigs=maxPerformance&useCompression=true", server,
            port, dbName);
    ds.setUrl(url);
    ds.setValidationQuery("SELECT 1;");
    ds.setTestWhileIdle(true);
    ds.setTestOnReturn(true);
    ds.setMaxTotal(maxActive);
    ds.setMaxIdle(maxIdle);
    ds.setRemoveAbandonedOnBorrow(true);
    ds.setRemoveAbandonedTimeout(60);

    if (Configuration.getInstance().isDeveloperMode()) {
        ds.setLogAbandoned(true);
    }

    sLogger.info("created new Connectionpool");
    return ds;
}

From source file:com.samovich.service.blueprint.App.java

/**
 * Data source configuration with dbcp/*w  w  w  .  j a  v  a  2  s . c  o m*/
 * @return dataSource
 */
@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://HOST:PORT/DATABASE_NAME");
    dataSource.setUsername("DB_USER");
    dataSource.setPassword("RB_PW");
    dataSource.setValidationQuery("select 1");
    dataSource.setMaxTotal(50);
    dataSource.setTestOnBorrow(true);
    dataSource.setMaxWaitMillis(10000);
    dataSource.setRemoveAbandonedOnBorrow(true);
    dataSource.setDefaultAutoCommit(false);
    dataSource.setNumTestsPerEvictionRun(3);
    dataSource.setTimeBetweenEvictionRunsMillis(1800000);
    dataSource.setMinEvictableIdleTimeMillis(1800000);
    return dataSource;
}

From source file:io.druid.metadata.SQLFirehoseDatabaseConnector.java

protected BasicDataSource getDatasource(MetadataStorageConnectorConfig connectorConfig) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUsername(connectorConfig.getUser());
    dataSource.setPassword(connectorConfig.getPassword());
    String uri = connectorConfig.getConnectURI();
    dataSource.setUrl(uri);//  w  w  w  .j  a va2s  . c o m
    dataSource.setTestOnBorrow(true);
    dataSource.setValidationQuery(getValidationQuery());

    return dataSource;
}

From source file:com.ebay.pulsar.analytics.dao.RDBMS.java

private boolean init(boolean force) {
    if (dataSource == null || force) {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUsername(userName);
        dataSource.setPassword(userPwd);
        dataSource.setUrl(url);//from  w ww .ja  v a 2  s .c  o  m
        dataSource.setTestOnBorrow(true);
        if (validationQuery != null)
            dataSource.setValidationQuery(validationQuery);
        dataSource.setDriverClassLoader(Thread.currentThread().getContextClassLoader());
        dataSource.setDriverClassName(driver);
        this.setDataSource(dataSource);
    }
    return true;
}

From source file:io.druid.metadata.SQLMetadataConnector.java

protected BasicDataSource getDatasource() {
    MetadataStorageConnectorConfig connectorConfig = getConfig();

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUsername(connectorConfig.getUser());
    dataSource.setPassword(connectorConfig.getPassword());
    String uri = connectorConfig.getConnectURI();
    dataSource.setUrl(uri);//from ww  w.  ja  v  a2  s.  co m

    dataSource.setValidationQuery(getValidationQuery());
    dataSource.setTestOnBorrow(true);

    return dataSource;
}

From source file:de.micromata.genome.util.runtime.LocalSettingsEnv.java

/**
 * Parses the ds.//from  ww w .  java  2  s .c om
 */
protected void parseDs() {
    // db.ds.rogerdb.name=RogersOracle
    // db.ds.rogerdb.drivername=oracle.jdbc.driver.OracleDriver
    // db.ds.rogerdb.url=jdbc:oracle:thin:@localhost:1521:rogdb
    // db.ds.rogerdb.username=genome
    // db.ds.rogerdb.password=genome
    List<String> dse = localSettings.getKeysPrefixWithInfix("db.ds", "name");
    for (String dsn : dse) {
        String key = dsn + ".name";
        String name = localSettings.get(key);
        if (StringUtils.isBlank(name) == true) {
            log.error("Name in local-settings is not defined with key: " + key);
            continue;
        }
        key = dsn + ".drivername";
        String driverName = localSettings.get(key);
        if (StringUtils.isBlank(name) == true) {
            log.error("drivername in local-settings is not defined with key: " + key);
            continue;
        }
        key = dsn + ".url";
        String url = localSettings.get(key);
        if (StringUtils.isBlank(name) == true) {
            log.error("url in local-settings is not defined with key: " + key);
            continue;
        }
        key = dsn + ".username";
        String userName = localSettings.get(key);
        key = dsn + ".password";
        String password = localSettings.get(key);
        BasicDataSource bd = dataSourceSuplier.get();

        bd.setDriverClassName(driverName);
        bd.setUrl(url);
        bd.setUsername(userName);
        bd.setPassword(password);
        bd.setMaxTotal(localSettings.getIntValue(dsn + ".maxActive",
                GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY));
        bd.setMaxIdle(localSettings.getIntValue(dsn + ".maxIdle",
                GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY));
        bd.setMinIdle(localSettings.getIntValue(dsn + ".minIdle",
                GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY));
        bd.setMaxWaitMillis(localSettings.getLongValue(dsn + ".maxWait",
                GenericKeyedObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS));
        bd.setInitialSize(localSettings.getIntValue(dsn + ".intialSize", 0));
        bd.setDefaultCatalog(localSettings.get(dsn + ".defaultCatalog", null));
        bd.setDefaultAutoCommit(localSettings.getBooleanValue(dsn + ".defaultAutoCommit", true));
        bd.setValidationQuery(localSettings.get(dsn + ".validationQuery", null));
        bd.setValidationQueryTimeout(localSettings.getIntValue(dsn + ".validationQueryTimeout", -1));
        dataSources.put(name, bd);
    }
}

From source file:annis.administration.AdministrationDao.java

private BasicDataSource createDataSource(String host, String port, String database, String user,
        String password, boolean useSSL, String schema) {

    String url = "jdbc:postgresql://" + host + ":" + port + "/" + database;

    // DriverManagerDataSource is deprecated
    // return new DriverManagerDataSource("org.postgresql.Driver", url, user, password);
    BasicDataSource result = new BasicDataSource();
    result.setUrl(url);/*w  w w  .j  a v a  2s. c o  m*/
    if (useSSL) {
        result.setConnectionProperties("ssl=true");
    }
    result.setUsername(user);
    result.setPassword(password);
    result.setValidationQuery("SELECT 1;");
    result.setAccessToUnderlyingConnectionAllowed(true);
    if (schema == null) {
        schema = "public";
    }
    result.setConnectionInitSqls(Arrays.asList("SET search_path TO \"$user\"," + schema));

    result.setDriverClassName("org.postgresql.Driver");

    return result;
}

From source file:no.kantega.publishing.common.util.database.dbConnectionFactory.java

public static void loadConfiguration() {
    try {//from ww w  . j av  a 2s.c  om

        setConfiguration();

        verifyCompleteDatabaseConfiguration();

        DriverManagerDataSource rawDataSource = new DriverManagerDataSource();
        rawDataSource.setDriverClassName(dbDriver);
        rawDataSource.setUrl(dbUrl);

        if (!dbNTMLAuthentication) {
            rawDataSource.setUsername(dbUsername);
            rawDataSource.setPassword(dbPassword);
        }

        if (dbEnablePooling) {
            // Enable DBCP pooling
            BasicDataSource bds = new BasicDataSource();
            bds.setMaxTotal(dbMaxConnections);
            bds.setMaxIdle(dbMaxIdleConnections);
            bds.setMinIdle(dbMinIdleConnections);
            if (dbMaxWait != -1) {
                bds.setMaxWaitMillis(1000 * dbMaxWait);
            }

            if (dbDefaultQueryTimeout != -1) {
                bds.setDefaultQueryTimeout(dbDefaultQueryTimeout);
            }

            bds.setDriverClassName(dbDriver);
            if (!dbNTMLAuthentication) {
                bds.setUsername(dbUsername);
                bds.setPassword(dbPassword);
            }
            bds.setUrl(dbUrl);

            if (dbUseTransactions) {
                bds.setDefaultTransactionIsolation(dbTransactionIsolationLevel);
            }

            if (dbCheckConnections) {
                // Gjr at connections frigjres ved lukking fra database/brannmur
                bds.setValidationQuery("SELECT max(ContentId) from content");
                bds.setTimeBetweenEvictionRunsMillis(1000 * 60 * 2);
                bds.setMinEvictableIdleTimeMillis(1000 * 60 * 5);
                bds.setNumTestsPerEvictionRun(dbMaxConnections);
                if (dbRemoveAbandonedTimeout > 0) {
                    bds.setRemoveAbandonedTimeout(dbRemoveAbandonedTimeout);
                    bds.setLogAbandoned(true);
                }
            }

            ds = bds;
        } else {
            ds = rawDataSource;
        }

        // Use non-pooled datasource for table creation since validation query might fail
        ensureDatabaseExists(rawDataSource);
        if (shouldMigrateDatabase) {
            migrateDatabase(servletContext, rawDataSource);
        }

        if (dbUseTransactions) {
            log.info("Using transactions, database transaction isolation level set to "
                    + dbTransactionIsolationLevel);
        } else {
            log.info("Not using transactions");
        }

        if (debugConnections) {
            proxyDs = (DataSource) Proxy.newProxyInstance(DataSource.class.getClassLoader(),
                    new Class[] { DataSource.class }, new DataSourceWrapper(ds));
        }

    } catch (Exception e) {
        log.error("********* could not read aksess.conf **********", e);
    }

}

From source file:org.apache.jmeter.protocol.jdbc.config.DataSourceElement.java

private BasicDataSource initPool(String maxPool) {
    BasicDataSource dataSource = new BasicDataSource();

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("MaxPool: ");
        sb.append(maxPool);//from ww  w .jav a2  s  . c  om
        sb.append(" Timeout: ");
        sb.append(getTimeout());
        sb.append(" TrimInt: ");
        sb.append(getTrimInterval());
        sb.append(" Auto-Commit: ");
        sb.append(isAutocommit());
        log.debug(sb.toString());
    }
    int poolSize = Integer.parseInt(maxPool);
    dataSource.setMinIdle(0);
    dataSource.setInitialSize(poolSize);
    dataSource.setMaxIdle(poolSize);
    dataSource.setMaxTotal(poolSize);
    dataSource.setMaxWaitMillis(Long.parseLong(getTimeout()));

    dataSource.setDefaultAutoCommit(Boolean.valueOf(isAutocommit()));

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("KeepAlive: ");
        sb.append(isKeepAlive());
        sb.append(" Age: ");
        sb.append(getConnectionAge());
        sb.append(" CheckQuery: ");
        sb.append(getCheckQuery());
        log.debug(sb.toString());
    }
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTestOnCreate(false);
    dataSource.setTestWhileIdle(false);

    if (isKeepAlive()) {
        dataSource.setTestWhileIdle(true);
        dataSource.setValidationQuery(getCheckQuery());
        dataSource.setSoftMinEvictableIdleTimeMillis(Long.parseLong(getConnectionAge()));
        dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(getTrimInterval()));
    }

    int transactionIsolation = DataSourceElementBeanInfo.getTransactionIsolationMode(getTransactionIsolation());
    if (transactionIsolation >= 0) {
        dataSource.setDefaultTransactionIsolation(transactionIsolation);
    }

    String _username = getUsername();
    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("Driver: ");
        sb.append(getDriver());
        sb.append(" DbUrl: ");
        sb.append(getDbUrl());
        sb.append(" User: ");
        sb.append(_username);
        log.debug(sb.toString());
    }
    dataSource.setDriverClassName(getDriver());
    dataSource.setUrl(getDbUrl());

    if (_username.length() > 0) {
        dataSource.setUsername(_username);
        dataSource.setPassword(getPassword());
    }

    // log is required to ensure errors are available
    //source.enableLogging(new LogKitLogger(log));
    if (log.isDebugEnabled()) {
        log.debug("PoolConfiguration:" + this.dataSource);
    }
    return dataSource;
}