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

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

Introduction

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

Prototype

public synchronized void setUrl(String url) 

Source Link

Document

Sets the #url .

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

Usage

From source file:com.alibaba.druid.DBCPTest.java

public void test_max() throws Exception {
    Class.forName("com.alibaba.druid.mock.MockDriver");

    final BasicDataSource dataSource = new BasicDataSource();
    //        final DruidDataSource dataSource = new DruidDataSource();
    dataSource.setInitialSize(3);//from   www  . ja  v a2s .co  m
    dataSource.setMaxActive(20);
    dataSource.setMaxIdle(20);
    dataSource.setDriverClassName("com.alibaba.druid.mock.MockDriver");
    dataSource.setUrl("jdbc:mock:xxx");

    final int THREAD_COUNT = 200;
    final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT);
    final CountDownLatch startLatch = new CountDownLatch(1);
    Thread[] threads = new Thread[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; ++i) {
        threads[i] = new Thread() {

            public void run() {
                try {
                    startLatch.await();
                    for (int i = 0; i < 1000; ++i) {
                        Connection conn = dataSource.getConnection();
                        Thread.sleep(1);
                        conn.close();
                    }
                } catch (Exception e) {
                } finally {
                    endLatch.countDown();
                }
            }
        };
        threads[i].start();
    }

    startLatch.countDown();

    endLatch.await();

    //        System.out.println(dataSource.getNumIdle());
    System.out.println(MockDriver.instance.getConnections().size());
    System.out.println(MockDriver.instance.getConnectionCloseCount());
}

From source file:com.alibaba.druid.benckmark.pool.Oracle_Case3.java

public void test_1() throws Exception {
    final BasicDataSource dataSource = new BasicDataSource();

    dataSource.setMaxActive(maxActive);//from w w  w.  j a v a  2s  .c  om
    dataSource.setMaxIdle(maxIdle);
    dataSource.setMaxWait(maxWait);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(jdbcUrl);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setValidationQuery(validationQuery);
    dataSource.setTestOnBorrow(testOnBorrow);

    for (int i = 0; i < loopCount; ++i) {
        p0(dataSource, "dbcp", threadCount);
    }
    System.out.println();
}

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);
    mySqlDs.setUsername(TEST_USER);//from ww  w .  j  a  v a 2s.co m
    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:com.uber.hoodie.hive.client.HoodieHiveClient.java

private DataSource getDatasource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverName);//from  ww w  . j av a2s.  c  o m
    ds.setUrl(getHiveJdbcUrlWithDefaultDBName());
    ds.setUsername(configuration.getHiveUsername());
    ds.setPassword(configuration.getHivePassword());
    return ds;
}

From source file:edu.si.services.sidora.rest.batch.BatchServiceTest.java

@Override
protected JndiRegistry createRegistry() throws Exception {
    JndiRegistry reg = super.createRegistry();

    if (USE_MYSQL_DB) {
        BasicDataSource testMySQLdb = new BasicDataSource();
        testMySQLdb.setDriverClassName("com.mysql.jdbc.Driver");
        testMySQLdb.setUrl(
                "jdbc:mysql://" + props.getProperty("mysql.host") + ":" + props.getProperty("mysql.port") + "/"
                        + props.getProperty("mysql.database") + "?zeroDateTimeBehavior=convertToNull");
        testMySQLdb.setUsername(props.getProperty("mysql.username").toString());
        testMySQLdb.setPassword(props.getProperty("mysql.password").toString());
        reg.bind("dataSource", testMySQLdb);
    } else {/* ww w.j  a v a 2 s .  co  m*/
        reg.bind("dataSource", db);
    }

    reg.bind("dataSource", db);

    reg.bind("jsonProvider", org.apache.cxf.jaxrs.provider.json.JSONProvider.class);
    reg.bind("jaxbProvider", org.apache.cxf.jaxrs.provider.JAXBElementProvider.class);

    return reg;
}

From source file:binky.reportrunner.service.impl.DatasourceServiceImpl.java

private DataSource getDs(RunnerDataSource runnerDs)
        throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException,
        PropertyVetoException, NamingException, EncryptionException {

    final String jndiDataSource = runnerDs.getJndiName();

    if (StringUtils.isBlank(jndiDataSource)) {
        EncryptionUtil enc = new EncryptionUtil();
        logger.info("using dbcp pooled connection for: " + runnerDs.getDataSourceName());

        String jdbcUser = runnerDs.getUsername();
        if (StringUtils.isBlank(runnerDs.getPassword()))
            throw new SecurityException("password is empty");
        String jdbcPassword = enc.decrpyt(secureKey, runnerDs.getPassword());

        String jdbcUrl = runnerDs.getJdbcUrl();
        String databaseDriver = runnerDs.getJdbcClass();

        Class.forName(databaseDriver).newInstance();

        BasicDataSource ds1 = new BasicDataSource();
        ds1.setDriverClassName(databaseDriver);
        ds1.setUrl(jdbcUrl);
        ds1.setUsername(jdbcUser);// w  ww.ja  v  a  2  s.  co m
        ds1.setPassword(jdbcPassword);
        ds1.setInitialSize(runnerDs.getInitialPoolSize());
        ds1.setMaxActive(runnerDs.getMaxPoolSize());

        ds1.setRemoveAbandoned(true);
        ds1.setRemoveAbandonedTimeout(600);

        // do not want anything updating anything
        ds1.setDefaultReadOnly(true);

        ds1.setLogAbandoned(true);
        ds1.setTestOnBorrow(true);
        ds1.setTestOnReturn(true);
        ds1.setTestWhileIdle(true);

        // does this work across all RBMS? - no it doesn't
        //ds1.setValidationQuery("select 1");
        //ds1.setValidationQueryTimeout(300);

        return ds1;
    } else {
        logger.info(
                "getting datasource from JNDI url: " + jndiDataSource + " for " + runnerDs.getDataSourceName());
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup("java:/comp/env/" + jndiDataSource);
        return ds;
    }
}

From source file:com.test.HibernateDerbyLockingTest.java

public void testSpringWithDataSource() throws Exception {
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(EmbeddedDriver.class.getName());
    dataSource.setUrl("jdbc:derby:lockingtest;create=true");
    dataSource.setUsername("sa");
    dataSource.setPassword("sa");

    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "create");
    properties.setProperty("hibernate.dialect", "org.bpmscript.hibernate.DerbyDialect");
    properties.setProperty("hibernate.show_sql", "true");

    // properties.setProperty("hibernate.connection.driver_class",
    // EmbeddedDriver.class.getName());
    // properties.setProperty("hibernate.connection.url",
    // "jdbc:derby:lockingtest;create=true");
    // properties.setProperty("hibernate.connection.username", "sa");
    // properties.setProperty("hibernate.connection.password", "sa");
    // properties.setProperty("hibernate.connection.pool_size", "10");

    final AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
    sessionFactoryBean.setLobHandler(new DefaultLobHandler());
    sessionFactoryBean.setHibernateProperties(properties);
    sessionFactoryBean.setAnnotatedClasses(new Class[] { Person.class });
    sessionFactoryBean.setDataSource(dataSource);
    sessionFactoryBean.afterPropertiesSet();

    SessionFactory sessionFactory = (SessionFactory) sessionFactoryBean.getObject();
    try {//from   w  ww  .ja  v  a  2s  .c o  m
        runTest(sessionFactory);
    } finally {
        sessionFactory.close();
    }
}

From source file:net.jetrix.DataSourceManager.java

/**
 * Configure a datasource.//from   w w  w. ja v  a 2s  .  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.bstek.dorado.core.store.SqlBaseStoreSupport.java

protected synchronized DataSource getDataSource() throws Exception {
    if (dataSource != null) {
        return dataSource;
    }/*  w w w .  j a  va 2  s .  c om*/

    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:fr.cnes.sitools.datasource.jdbc.business.SitoolsDataSourceFactory.java

/**
 * Local creation of a DataSource//from   w ww.  j  a  v a2s  .com
 * 
 * @param driver
 *          the database driver
 * @param connectURI
 *          the URI to connect
 * @param userName
 *          the database user name
 * @param password
 *          the password
 * @param schemaOnConnection
 *          the schema on connection
 * @return SitoolsDataSource a standard data source for SITools
 */
public SitoolsDataSource setupDataSource(String driver, String connectURI, String userName, String password,
        String schemaOnConnection) {

    String key = connectURI + "@" + userName;
    SitoolsDataSource foundDatasource = dataSources.get(key);
    if (foundDatasource == null) {

        BasicDataSource ds = new BasicDataSource();
        // OSGi
        ds.setDriverClassLoader(getClass().getClassLoader());
        ds.setDriverClassName(driver);
        ds.setUsername(userName);
        ds.setPassword(password);
        ds.setUrl(connectURI);
        ds.setMaxActive(10);
        ds.setInitialSize(1);
        //      ds.setDefaultReadOnly(false);
        //      ds.setDefaultAutoCommit(true);
        JDBCDataSource jdbcDS = new JDBCDataSource();
        jdbcDS.setName(key);
        jdbcDS.setDriverClass(driver);
        foundDatasource = new SitoolsDataSource(jdbcDS, ds, schemaOnConnection);
        dataSources.put(key, foundDatasource);
    }
    return foundDatasource;
}