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:org.apache.james.user.jdbc.DefaultUsersJdbcRepositoryTest.java

private BasicDataSource getDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(EmbeddedDriver.class.getName());
    ds.setUrl("jdbc:derby:memory:testdb;create=true");
    ds.setUsername("james");
    ds.setPassword("james");
    return ds;/*from   ww w.  j av a 2 s.  c  o m*/
}

From source file:org.apache.kylin.query.QueryDataSource.java

private static WrappedDataSource getWrapped(String project, KylinConfig config, Properties props) {
    File olapTmp = OLAPSchemaFactory.createTempOLAPJson(project, config);
    if (logger.isDebugEnabled()) {
        try {//  w w  w  .ja v a2 s  . co m
            String text = FileUtils.readFileToString(olapTmp, Charset.defaultCharset());
            logger.debug("The new temp olap json is :" + text);
        } catch (IOException e) {
            // logging failure is not critical
        }
    }

    BasicDataSource ds = null;
    if (StringUtils.isEmpty(props.getProperty("maxActive"))) {
        props.setProperty("maxActive", "-1");
    }
    try {
        ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(props);
    } catch (Exception e) {
        // Basic mode
        ds = new BasicDataSource();
        ds.setMaxActive(-1);
    }
    ds.setUrl("jdbc:calcite:model=" + olapTmp.getAbsolutePath());
    ds.setDriverClassName(Driver.class.getName());

    WrappedDataSource wrappedDS = new WrappedDataSource(ds, olapTmp);
    return wrappedDS;
}

From source file:org.apache.lens.server.util.UtilityMethods.java

/**
 * Gets the data source from conf./*w w  w  .  j a  va2s  .  com*/
 *
 * @param conf the conf
 * @return the data source from conf
 */
public static BasicDataSource getDataSourceFromConf(Configuration conf) {
    BasicDataSource tmp = new BasicDataSource();
    tmp.setDriverClassName(
            conf.get(LensConfConstants.SERVER_DB_DRIVER_NAME, LensConfConstants.DEFAULT_SERVER_DB_DRIVER_NAME));
    tmp.setUrl(conf.get(LensConfConstants.SERVER_DB_JDBC_URL, LensConfConstants.DEFAULT_SERVER_DB_JDBC_URL));
    tmp.setUsername(conf.get(LensConfConstants.SERVER_DB_JDBC_USER, LensConfConstants.DEFAULT_SERVER_DB_USER));
    tmp.setPassword(conf.get(LensConfConstants.SERVER_DB_JDBC_PASS, LensConfConstants.DEFAULT_SERVER_DB_PASS));
    tmp.setValidationQuery(conf.get(LensConfConstants.SERVER_DB_VALIDATION_QUERY,
            LensConfConstants.DEFAULT_SERVER_DB_VALIDATION_QUERY));
    tmp.setDefaultAutoCommit(true);
    return tmp;
}

From source file:org.apache.metamodel.jdbc.integrationtests.AbstractJdbIntegrationTest.java

protected BasicDataSource getDataSource() {
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl(getUrl());
    dataSource.setDriverClassName(getDriver());
    dataSource.setUsername(getUsername());
    dataSource.setPassword(getPassword());

    return dataSource;
}

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);/* www  .ja  v  a  2 s. co m*/
    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();//  w  ww  .j a va 2  s  . co 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.ode.daohib.bpel.BaseTestDAO.java

protected DataSource getDataSource() {
    if (externalDB) {
        BasicDataSource ds = new BasicDataSource();
        try {/*from  www . j  a v  a 2  s .  co m*/
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            ds.setUsername("sa");
            ds.setPassword("sa");
            ds.setUrl("jdbc:mysql://localhost/bpmsdbJunit");
            this.ds = ds;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("######### Couldn't get External connection! #############");
        }
    }
    if (ds == null) {
        EmbeddedXADataSource ds = new EmbeddedXADataSource();
        ds.setCreateDatabase("create");
        ds.setDatabaseName("target/testdb");
        ds.setUser("sa");
        ds.setPassword("");
        this.ds = ds;
    }
    return ds;
}

From source file:org.apache.openejb.resource.jdbc.HsqldbDataSourcePlugin.java

public void configure(BasicDataSource dataSource) {
    String url = dataSource.getUrl();
    url = toAbsolutePath(url);
    dataSource.setUrl(url);
}

From source file:org.apache.stratos.tenant.mgt.util.TenantMgtUtil.java

public static void deleteTenantUMData(int tenantId) throws Exception {
    RealmConfiguration realmConfig = TenantMgtServiceComponent.getRealmService()
            .getBootstrapRealmConfiguration();
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(realmConfig.getRealmProperty(JDBCRealmConstants.DRIVER_NAME));
    dataSource.setUrl(realmConfig.getRealmProperty(JDBCRealmConstants.URL));
    dataSource.setUsername(realmConfig.getRealmProperty(JDBCRealmConstants.USER_NAME));
    dataSource.setPassword(realmConfig.getRealmProperty(JDBCRealmConstants.PASSWORD));
    dataSource.setMaxActive(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_ACTIVE)));
    dataSource.setMinIdle(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MIN_IDLE)));
    dataSource.setMaxWait(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_WAIT)));

    TenantUMDataDeletionUtil.deleteTenantUMData(tenantId, dataSource.getConnection());
}

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  w w  w.  j  a v a  2s .co 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;
}