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

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

Introduction

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

Prototype

public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) 

Source Link

Document

Sets the #timeBetweenEvictionRunsMillis property.

Usage

From source file:org.apache.jackrabbit.core.util.db.ConnectionFactory.java

/**
 * Creates and returns a pooling JDBC {@link DataSource} for accessing
 * the database identified by the given driver class and JDBC
 * connection URL. The driver class can be <code>null</code> if
 * a specific driver has not been configured.
 *
 * @param driverClass the JDBC driver class, or <code>null</code>
 * @param url the JDBC connection URL/*from  w w w  .  java  2  s.  c om*/
 * @return pooling DataSource for accessing the specified database
 */
private BasicDataSource getDriverDataSource(Class<?> driverClass, String url, String user, String password) {
    BasicDataSource ds = new BasicDataSource();
    created.add(ds);

    if (driverClass != null) {
        Driver instance = null;
        try {
            // Workaround for Apache Derby:
            // The JDBC specification recommends the Class.forName
            // method without the .newInstance() method call,
            // but it is required after a Derby 'shutdown'
            instance = (Driver) driverClass.newInstance();
        } catch (Throwable e) {
            // Ignore exceptions as there's no requirement for
            // a JDBC driver class to have a public default constructor
        }
        if (instance != null) {
            if (instance.jdbcCompliant()) {
                // JCR-3445 At the moment the PostgreSQL isn't compliant because it doesn't implement this method...                   
                ds.setValidationQueryTimeout(3);
            }
        }
        ds.setDriverClassName(driverClass.getName());
    }

    ds.setUrl(url);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setDefaultAutoCommit(true);
    ds.setTestOnBorrow(false);
    ds.setTestWhileIdle(true);
    ds.setTimeBetweenEvictionRunsMillis(600000); // 10 Minutes
    ds.setMinEvictableIdleTimeMillis(60000); // 1 Minute
    ds.setMaxActive(-1); // unlimited
    ds.setMaxIdle(GenericObjectPool.DEFAULT_MAX_IDLE + 10);
    ds.setValidationQuery(guessValidationQuery(url));
    ds.setAccessToUnderlyingConnectionAllowed(true);
    ds.setPoolPreparedStatements(true);
    ds.setMaxOpenPreparedStatements(-1); // unlimited
    return ds;
}

From source file:org.apache.metamodel.jdbc.JdbcDataContextTest.java

public void testReleaseConnectionsInCompiledQuery() throws Exception {
    final int connectionPoolSize = 2;
    final int threadCount = 4;
    final int noOfCallsPerThreads = 30;

    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.hsqldb.jdbcDriver");
    ds.setUrl("jdbc:hsqldb:res:metamodel");
    ds.setInitialSize(connectionPoolSize);
    ds.setMaxActive(connectionPoolSize);
    ds.setMaxWait(10000);//w w w .j a  v  a2 s  .  c om
    ds.setMinEvictableIdleTimeMillis(1800000);
    ds.setMinIdle(0);
    ds.setMaxIdle(connectionPoolSize);
    ds.setNumTestsPerEvictionRun(3);
    ds.setTimeBetweenEvictionRunsMillis(-1);
    ds.setDefaultTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED);

    final JdbcDataContext dataContext = new JdbcDataContext(ds,
            new TableType[] { TableType.TABLE, TableType.VIEW }, null);

    final JdbcCompiledQuery compiledQuery = (JdbcCompiledQuery) dataContext.query().from("CUSTOMERS")
            .select("CUSTOMERNAME").where("CUSTOMERNUMBER").eq(new QueryParameter()).compile();

    assertEquals(0, compiledQuery.getActiveLeases());
    assertEquals(0, compiledQuery.getIdleLeases());

    final String compliedQueryString = compiledQuery.toSql();

    assertEquals(
            "SELECT _CUSTOMERS_._CUSTOMERNAME_ FROM PUBLIC._CUSTOMERS_ WHERE _CUSTOMERS_._CUSTOMERNUMBER_ = ?",
            compliedQueryString.replace('\"', '_'));

    assertEquals(0, compiledQuery.getActiveLeases());
    assertEquals(0, compiledQuery.getIdleLeases());

    ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
    final CountDownLatch latch = new CountDownLatch(threadCount);
    final List<Throwable> errors = new ArrayList<Throwable>();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                for (int i = 0; i < noOfCallsPerThreads; i++) {
                    final DataSet dataSet = dataContext.executeQuery(compiledQuery, new Object[] { 103 });
                    try {
                        assertTrue(dataSet.next());
                        Row row = dataSet.getRow();
                        assertNotNull(row);
                        assertEquals("Atelier graphique", row.getValue(0).toString());
                        assertFalse(dataSet.next());
                    } finally {
                        dataSet.close();
                    }
                }
            } catch (Throwable e) {
                errors.add(e);
            } finally {
                latch.countDown();
            }
        }
    };

    for (int i = 0; i < threadCount; i++) {
        executorService.execute(runnable);
    }

    try {
        latch.await(60000, TimeUnit.MILLISECONDS);

        if (errors.size() > 0) {
            throw new IllegalStateException(errors.get(0));
        }
        assertTrue(true);
    } finally {
        executorService.shutdownNow();
    }

    assertEquals(0, compiledQuery.getActiveLeases());

    compiledQuery.close();

    assertEquals(0, compiledQuery.getActiveLeases());
    assertEquals(0, compiledQuery.getIdleLeases());
}

From source file:org.apache.metamodel.jdbc.JdbcUpdateCallbackTest.java

@Test
public void testTransactionalUpdateScripts() throws Exception {
    DerbyTest.initDerbySettings();//from  w  w  w .j  a v  a 2s .c o m

    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    dataSource.setUrl("jdbc:derby:target/temp_derby;create=true");
    dataSource.setInitialSize(10);
    dataSource.setMaxActive(10);
    dataSource.setMaxWait(10000);
    dataSource.setMinEvictableIdleTimeMillis(1800000);
    dataSource.setMinIdle(0);
    dataSource.setMaxIdle(10);
    dataSource.setNumTestsPerEvictionRun(3);
    dataSource.setTimeBetweenEvictionRunsMillis(-1);
    dataSource.setDefaultTransactionIsolation(ISOLATION_LEVEL);

    final String tableName = "counter_table";
    final String columnName = "n";
    final JdbcDataContext dataContext = new JdbcDataContext(dataSource);
    dataContext.executeUpdate(new UpdateScript() {
        @Override
        public void run(UpdateCallback callback) {
            if (dataContext.getTableByQualifiedLabel(tableName) != null) {
                callback.dropTable(tableName).execute();
            }
            callback.createTable(dataContext.getDefaultSchema(), tableName).withColumn(columnName)
                    .ofType(ColumnType.INTEGER).execute();
        }
    });

    final Table table = dataContext.getTableByQualifiedLabel(tableName);
    final Column col = table.getColumnByName(columnName);
    assertNotNull(col);

    // insert one record - this one record will be updated transactionally below
    dataContext.executeUpdate(new InsertInto(table).value(columnName, 0));

    final UpdateScript updateScript = new UpdateScript() {
        @Override
        public void run(UpdateCallback callback) {
            final int n = getCounterValue(callback.getDataContext(), table, col);
            callback.update(table).value(col, n + 1).execute();
        }
    };

    final int threadCount = 2;
    final int iterationsPerThread = 5;

    final Thread[] threads = new Thread[threadCount];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread() {
            @Override
            public void run() {
                for (int j = 0; j < iterationsPerThread; j++) {
                    int retries = 10;
                    while (retries > 0) {
                        try {
                            dataContext.executeUpdate(updateScript);
                            retries = 0;
                        } catch (RolledBackUpdateException e) {
                            retries--;
                            if (retries == 0) {
                                throw e;
                            }
                        }
                    }
                }
            }
        };
    }
    for (Thread thread : threads) {
        thread.start();
    }
    for (Thread thread : threads) {
        thread.join();
    }

    assertEquals(threadCount * iterationsPerThread, getCounterValue(dataContext, table, col));
}

From source file:org.apache.synapse.commons.datasource.factory.DataSourceFactory.java

/**
 * Factory method to create a DataSource based on provided information
 * which is encapsulated in the DataSourceInformation object.
 *
 * @param dataSourceInformation Information about DataSource
 * @return DataSource Instance if one can be created ,
 *         otherwise null or exception if provided details are not valid or enough to create
 *         a DataSource/*from ww w  .j  a  v a2s.  c  o m*/
 */
public static DataSource createDataSource(DataSourceInformation dataSourceInformation) {

    String dsType = dataSourceInformation.getType();
    String driver = dataSourceInformation.getDriver();

    if (driver == null || "".equals(driver)) {
        handleException("Database driver class name cannot be found.");
    }

    String url = dataSourceInformation.getUrl();

    if (url == null || "".equals(url)) {
        handleException("Database connection URL cannot be found.");
    }

    String user = dataSourceInformation.getSecretInformation().getUser();
    String password = dataSourceInformation.getSecretInformation().getResolvedSecret();

    int defaultTransactionIsolation = dataSourceInformation.getDefaultTransactionIsolation();

    if (DataSourceInformation.BASIC_DATA_SOURCE.equals(dsType)) {

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(driver);
        basicDataSource.setUrl(url);

        if (user != null && !"".equals(user)) {
            basicDataSource.setUsername(user);
        }

        if (password != null && !"".equals(password)) {
            basicDataSource.setPassword(password);
        }

        basicDataSource.setMaxActive(dataSourceInformation.getMaxActive());
        basicDataSource.setMaxIdle(dataSourceInformation.getMaxIdle());
        basicDataSource.setMaxWait(dataSourceInformation.getMaxWait());
        basicDataSource.setMinIdle(dataSourceInformation.getMinIdle());
        basicDataSource.setDefaultAutoCommit(dataSourceInformation.isDefaultAutoCommit());
        basicDataSource.setDefaultReadOnly(dataSourceInformation.isDefaultReadOnly());
        basicDataSource.setTestOnBorrow(dataSourceInformation.isTestOnBorrow());
        basicDataSource.setTestOnReturn(dataSourceInformation.isTestOnReturn());
        basicDataSource.setTestWhileIdle(dataSourceInformation.isTestWhileIdle());
        basicDataSource.setMinEvictableIdleTimeMillis(dataSourceInformation.getMinEvictableIdleTimeMillis());
        basicDataSource
                .setTimeBetweenEvictionRunsMillis(dataSourceInformation.getTimeBetweenEvictionRunsMillis());
        basicDataSource.setNumTestsPerEvictionRun(dataSourceInformation.getNumTestsPerEvictionRun());
        basicDataSource.setMaxOpenPreparedStatements(dataSourceInformation.getMaxOpenPreparedStatements());
        basicDataSource.setAccessToUnderlyingConnectionAllowed(
                dataSourceInformation.isAccessToUnderlyingConnectionAllowed());
        basicDataSource.setInitialSize(dataSourceInformation.getInitialSize());
        basicDataSource.setPoolPreparedStatements(dataSourceInformation.isPoolPreparedStatements());

        if (defaultTransactionIsolation != -1) {
            basicDataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
        }

        String defaultCatalog = dataSourceInformation.getDefaultCatalog();
        if (defaultCatalog != null && !"".equals(defaultCatalog)) {
            basicDataSource.setDefaultCatalog(defaultCatalog);
        }

        String validationQuery = dataSourceInformation.getValidationQuery();

        if (validationQuery != null && !"".equals(validationQuery)) {
            basicDataSource.setValidationQuery(validationQuery);
        }

        return basicDataSource;

    } else if (DataSourceInformation.PER_USER_POOL_DATA_SOURCE.equals(dsType)) {

        DriverAdapterCPDS adapterCPDS = new DriverAdapterCPDS();

        try {
            adapterCPDS.setDriver(driver);
        } catch (ClassNotFoundException e) {
            handleException("Error setting driver : " + driver + " in DriverAdapterCPDS", e);
        }

        adapterCPDS.setUrl(url);

        if (user != null && !"".equals(user)) {
            adapterCPDS.setUser(user);
        }

        if (password != null && !"".equals(password)) {
            adapterCPDS.setPassword(password);
        }

        adapterCPDS.setPoolPreparedStatements(dataSourceInformation.isPoolPreparedStatements());
        adapterCPDS.setMaxIdle(dataSourceInformation.getMaxIdle());

        PerUserPoolDataSource perUserPoolDataSource = new PerUserPoolDataSource();
        perUserPoolDataSource.setConnectionPoolDataSource(adapterCPDS);

        perUserPoolDataSource.setDefaultMaxActive(dataSourceInformation.getMaxActive());
        perUserPoolDataSource.setDefaultMaxIdle(dataSourceInformation.getMaxIdle());
        perUserPoolDataSource.setDefaultMaxWait((int) dataSourceInformation.getMaxWait());
        perUserPoolDataSource.setDefaultAutoCommit(dataSourceInformation.isDefaultAutoCommit());
        perUserPoolDataSource.setDefaultReadOnly(dataSourceInformation.isDefaultReadOnly());
        perUserPoolDataSource.setTestOnBorrow(dataSourceInformation.isTestOnBorrow());
        perUserPoolDataSource.setTestOnReturn(dataSourceInformation.isTestOnReturn());
        perUserPoolDataSource.setTestWhileIdle(dataSourceInformation.isTestWhileIdle());
        perUserPoolDataSource
                .setMinEvictableIdleTimeMillis((int) dataSourceInformation.getMinEvictableIdleTimeMillis());
        perUserPoolDataSource.setTimeBetweenEvictionRunsMillis(
                (int) dataSourceInformation.getTimeBetweenEvictionRunsMillis());
        perUserPoolDataSource.setNumTestsPerEvictionRun(dataSourceInformation.getNumTestsPerEvictionRun());

        if (defaultTransactionIsolation != -1) {
            perUserPoolDataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
        }

        String validationQuery = dataSourceInformation.getValidationQuery();

        if (validationQuery != null && !"".equals(validationQuery)) {
            perUserPoolDataSource.setValidationQuery(validationQuery);
        }

        return perUserPoolDataSource;

    } else {
        handleException("Unsupported DataSource : " + dsType);
    }
    return null;
}

From source file:org.datacleaner.connection.JdbcDatastore.java

public DataSource createDataSource() {
    initializeDriver();/* w w  w  .  j av  a 2s.c o  m*/

    BasicDataSource ds = new BasicDataSource();
    ds.setDefaultAutoCommit(false);
    ds.setUrl(_jdbcUrl);

    ds.setMaxActive(getSystemPropertyValue(SYSTEM_PROPERTY_CONNECTION_POOL_MAX_SIZE, -1));
    ds.setMinEvictableIdleTimeMillis(
            getSystemPropertyValue(SYSTEM_PROPERTY_CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME_MILLIS, 500));
    ds.setTimeBetweenEvictionRunsMillis(
            getSystemPropertyValue(SYSTEM_PROPERTY_CONNECTION_POOL_TIME_BETWEEN_EVICTION_RUNS_MILLIS, 1000));

    if (_username != null && _password != null) {
        ds.setUsername(_username);
        ds.setPassword(_password);
    }
    return ds;
}

From source file:org.geosde.core.jdbc.data.datasource.DataSourceUtil.java

/**
 * Builds up a default DBCP DataSource that easy to use connection factories
 * can use to setup a connection pool.//from  w  ww  .  j  a  v  a  2s. com
 * 
 * @param url
 *            the jdbc url
 * @param driverName
 *            the jdbc driver full qualified class name
 * @param username
 * @param password
 * @param maxActive maximum number of concurrent connections in the pool
 * @param minIdle minimum number of concurrent connections in the pool
 * @param validationQuery
 *            the validation query to be used for connection liveliness on
 *            borrow, or null, if no check is to be performed
 * @param cachePreparedStatements
 *            wheter to cache prepared statements or not
 * @return
 * @throws DataSourceException
 */
public static ManageableDataSource buildDefaultDataSource(String url, String driverName, String username,
        String password, int maxActive, int minIdle, String validationQuery, boolean cachePreparedStatements,
        int removeAbandonedTimeout) throws DataSourceException {
    // basics
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverName);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setAccessToUnderlyingConnectionAllowed(true);

    // pool size
    dataSource.setMaxActive(maxActive);
    dataSource.setMinIdle(minIdle);

    // pool eviction settings
    dataSource.setMinEvictableIdleTimeMillis(1000 * 20);
    dataSource.setTimeBetweenEvictionRunsMillis(1000 * 10);

    // connection validation
    if (validationQuery != null) {
        dataSource.setTestOnBorrow(true);
        dataSource.setValidationQuery(validationQuery);
    }

    // prepared statement cache
    if (cachePreparedStatements) {
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxOpenPreparedStatements(10);
    }

    // remove abandoned connections (I know it's deprecated, but we do want
    // something shaving off lost connections. Let's give them 5 minutes of 
    // continuous usage
    if (removeAbandonedTimeout > 0) {
        dataSource.setRemoveAbandoned(true);
        dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        dataSource.setLogAbandoned(true);
    }

    Connection conn = null;
    try {
        conn = dataSource.getConnection();
    } catch (Exception e) {
        throw new DataSourceException("Connection test failed ", e);
    } finally {
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException e) {
            }
    }

    return new DBCPDataSource(dataSource);
}

From source file:org.geosde.core.jdbc.JDBCDataStoreFactory.java

/**
 * DataSource access allowing SQL use: intended to allow client code to query available schemas.
 * <p>/*from  ww  w . j  a  v a2 s .  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 (on embedded dbs it can be optional)
    String user = (String) USER.lookUp(params);
    if (user != null) {
        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());
    }

    Boolean testWhileIdle = (Boolean) TEST_WHILE_IDLE.lookUp(params);
    if (testWhileIdle != null) {
        dataSource.setTestWhileIdle(testWhileIdle);
    }

    Integer timeBetweenEvictorRuns = (Integer) TIME_BETWEEN_EVICTOR_RUNS.lookUp(params);
    if (timeBetweenEvictorRuns != null && timeBetweenEvictorRuns > 0) {
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictorRuns * 1000l);
    }

    Integer minEvictableTime = (Integer) MIN_EVICTABLE_TIME.lookUp(params);
    if (minEvictableTime != null) {
        dataSource.setMinEvictableIdleTimeMillis(minEvictableTime * 1000l);
    }

    Integer evictorTestsPerRun = (Integer) EVICTOR_TESTS_PER_RUN.lookUp(params);
    if (evictorTestsPerRun != null) {
        dataSource.setNumTestsPerEvictionRun(evictorTestsPerRun);
    }

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

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

/**
 * ???//from  w w w . j  av a 2  s .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.pinus4j.cluster.impl.AppDBClusterImpl.java

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

    LOG.info(dbConnInfo.toString());/*from  ww w  .j av  a  2 s . co  m*/

    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 .  jav  a2 s .  co 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;
    }

}