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

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

Introduction

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

Prototype

public synchronized void setDefaultAutoCommit(boolean defaultAutoCommit) 

Source Link

Document

Sets default auto-commit state of connections returned by this datasource.

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

Usage

From source file:com.pinterest.deployservice.db.DatabaseUtil.java

/**
 * Create a MySQL datasource.//  w w  w  .j  a v  a  2  s  .  co m
 *
 * @param url             the url of the DB.
 * @param user            the user name to connect to MySQL as.
 * @param passwd          the password for the corresponding MySQL user.
 * @param poolSize        the connection pool size string, in the format of
 *                        initialSize:maxActive:maxIdle:minIdle.
 * @param maxWaitInMillis the max wait time in milliseconds to get a connection from the pool.
 * @return a BasicDataSource for the target MySQL instance.
 */
public static BasicDataSource createDataSource(String driverClassName, String url, String user, String passwd,
        String poolSize, int maxWaitInMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setDefaultReadOnly(false);

    // poolSize parsing, the poolsize string passed in the following format
    // initialSize:maxActive:maxIdle:minIdle
    String[] sizeStrs = poolSize.split(":");
    dataSource.setInitialSize(Integer.parseInt(sizeStrs[0]));
    dataSource.setMaxActive(Integer.parseInt(sizeStrs[1]));
    dataSource.setMaxIdle(Integer.parseInt(sizeStrs[2]));
    dataSource.setMinIdle(Integer.parseInt(sizeStrs[3]));

    dataSource.setValidationQuery("SELECT 1");
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    // dataSource.setNumTestsPerEvictionRun(3);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitInMillis);

    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format("Failed to get a db connection when creating DataSource, url = %s", url), e);
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return dataSource;
}

From source file:com.pinterest.pinlater.backends.mysql.MySQLDataSources.java

private static DataSource createDataSource(String host, int port, String user, String passwd, int poolSize,
        int maxWaitMillis, int socketTimeoutMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource//w w  w .  j  a  v a2s  .c om
            .setUrl(String.format(
                    "jdbc:mysql://%s:%d?" + "connectTimeout=5000&" + "socketTimeout=%d&"
                            + "enableQueryTimeouts=false&" + "cachePrepStmts=true&" + "characterEncoding=UTF-8",
                    host, port, socketTimeoutMillis));
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setInitialSize(poolSize);
    dataSource.setMaxActive(poolSize);
    dataSource.setMaxIdle(poolSize);
    // deal with idle connection eviction
    dataSource.setValidationQuery("SELECT 1 FROM DUAL");
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    dataSource.setNumTestsPerEvictionRun(poolSize);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitMillis);
    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format(
                "Failed to get a mysql connection when creating DataSource, " + "host: %s, port: %d", host,
                port), e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }
    return dataSource;
}

From source file:net.sf.taverna.t2.provenance.api.ProvenanceAccess.java

/**
 * Initialises a named JNDI DataSource if not already set up externally.
 * The DataSource is named jdbc/taverna//w ww  . ja  va2 s  . co  m
 *
 * @param driverClassName - the classname for the driver to be used.
 * @param jdbcUrl - the jdbc connection url
 * @param username - the username, if required (otherwise null)
 * @param password - the password, if required (oteherwise null)
 * @param minIdle - if the driver supports multiple connections, then the minumum number of idle connections in the pool
 * @param maxIdle - if the driver supports multiple connections, then the maximum number of idle connections in the pool
 * @param maxActive - if the driver supports multiple connections, then the minumum number of connections in the pool
 */
public static void initDataSource(String driverClassName, String jdbcUrl, String username, String password,
        int minIdle, int maxIdle, int maxActive) {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setMaxIdle(maxIdle);
    ds.setDefaultAutoCommit(true);
    if (username != null) {
        ds.setUsername(username);
    }
    if (password != null) {
        ds.setPassword(password);
    }

    ds.setUrl(jdbcUrl);

    InitialContext context;
    try {
        context = new InitialContext();
        context.rebind("jdbc/taverna", ds);
    } catch (NamingException ex) {
        logger.error("Problem rebinding the jdbc context: " + ex);
    }

}

From source file:gobblin.metastore.MysqlStateStore.java

/**
 * creates a new {@link BasicDataSource}
 * @param config the properties used for datasource instantiation
 * @return/*from w  w w . jav  a2 s.  com*/
 */
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;
}

From source file:com.openteach.diamond.repository.client.impl.database.DataSourceFactory.java

/**
 * /*ww w.  ja  v a 2  s .  co  m*/
 * @return
 */
public DataSource newInstance() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDefaultAutoCommit(true);
    dataSource.setDriverClassName(certificate.getDriverClassName());
    dataSource.setMaxActive(certificate.getMaxActive());
    dataSource.setMaxIdle(certificate.getMaxIdle());
    dataSource.setMaxWait(certificate.getMaxWait());
    dataSource.setMinIdle(certificate.getMinIdle());
    dataSource.setUsername(certificate.getUsername());
    dataSource.setPassword(certificate.getPassword());
    dataSource.setUrl(certificate.getUrl());
    return dataSource;
}

From source file:net.jetrix.DataSourceManager.java

/**
 * Configure a datasource.// w  w w.  j a v a2s  .  c  o  m
 *
 * @param config      the configuration of the datasource
 * @param environment the environment of the datasource
 */
public void setDataSource(DataSourceConfig config, String environment) {
    try {
        Class.forName(config.getDriver());
    } catch (ClassNotFoundException e) {
        log.warning("Unable to find the database driver (" + config.getDriver()
                + "), put the related jar in the lib directory");
        return;
    }

    try {
        // close the previous datasource if necessary
        if (datasources.containsKey(environment)) {
            BasicDataSource datasource = (BasicDataSource) datasources.get(environment);
            datasource.close();
        }

        BasicDataSource datasource = new BasicDataSource();
        datasource.setDefaultAutoCommit(false);

        datasource.setDriverClassName(config.getDriver());
        datasource.setUrl(config.getUrl());
        datasource.setUsername(config.getUsername());
        datasource.setPassword(config.getPassword());
        datasource.setMinIdle(config.getMinIdle() != 0 ? config.getMinIdle() : DEFAULT_MIN_IDLE);
        datasource.setMaxActive(config.getMaxActive() != 0 ? config.getMaxActive() : DEFAULT_MAX_ACTIVE);

        // attempts to open the connection
        datasource.getConnection().close();

        datasources.put(environment, datasource);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Unable to configure the datasource '" + environment + "'", e);
    }
}

From source file:com.googlecode.jdbcproc.daofactory.guice.SimpleModule.java

@Provides
@Singleton/* w w  w.j a v a 2 s . c o  m*/
DataSource provideDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/jdbcprocdb");
    dataSource.setUsername("jdbcproc");
    dataSource.setPassword("jdbcproc");
    dataSource.setDefaultAutoCommit(true);
    dataSource.setValidationQuery("call create_collections()");

    return dataSource;
}

From source file:com.stitchgalaxy.domain.spring.configuration.JpaConfig.java

@Bean
public DataSource dataSource() {
    org.apache.commons.dbcp.BasicDataSource ds = new org.apache.commons.dbcp.BasicDataSource();
    ds.setUrl(jdbcUrl);/*from  w  ww . j  a va 2s  . c om*/
    ds.setDriverClassName(driverClassName);
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setInitialSize(4);
    ds.setDefaultAutoCommit(false);
    return ds;
    //EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    //return builder.setType(EmbeddedDatabaseType.HSQL).build();
}

From source file:gobblin.runtime.MysqlDatasetStateStoreTest.java

@BeforeClass
public void setUp() throws Exception {
    testMetastoreDatabase = TestMetastoreDatabaseFactory.get();
    String jdbcUrl = testMetastoreDatabase.getJdbcUrl();
    ConfigBuilder configBuilder = ConfigBuilder.create();
    BasicDataSource mySqlDs = new BasicDataSource();

    mySqlDs.setDriverClassName(ConfigurationKeys.DEFAULT_STATE_STORE_DB_JDBC_DRIVER);
    mySqlDs.setDefaultAutoCommit(false);
    mySqlDs.setUrl(jdbcUrl);/*from w  w  w.  j  ava  2s. co m*/
    mySqlDs.setUsername(TEST_USER);
    mySqlDs.setPassword(TEST_PASSWORD);

    dbJobStateStore = new MysqlStateStore<>(mySqlDs, TEST_STATE_STORE, false, JobState.class);

    configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_URL_KEY, jdbcUrl);
    configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_USER_KEY, TEST_USER);
    configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY, TEST_PASSWORD);

    ClassAliasResolver<DatasetStateStore.Factory> resolver = new ClassAliasResolver<>(
            DatasetStateStore.Factory.class);

    DatasetStateStore.Factory stateStoreFactory = resolver.resolveClass("mysql").newInstance();
    dbDatasetStateStore = stateStoreFactory.createStateStore(configBuilder.build());

    // clear data that may have been left behind by a prior test run
    dbJobStateStore.delete(TEST_JOB_NAME);
    dbDatasetStateStore.delete(TEST_JOB_NAME);
}

From source file:io.springagora.store.ApplicationConfig.java

/**
 * Bean definition./*from   w  w w .  ja v a  2s. c  o  m*/
 * 
 * Datasource used to retrieve connections for the persistence layer. It's
 * configured following definitions written in {@code application.properties}.
 * 
 * @return
 *      The {@code Datasource} object, that will act as the connection pool,
 *      providing connections to the application. 
 * 
 * @throws SQLException
 *      If any error occurs during the connection attempt, it will be thrown
 *      as a {@code SQLException}.
 */
@Bean
public DataSource dataSource() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl(connectionUrl);
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setInitialSize(5);
    ds.setMaxActive(20);
    ds.setDefaultAutoCommit(false);
    return ds;
}