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

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

Introduction

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

Prototype

public synchronized void setDriverClassName(String driverClassName) 

Source Link

Document

Sets the jdbc driver class name.

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

Usage

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 {/*from www.  j ava  2  s .com*/
            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./*from   ww  w .j  a  va2s .  co  m*/
 *
 * @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());//from   ww w  . j  a  v a  2 s .  c o m
    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);/*from   w w w.  j  av a 2s. c o  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 w w . j  av a  2s .  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 {/* w w w.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.DataSourceFactory.java

public static DataSource create(final boolean managed, final Class impl, final String definition)
        throws IllegalAccessException, InstantiationException, IOException {

    final org.apache.commons.dbcp.BasicDataSource ds;

    if (DataSource.class.isAssignableFrom(impl) && !Boolean
            .parseBoolean(System.getProperty("org.apache.openejb.resource.jdbc.hot.deploy", "false"))) {

        final ObjectRecipe recipe = new ObjectRecipe(impl);
        recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
        recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
        recipe.allow(Option.NAMED_PARAMETERS);
        recipe.setAllProperties(asProperties(definition));

        DataSource dataSource = (DataSource) recipe.create();

        if (managed) {
            ds = new DbcpManagedDataSource(dataSource);
        } else {/*ww  w  .j a  v a 2  s.  c  o  m*/
            ds = new DbcpDataSource(dataSource);
        }
    } else {
        ds = (org.apache.commons.dbcp.BasicDataSource) create(managed);
    }

    // force the driver class to be set
    ds.setDriverClassName(impl.getName());

    return ds;
}

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 ww . j  ava  2s  .c  o  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;
}

From source file:org.apache.synapse.config.xml.AbstractDBMediatorFactory.java

/**
 * Create a custom DataSource using the specified properties and Apache DBCP
 * @param pool the toplevel 'pool' element that holds DataSource information
 * @param mediator the mediator to store properties for serialization
 * @return a DataSource created using specified properties
 *///from ww w. j  av a 2s  .  co  m
private DataSource createCustomDataSource(OMElement pool, AbstractDBMediator mediator) {

    BasicDataSource ds = new BasicDataSource();

    // load the minimum required properties
    ds.setDriverClassName(getValue(pool, DRIVER_Q));
    ds.setUsername(getValue(pool, USER_Q));
    ds.setPassword(getValue(pool, PASS_Q));
    ds.setUrl(getValue(pool, URL_Q));

    //save loaded properties for later
    mediator.addDataSourceProperty(DRIVER_Q, getValue(pool, DRIVER_Q));
    mediator.addDataSourceProperty(URL_Q, getValue(pool, URL_Q));
    mediator.addDataSourceProperty(USER_Q, getValue(pool, USER_Q));
    mediator.addDataSourceProperty(PASS_Q, getValue(pool, PASS_Q));

    Iterator props = pool.getChildrenWithName(PROP_Q);
    while (props.hasNext()) {

        OMElement prop = (OMElement) props.next();
        String name = prop.getAttribute(ATT_NAME).getAttributeValue();
        String value = prop.getAttribute(ATT_VALUE).getAttributeValue();
        // save property for later
        mediator.addDataSourceProperty(name, value);

        if ("autocommit".equals(name)) {
            if ("true".equals(value)) {
                ds.setDefaultAutoCommit(true);
            } else if ("false".equals(value)) {
                ds.setDefaultAutoCommit(false);
            }
        } else if ("isolation".equals(name)) {
            try {
                if ("Connection.TRANSACTION_NONE".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
                } else if ("Connection.TRANSACTION_READ_COMMITTED".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                } else if ("Connection.TRANSACTION_READ_UNCOMMITTED".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
                } else if ("Connection.TRANSACTION_REPEATABLE_READ".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
                } else if ("Connection.TRANSACTION_SERIALIZABLE".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                }
            } catch (NumberFormatException ignore) {
            }
        } else if ("initialsize".equals(name)) {
            try {
                ds.setInitialSize(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxactive".equals(name)) {
            try {
                ds.setMaxActive(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxidle".equals(name)) {
            try {
                ds.setMaxIdle(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxopenstatements".equals(name)) {
            try {
                ds.setMaxOpenPreparedStatements(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxwait".equals(name)) {
            try {
                ds.setMaxWait(Long.parseLong(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("minidle".equals(name)) {
            try {
                ds.setMinIdle(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("poolstatements".equals(name)) {
            if ("true".equals(value)) {
                ds.setPoolPreparedStatements(true);
            } else if ("false".equals(value)) {
                ds.setPoolPreparedStatements(false);
            }
        } else if ("testonborrow".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestOnBorrow(true);
            } else if ("false".equals(value)) {
                ds.setTestOnBorrow(false);
            }
        } else if ("testonreturn".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestOnReturn(true);
            } else if ("false".equals(value)) {
                ds.setTestOnReturn(false);
            }
        } else if ("testwhileidle".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestWhileIdle(true);
            } else if ("false".equals(value)) {
                ds.setTestWhileIdle(false);
            }
        } else if ("validationquery".equals(name)) {
            ds.setValidationQuery(value);
        }
    }
    return ds;
}