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:org.apache.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   ww  w  .ja va2s  .  c  om
    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);
    dbJobStateStore.delete(TEST_JOB_NAME2);
    dbDatasetStateStore.delete(TEST_JOB_NAME2);
}

From source file:org.apache.jackrabbit.core.util.db.ConnectionFactory.java

/**
 * Creates and returns a pooling JDBC {@link DataSource} for accessing
 * the database identified by the given driver class and JDBC
 * connection URL. The driver class can be <code>null</code> if
 * a specific driver has not been configured.
 *
 * @param driverClass the JDBC driver class, or <code>null</code>
 * @param url the JDBC connection URL//ww  w .j a  v a 2 s. c om
 * @return pooling DataSource for accessing the specified database
 */
private BasicDataSource getDriverDataSource(Class<?> driverClass, String url, String user, String password) {
    BasicDataSource ds = new BasicDataSource();
    created.add(ds);

    if (driverClass != null) {
        Driver instance = null;
        try {
            // Workaround for Apache Derby:
            // The JDBC specification recommends the Class.forName
            // method without the .newInstance() method call,
            // but it is required after a Derby 'shutdown'
            instance = (Driver) driverClass.newInstance();
        } catch (Throwable e) {
            // Ignore exceptions as there's no requirement for
            // a JDBC driver class to have a public default constructor
        }
        if (instance != null) {
            if (instance.jdbcCompliant()) {
                // JCR-3445 At the moment the PostgreSQL isn't compliant because it doesn't implement this method...                   
                ds.setValidationQueryTimeout(3);
            }
        }
        ds.setDriverClassName(driverClass.getName());
    }

    ds.setUrl(url);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setDefaultAutoCommit(true);
    ds.setTestOnBorrow(false);
    ds.setTestWhileIdle(true);
    ds.setTimeBetweenEvictionRunsMillis(600000); // 10 Minutes
    ds.setMinEvictableIdleTimeMillis(60000); // 1 Minute
    ds.setMaxActive(-1); // unlimited
    ds.setMaxIdle(GenericObjectPool.DEFAULT_MAX_IDLE + 10);
    ds.setValidationQuery(guessValidationQuery(url));
    ds.setAccessToUnderlyingConnectionAllowed(true);
    ds.setPoolPreparedStatements(true);
    ds.setMaxOpenPreparedStatements(-1); // unlimited
    return ds;
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepositoryTest.java

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

From source file:org.apache.james.rrt.jdbc.JDBCStepdefs.java

private BasicDataSource getDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(EmbeddedDriver.class.getName());
    ds.setUrl("jdbc:derby:target/" + UUID.randomUUID() + ";create=true");
    ds.setUsername("james");
    ds.setPassword("james");
    return ds;/* w  w w  . ja va2s .c o  m*/
}

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.ja v  a  2 s  .co  m
}

From source file:org.apache.kylin.query.adhoc.JdbcPushDownConnectionManager.java

private JdbcPushDownConnectionManager(KylinConfig config) throws ClassNotFoundException {
    dataSource = new BasicDataSource();

    Class.forName(config.getJdbcDriverClass());
    dataSource.setDriverClassName(config.getJdbcDriverClass());
    dataSource.setUrl(config.getJdbcUrl());
    dataSource.setUsername(config.getJdbcUsername());
    dataSource.setPassword(config.getJdbcPassword());
    dataSource.setMaxActive(config.getPoolMaxTotal());
    dataSource.setMaxIdle(config.getPoolMaxIdle());
    dataSource.setMinIdle(config.getPoolMinIdle());

    // Default settings
    dataSource.setTestOnBorrow(true);/*from   w  ww  .j  a  v  a2s . c o m*/
    dataSource.setValidationQuery("select 1");
    dataSource.setRemoveAbandoned(true);
    dataSource.setRemoveAbandonedTimeout(300);
}

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 ww  w. j  a  va2 s .c o  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.// ww w  .j a v  a  2  s .c  om
 *
 * @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());// ww  w . j  ava 2s  . 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);/* w w  w . j a va  2 s  .  c om*/
    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());
}