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

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

Introduction

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

Prototype

BasicDataSource

Source Link

Usage

From source file:cn.newgxu.lab.core.config.SpringBeans.java

@Bean(destroyMethod = "close")
public DataSource dataSource() {
    Properties props = new Properties();
    InputStream in = null;//www  . ja v  a2  s  . co  m
    try {
        in = this.getClass().getResourceAsStream("/config/dataSource.properties");
        props.load(in);
    } catch (IOException e) {
        L.error("????", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            L.error("wtf!", e);
        }
    }
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(props.getProperty("db.driver"));
    dataSource.setUrl(props.getProperty("db.url"));
    dataSource.setUsername(props.getProperty("db.username"));
    dataSource.setPassword(props.getProperty("db.password"));
    dataSource.setDefaultAutoCommit(false);
    return dataSource;
}

From source file:com.agiletec.ConfigTestUtils.java

private void createDatasource(String dsNameControlKey, SimpleNamingContextBuilder builder,
        Properties testConfig) {//w w w  .  j  av  a  2 s  .c om
    String beanName = testConfig.getProperty("jdbc." + dsNameControlKey + ".beanName");
    try {
        String className = testConfig.getProperty("jdbc." + dsNameControlKey + ".driverClassName");
        String url = testConfig.getProperty("jdbc." + dsNameControlKey + ".url");
        String username = testConfig.getProperty("jdbc." + dsNameControlKey + ".username");
        String password = testConfig.getProperty("jdbc." + dsNameControlKey + ".password");
        Class.forName(className);
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setMaxActive(8);
        ds.setMaxIdle(4);
        ds.setDriverClassName(className);
        builder.bind("java:comp/env/jdbc/" + beanName, ds);
    } catch (Throwable t) {
        throw new RuntimeException("Error on creation datasource '" + beanName + "'", t);
    }
}

From source file:com.dangdang.ddframe.rdb.sharding.config.yaml.YamlShardingDataSourceTest.java

private DataSource createDataSource() {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(Driver.class.getName());
    result.setUrl("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL");
    result.setUsername("sa");
    result.setPassword("");
    return result;
}

From source file:info.jtrac.config.DataSourceFactoryBean.java

/**
 * This method returns the dataSource object used for the DB access.
 *
 * @throws Exception/*from w  w w.  java 2  s  .co m*/
 * @see org.springframework.beans.factory.FactoryBean#getObject()
 */
@Override
public DataSource getObject() throws Exception {
    if (StringUtils.hasText(dataSourceJndiName)) {
        logger.info("JNDI datasource requested, looking up datasource from JNDI name: '" + dataSourceJndiName
                + "'");
        JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
        factoryBean.setJndiName(dataSourceJndiName);

        // "java:comp/env/" will be prefixed if the JNDI name doesn't already have it
        factoryBean.setResourceRef(true);

        // This step actually does the JNDI lookup
        try {
            factoryBean.afterPropertiesSet();
        } catch (Exception e) {
            logger.error("datasource init from JNDI failed : " + e);
            logger.error("aborting application startup");
            throw new RuntimeException(e);
        } // end try..catch

        dataSource = (DataSource) factoryBean.getObject();
    } else if (url.startsWith("jdbc:hsqldb:file")) {
        logger.info("embedded HSQLDB mode detected, switching on spring single connection data source");
        SingleConnectionDataSource ds = new SingleConnectionDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setSuppressClose(true);
        dataSource = ds;
    } else {
        logger.info(
                "Not using embedded HSQLDB or JNDI datasource, switching on Apache DBCP data source connection pooling");
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setValidationQuery(validationQuery);
        ds.setTestOnBorrow(false);
        ds.setTestWhileIdle(true);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        dataSource = ds;
    } // end if..else

    return dataSource;
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * //  www . ja  v a  2s .  c  o m
 *
 * @param doPreparedStatement 
 * @return time taken
 * @throws PropertyVetoException 
 * @throws InterruptedException 
 * @throws SQLException 
 */
private DataSource multiThreadedDBCP(boolean doPreparedStatement)
        throws PropertyVetoException, InterruptedException, SQLException {
    BasicDataSource cpds = new BasicDataSource();
    cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    cpds.setUrl(url);
    cpds.setUsername(username);
    cpds.setPassword(password);
    cpds.setMaxIdle(-1);
    cpds.setMinIdle(-1);
    if (doPreparedStatement) {
        cpds.setPoolPreparedStatements(true);
        cpds.setMaxOpenPreparedStatements(max_statement);
    }
    cpds.setInitialSize(pool_size);
    cpds.setMaxActive(pool_size);
    return cpds;
}

From source file:gxu.software_engineering.shen10.market.core.SpringBeans.java

@Bean(destroyMethod = "close")
public DataSource dataSource() {
    Properties props = new Properties();
    InputStream in = null;/*  w ww.  j  a v a  2 s .  com*/
    try {
        in = this.getClass().getResourceAsStream("/db/dataSource.properties");
        props.load(in);
    } catch (IOException e) {
        L.error("????", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            L.error("wtf!", e);
        }
    }
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(props.getProperty("db.driver"));
    dataSource.setUrl(props.getProperty("db.url"));
    dataSource.setUsername(props.getProperty("db.username"));
    dataSource.setPassword(props.getProperty("db.password"));
    dataSource.setDefaultAutoCommit(false);
    return dataSource;
}

From source file:com.devwebsphere.jdbc.loader.JDBCTxCallback.java

public synchronized static DataSource setupDataSource(String connectURI, String user, String password) {
    String key = connectURI + ":" + user + ":" + password;
    DataSource rc = dataSourceList.get(key);
    if (rc == null) {
        ///*from w  w  w .  j ava 2 s . c o m*/
        // First, 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.
        //

        BasicDataSource bds = new BasicDataSource();
        bds.setInitialSize(5);
        bds.setUrl(connectURI);
        bds.setUsername(user);
        bds.setPassword(password);
        bds.setPoolPreparedStatements(true);

        rc = bds;

        dataSourceList.put(key, bds);
    }
    return rc;
}

From source file:$.DataSourceConf.java

@Bean
    public DataSource dataSource() {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);/*from www  . j  a v  a2s  .  co  m*/
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setMaxActive(maxActive);
        dataSource.setMaxIdle(maxIdle);
        dataSource.setMaxWait(maxWait);
        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        dataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        dataSource.setRemoveAbandoned(removeAbandoned);
        dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        dataSource.setLogAbandoned(logAbandoned);
        return dataSource;
    }

From source file:com.bstek.dorado.core.store.SqlBaseStoreSupport.java

protected synchronized DataSource getDataSource() throws Exception {
    if (dataSource != null) {
        return dataSource;
    }//from   w  ww . ja v a 2  s .co m

    if (StringUtils.isBlank(namespace)) {
        throw new IllegalArgumentException("The namespace of store cannot be empty. ");
    }

    prepareNamespace();

    BasicDataSource pds = new BasicDataSource();
    dataSource = pds;

    pds.setDriverClassName(driverClassName);
    pds.setUrl(getConnectionUrl());
    pds.setUsername(username);
    pds.setPassword(password);
    pds.setDefaultCatalog(defaultCatalog);

    if (defaultAutoCommit != null) {
        pds.setDefaultAutoCommit(defaultAutoCommit.booleanValue());
    }
    if (defaultReadOnly != null) {
        pds.setDefaultReadOnly(defaultReadOnly.booleanValue());
    }
    if (defaultTransactionIsolation != null) {
        pds.setDefaultTransactionIsolation(defaultTransactionIsolation.intValue());
    }
    if (maxActive != null) {
        pds.setMaxActive(maxActive.intValue());
    }
    if (maxIdle != null) {
        pds.setMaxIdle(maxIdle.intValue());
    }
    if (minIdle != null) {
        pds.setMinIdle(minIdle.intValue());
    }
    if (initialSize != null) {
        pds.setInitialSize(initialSize.intValue());
    }
    if (maxWait != null) {
        pds.setMaxWait(maxWait.longValue());
    }
    if (timeBetweenEvictionRunsMillis != null) {
        pds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis.longValue());
    }
    if (minEvictableIdleTimeMillis != null) {
        pds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis.longValue());
    }
    return dataSource;
}

From source file:gobblin.metastore.MysqlStateStore.java

/**
 * creates a new {@link BasicDataSource}
 * @param config the properties used for datasource instantiation
 * @return// w ww .ja v  a2 s  .c  o  m
 */
public static BasicDataSource newDataSource(Config config) {
    BasicDataSource basicDataSource = new BasicDataSource();
    PasswordManager passwordManager = PasswordManager.getInstance(ConfigUtils.configToProperties(config));

    basicDataSource
            .setDriverClassName(ConfigUtils.getString(config, ConfigurationKeys.STATE_STORE_DB_JDBC_DRIVER_KEY,
                    ConfigurationKeys.DEFAULT_STATE_STORE_DB_JDBC_DRIVER));
    // MySQL server can timeout a connection so need to validate connections before use
    basicDataSource.setValidationQuery("select 1");
    basicDataSource.setTestOnBorrow(true);
    basicDataSource.setDefaultAutoCommit(false);
    basicDataSource.setTimeBetweenEvictionRunsMillis(60000);
    basicDataSource.setUrl(config.getString(ConfigurationKeys.STATE_STORE_DB_URL_KEY));
    basicDataSource.setUsername(
            passwordManager.readPassword(config.getString(ConfigurationKeys.STATE_STORE_DB_USER_KEY)));
    basicDataSource.setPassword(
            passwordManager.readPassword(config.getString(ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY)));
    basicDataSource.setMinEvictableIdleTimeMillis(
            ConfigUtils.getLong(config, ConfigurationKeys.STATE_STORE_DB_CONN_MIN_EVICTABLE_IDLE_TIME_KEY,
                    ConfigurationKeys.DEFAULT_STATE_STORE_DB_CONN_MIN_EVICTABLE_IDLE_TIME));

    return basicDataSource;
}