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

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

Introduction

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

Prototype

public synchronized void setInitialSize(int initialSize) 

Source Link

Document

Sets the initial size of the connection pool.

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

Usage

From source file:com.github.akiraly.db4j.pool.DbcpUtils.java

public static BasicDataSource newDefaultDS() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDefaultAutoCommit(false);

    dataSource.setDefaultQueryTimeout(1);
    dataSource.setValidationQueryTimeout(1);
    dataSource.setMaxWaitMillis(5000);//from  w ww  .  j  ava2s  .c o m

    dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    dataSource.setInitialSize(4);
    dataSource.setMinIdle(4);
    dataSource.setMaxIdle(8);
    dataSource.setMaxTotal(16);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setMaxOpenPreparedStatements(128);
    return dataSource;
}

From source file:dgw.mt940.db.util.DGWBasicDataSource.java

public static DataSource setupDataSource(String connectURI, String driver, String userName, String password,
        String removeAbandoned, String initSize, String mxSize) {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driver);/*from  w w w. ja  v a  2 s .co  m*/
    ds.setUrl(connectURI);
    ds.setUsername(userName);
    ds.setPassword(password);
    ds.setUrl(connectURI);
    ds.setAbandonedUsageTracking(Boolean.getBoolean(removeAbandoned));
    ds.setInitialSize(Integer.parseInt(initSize));
    ds.setMaxIdle(Integer.parseInt(mxSize));
    return ds;
}

From source file:com.tukaloff.customers.Config.java

@Bean
public BasicDataSource dataSource() {
    BasicDataSource dbcp = new BasicDataSource();
    dbcp.setDriverClassName("com.mysql.jdbc.Driver");
    dbcp.setInitialSize(5);
    dbcp.setMaxIdle(10);//from  w w w . j  av a  2s.c o  m
    return dbcp;
}

From source file:co.id.ipb.ilkom.training.db.SpringDataJpaConfiguration.java

@Bean
DataSource dataSource() {/*from ww w .j  av  a 2s. c om*/
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mysql://localhost:3306/trainingjava");
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    dataSource.setInitialSize(20);
    dataSource.setMaxIdle(20);
    dataSource.setMaxTotal(100);
    return dataSource;
}

From source file:com.mycompany.configuration.SpringDateConfigMySQL.java

@Bean
//? ? // ww  w.  j  ava  2s. c o  m
public DataSource dataSource() {
    //MySQL
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    //? 
    ds.setUrl("jdbc:mysql://localhost:3306/dateexam");
    ds.setUsername("root");
    ds.setPassword("root");
    /* ds.setUsername("exam");
    ds.setPassword("exam68");*/
    //
    ds.setInitialSize(5);
    ds.setMaxIdle(5);
    ds.setMaxTotal(15);

    return ds;
}

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

/**
 * Parses the ds.//  w w  w .j  av a2s.  c o m
 */
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: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   w  w  w .j  av  a 2 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;
}

From source file:org.lib4j.dbcp.DataSources.java

/**
 * Create a <code>BasicDataSource</code> given a dbcp JAXB binding.
 *
 * @param dbcp JAXB dbcp binding.//ww  w  .ja  va 2s  .  co  m
 * @param driverClassLoader Class loader to be used to load the JDBC driver.
 * @return the <code>BasicDataSource</code> instance.
 * @throws SQLException If a database access error occurs.
 */
public static BasicDataSource createDataSource(final Dbcp dbcp, final ClassLoader driverClassLoader)
        throws SQLException {
    final BasicDataSource dataSource = new BasicDataSource();

    final Dbcp.Jdbc jdbc = dbcp.getJdbc();
    dataSource.setDriverClassName(jdbc.getDriverClassName());
    dataSource.setDriverClassLoader(driverClassLoader);

    dataSource.setUrl(jdbc.getUrl());

    dataSource.setUsername(jdbc.getUsername());
    dataSource.setPassword(jdbc.getPassword());

    final Dbcp.Default _default = dbcp.getDefault();
    if (_default != null && _default.getCatalog() != null)
        dataSource.setDefaultCatalog(_default.getCatalog());

    dataSource.setDefaultAutoCommit(
            _default == null || _default.getAutoCommit() == null || _default.getAutoCommit());
    dataSource.setDefaultReadOnly(_default != null && _default.getReadOnly() != null && _default.getReadOnly());
    if (_default != null && _default.getQueryTimeout() != null)
        dataSource.setDefaultQueryTimeout(_default.getQueryTimeout());

    if (_default != null && _default.getTransactionIsolation() != null) {
        if ("NONE".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        else if ("READ_COMMITTED".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        else if ("READ_UNCOMMITTED".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        else if ("REPEATABLE_READ".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        else if ("SERIALIZABLE".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        else
            throw new UnsupportedOperationException(
                    "Unsupported transaction isolation: " + _default.getTransactionIsolation());
    }

    final Dbcp.Connection connection = dbcp.getConnection();
    if (connection != null) {
        if (connection.getProperties() != null)
            for (final Dbcp.Connection.Properties.Property property : connection.getProperties().getProperty())
                if (property.getName() != null && property.getValue() != null)
                    dataSource.addConnectionProperty(property.getName(), property.getValue());

        if (connection.getInitSqls() != null) {
            final List<String> initSqls = new ArrayList<>();
            for (final String initSql : connection.getInitSqls().getInitSql())
                initSqls.add(initSql);

            dataSource.setConnectionInitSqls(initSqls);
        }
    }

    final Dbcp.Size size = dbcp.getSize();
    dataSource.setInitialSize(size == null || size.getInitialSize() == null ? 0 : size.getInitialSize());
    dataSource.setMaxTotal(size == null || size.getMaxTotal() == null ? 8
            : INDEFINITE.equals(size.getMaxTotal()) ? -1 : Integer.parseInt(size.getMaxTotal()));
    dataSource.setMaxIdle(size == null || size.getMaxIdle() == null ? 8
            : INDEFINITE.equals(size.getMaxIdle()) ? -1 : Integer.parseInt(size.getMaxIdle()));
    dataSource.setMinIdle(size == null || size.getMinIdle() == null ? 9 : size.getMinIdle());
    if (size == null || size.getMaxOpenPreparedStatements() == null
            || INDEFINITE.equals(size.getMaxOpenPreparedStatements())) {
        dataSource.setPoolPreparedStatements(false);
    } else {
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxOpenPreparedStatements(Integer.parseInt(size.getMaxOpenPreparedStatements()));
    }

    final Dbcp.Pool pool = dbcp.getPool();
    if (pool == null || pool.getQueue() == null || "lifo".equals(pool.getQueue()))
        dataSource.setLifo(true);
    else if ("fifo".equals(pool.getQueue()))
        dataSource.setLifo(false);
    else
        throw new UnsupportedOperationException("Unsupported queue spec: " + pool.getQueue());

    dataSource.setCacheState(pool != null && pool.getCacheState() != null && pool.getCacheState());
    dataSource.setMaxWaitMillis(
            pool == null || pool.getMaxWait() != null || INDEFINITE.equals(pool.getMaxWait()) ? -1
                    : Long.parseLong(pool.getMaxWait()));
    dataSource.setMaxConnLifetimeMillis(pool == null || pool.getMaxConnectionLifetime() == null
            || INDEFINITE.equals(pool.getMaxConnectionLifetime()) ? 0
                    : Long.parseLong(pool.getMaxConnectionLifetime()));
    dataSource.setEnableAutoCommitOnReturn(_default == null || pool.getEnableAutoCommitOnReturn() == null
            || pool.getEnableAutoCommitOnReturn());
    dataSource.setRollbackOnReturn(
            pool == null || pool.getRollbackOnReturn() == null || pool.getRollbackOnReturn());
    if (pool != null && pool.getRemoveAbandoned() != null) {
        if ("borrow".equals(pool.getRemoveAbandoned().getOn()))
            dataSource.setRemoveAbandonedOnBorrow(true);
        else if ("maintenance".equals(pool.getRemoveAbandoned().getOn()))
            dataSource.setRemoveAbandonedOnMaintenance(true);
        else
            throw new UnsupportedOperationException(
                    "Unsupported remove abandoned spec: " + pool.getRemoveAbandoned().getOn());

        dataSource.setRemoveAbandonedTimeout(pool.getRemoveAbandoned().getTimeout());
    }

    dataSource.setAbandonedUsageTracking(
            pool != null && pool.getAbandonedUsageTracking() != null && pool.getAbandonedUsageTracking());
    dataSource.setAccessToUnderlyingConnectionAllowed(
            pool != null && pool.getAllowAccessToUnderlyingConnection() != null
                    && pool.getAllowAccessToUnderlyingConnection());

    final Dbcp.Pool.Eviction evictor = pool != null && pool.getEviction() != null ? pool.getEviction() : null;
    if (evictor != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(evictor.getTimeBetweenRuns());
        dataSource.setNumTestsPerEvictionRun(evictor.getNumTestsPerRun());
        dataSource.setMinEvictableIdleTimeMillis(
                evictor.getMinIdleTime() == null ? 1800000 : evictor.getMinIdleTime());
        dataSource.setSoftMinEvictableIdleTimeMillis(
                evictor.getSoftMinIdleTime() == null || INDEFINITE.equals(evictor.getSoftMinIdleTime()) ? -1
                        : Long.parseLong(evictor.getSoftMinIdleTime()));
        if (evictor.getPolicyClassName() != null)
            dataSource.setEvictionPolicyClassName(evictor.getPolicyClassName());
    }

    final Dbcp.Validation validation = dbcp.getValidation();
    if (validation != null && validation.getQuery() != null)
        dataSource.setValidationQuery(validation.getQuery());

    dataSource.setTestOnBorrow(
            validation == null || validation.getTestOnBorrow() == null || validation.getTestOnBorrow());
    dataSource.setTestOnReturn(
            validation != null && validation.getTestOnReturn() != null && validation.getTestOnReturn());
    dataSource.setTestWhileIdle(
            validation != null && validation.getTestWhileIdle() != null && validation.getTestWhileIdle());
    if (validation != null && validation.getFastFail() != null) {
        dataSource.setFastFailValidation(true);
        if (validation.getFastFail().getDisconnectionSqlCodes() != null)
            dataSource.setDisconnectionSqlCodes(
                    Arrays.asList(validation.getFastFail().getDisconnectionSqlCodes().split(" ")));
    }

    final Dbcp.Logging logging = dbcp.getLogging();
    if (logging != null) {
        final Logger logger = LoggerFactory.getLogger(DataSources.class);
        final LoggerPrintWriter loggerPrintWriter = new LoggerPrintWriter(logger,
                Level.valueOf(logging.getLevel().toString()));
        dataSource.setLogWriter(loggerPrintWriter);
        dataSource.setLogExpiredConnections(logging.isLogExpiredConnections());
        if (logging.isLogAbandoned()) {
            dataSource.setAbandonedLogWriter(loggerPrintWriter);
            dataSource.setLogAbandoned(true);
        }
    }

    return dataSource;
}

From source file:org.libx4j.dbcp.DataSources.java

public static BasicDataSource createDataSource(final $dbcp_dbcp dbcp) throws SQLException {
    if (dbcp.isNull())
        throw new BindingRuntimeException("/dbcp:jdbc is missing");

    final dbcp_dbcp._jdbc jdbc = dbcp._jdbc(0);
    final BasicDataSource dataSource = new BasicDataSource() {
        @Override/*from   w w w.  j  a v a  2 s.  c om*/
        public Connection getConnection() throws SQLException {
            //        try {
            return super.getConnection();
            //        }
            //        catch (final SQLException e) {
            //          // TODO: Finish this!
            //          if ("Cannot get a connection, pool error Timeout waiting for idle object".equals(e.getMessage()))
            //            Throwables.set(e, "XX" + e.getMessage());
            //
            //          throw e;
            //        }
        }
    };

    if (jdbc._driverClassName(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:driverClassName is missing");

    dataSource.setDriverClassName(jdbc._driverClassName(0).text());

    //    if (jdbc._loginTimeout() != null && jdbc._loginTimeout().size() != 0 && jdbc._loginTimeout(0).text() != null) {
    // FIXME: This causes a ClassNotFoundException: com.sybase.jdbc3.jdbc.SybDriver
    //      try {
    //        dataSource.setLoginTimeout(jdbc._loginTimeout(0).text());
    //      }
    //      catch(final SQLException e) {
    //        throw new SQLException(e);
    //      }
    //  }

    if (jdbc._url(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:url is missing");

    dataSource.setUrl(jdbc._url(0).text());

    if (jdbc._username(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:username is missing");

    dataSource.setUsername(jdbc._username(0).text());

    if (jdbc._password(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:password is missing");

    dataSource.setPassword(jdbc._password(0).text());
    final dbcp_dbcp._default defaults = dbcp._default(0);
    if (!defaults._connectionProperties(0).isNull())
        for (final dbcp_dbcp._default._connectionProperties._property property : defaults
                ._connectionProperties(0)._property())
            if (property._name$() != null && property._name$().text() != null && property._value$() != null
                    && property._value$().text() != null)
                dataSource.addConnectionProperty(property._name$().text(), property._value$().text());

    if (!defaults._autoCommit(0).isNull())
        dataSource.setDefaultAutoCommit(defaults._autoCommit(0).text());

    if (!defaults._readOnly(0).isNull())
        dataSource.setDefaultReadOnly(defaults._readOnly(0).text());

    if (!defaults._transactionIsolation(0).isNull()) {
        if (dbcp_dbcp._default._transactionIsolation.NONE.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        else if (dbcp_dbcp._default._transactionIsolation.READ_5FCOMMITTED.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        else if (dbcp_dbcp._default._transactionIsolation.READ_5FUNCOMMITTED.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        else if (dbcp_dbcp._default._transactionIsolation.REPEATABLE_5FREAD.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        else if (dbcp_dbcp._default._transactionIsolation.SERIALIZABLE.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        else
            throw new UnsupportedOperationException(
                    "Unsupported transaction isolation: " + defaults._transactionIsolation(0).text());
    }

    final dbcp_dbcp._size size = dbcp._size(0);
    if (!size.isNull()) {
        if (!size._initialSize(0).isNull())
            dataSource.setInitialSize(size._initialSize(0).text().intValue());

        if (!size._maxActive(0).isNull())
            dataSource.setMaxTotal(size._maxActive(0).text().intValue());

        if (!size._maxIdle(0).isNull())
            dataSource.setMaxIdle(size._maxIdle(0).text().intValue());

        if (!size._minIdle(0).isNull())
            dataSource.setMinIdle(size._minIdle(0).text().intValue());

        if (!size._maxWait(0).isNull())
            dataSource.setMaxWaitMillis(size._maxWait(0).text().intValue());
    }

    final dbcp_dbcp._management management = dbcp._management(0);
    if (!management.isNull()) {
        if (!management._validationQuery(0).isNull())
            dataSource.setValidationQuery(management._validationQuery(0).text());

        if (!management._testOnBorrow(0).isNull())
            dataSource.setTestOnBorrow(management._testOnBorrow(0).text());

        if (!management._testOnReturn(0).isNull())
            dataSource.setTestOnReturn(management._testOnReturn(0).text());

        if (!management._testWhileIdle(0).isNull())
            dataSource.setTestWhileIdle(management._testWhileIdle(0).text());

        if (!management._timeBetweenEvictionRuns(0).isNull())
            dataSource
                    .setTimeBetweenEvictionRunsMillis(management._timeBetweenEvictionRuns(0).text().intValue());

        if (!management._numTestsPerEvictionRun(0).isNull())
            dataSource.setNumTestsPerEvictionRun(management._numTestsPerEvictionRun(0).text().intValue());

        if (!management._minEvictableIdleTime(0).isNull())
            dataSource.setMinEvictableIdleTimeMillis(management._minEvictableIdleTime(0).text().intValue());
    }

    final dbcp_dbcp._preparedStatements preparedStatements = dbcp._preparedStatements(0);
    if (!preparedStatements.isNull()) {
        if (!preparedStatements._poolPreparedStatements(0).isNull())
            dataSource.setPoolPreparedStatements(preparedStatements._poolPreparedStatements(0).text());

        if (!preparedStatements._maxOpenPreparedStatements(0).isNull())
            dataSource.setMaxOpenPreparedStatements(
                    preparedStatements._maxOpenPreparedStatements(0).text().intValue());
    }

    final dbcp_dbcp._removal removal = dbcp._removal(0);
    if (!removal.isNull()) {
        if (!removal._removeAbandoned(0).isNull())
            dataSource.setRemoveAbandonedOnBorrow(removal._removeAbandoned(0).text());

        if (!removal._removeAbandonedTimeout(0).isNull())
            dataSource.setRemoveAbandonedTimeout(removal._removeAbandonedTimeout(0).text().intValue());

        if (!removal._logAbandoned(0).isNull())
            dataSource.setLogAbandoned(removal._logAbandoned(0).text());
    }

    final dbcp_dbcp._logging logging = dbcp._logging(0);
    if (!logging.isNull()) {
        final Logger logger = LoggerFactory.getLogger(DataSources.class);
        final LoggerPrintWriter loggerPrintWriter = new LoggerPrintWriter(logger,
                Level.valueOf(logging._level(0).text()));
        dataSource.setLogWriter(loggerPrintWriter);
        dataSource.setLogExpiredConnections(
                !logging._logExpiredConnections(0).isNull() && logging._logExpiredConnections(0).text());
        if (!logging._logAbandoned(0).isNull() && logging._logAbandoned(0).text()) {
            dataSource.setAbandonedLogWriter(loggerPrintWriter);
            dataSource.setLogAbandoned(true);
        }
    }

    return dataSource;
}

From source file:org.mingle.pear.config.DataAccessJpaConfig.java

@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(propDatabase.getDriverClassName());
    dataSource.setUrl(propDatabase.getUrl());
    dataSource.setUsername(propDatabase.getUsername());
    dataSource.setPassword(propDatabase.getPassword());
    dataSource.setInitialSize(5);
    dataSource.setTestOnBorrow(true);/* www . j  a va2  s .  c om*/
    dataSource.setTestOnReturn(true);
    dataSource.setTestWhileIdle(true);
    dataSource.setTimeBetweenEvictionRunsMillis(1800000L);
    dataSource.setNumTestsPerEvictionRun(3);
    dataSource.setMinEvictableIdleTimeMillis(1800000L);
    return dataSource;
}