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

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

Introduction

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

Prototype

public synchronized void setMaxWait(long maxWait) 

Source Link

Document

Sets the maxWait property.

Usage

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);
    ds.setMinEvictableIdleTimeMillis(1800000);
    ds.setMinIdle(0);//w  w  w.  j  a v  a 2  s .c  o  m
    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  a2s. c  o 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.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 www.  j ava2  s  .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;
}

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
 *///w  ww.ja v a  2  s . com
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;
}

From source file:org.blocks4j.reconf.client.setup.DatabaseManager.java

private BasicDataSource createDataSource(DatabaseURL arg) {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(arg.getDriverClassName());
    ds.setUrl(arg.buildRuntimeURL());/*from   w  ww.  j  av  a2s .c om*/
    ds.setUsername(arg.getLogin());
    ds.setPassword(arg.getPass());
    ds.setMaxActive(30);
    ds.setMinIdle(5);
    ds.setTestOnBorrow(true);
    ds.setMaxWait(5000);
    return ds;
}

From source file:org.compass.core.lucene.engine.store.jdbc.DbcpDataSourceProvider.java

protected DataSource doCreateDataSource(String url, CompassSettings settings) throws CompassException {
    BasicDataSource dataSource = new BasicDataSource();
    if (!externalAutoCommit) {
        dataSource.setDefaultAutoCommit(autoCommit);
    }//from  w  ww.ja v a 2 s .co m
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);

    if (settings.getSetting(
            LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.DEFAULT_TRANSACTION_ISOLATION) != null) {
        dataSource.setDefaultTransactionIsolation(settings.getSettingAsInt(
                LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.DEFAULT_TRANSACTION_ISOLATION, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.INITIAL_SIZE) != null) {
        dataSource.setInitialSize(
                settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.INITIAL_SIZE, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_ACTIVE) != null) {
        dataSource.setMaxActive(
                settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_ACTIVE, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_IDLE) != null) {
        dataSource.setMaxIdle(
                settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_IDLE, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MIN_IDLE) != null) {
        dataSource.setMinIdle(
                settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MIN_IDLE, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_WAIT) != null) {
        dataSource.setMaxWait(
                settings.getSettingAsLong(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_WAIT, 0));
    }

    if (settings.getSetting(
            LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_OPEN_PREPARED_STATEMENTS) != null) {
        dataSource.setMaxOpenPreparedStatements(settings.getSettingAsInt(
                LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_OPEN_PREPARED_STATEMENTS, 0));
    }

    if (settings
            .getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.POOL_PREPARED_STATEMENTS) != null) {
        dataSource.setPoolPreparedStatements(settings.getSettingAsBoolean(
                LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.POOL_PREPARED_STATEMENTS, false));
    }

    return dataSource;
}

From source file:org.eclipse.dirigible.repository.datasource.DataSourceFacade.java

private DataSource createDirectDataSource(Properties properties) {
    String id = properties.getProperty(DataSourceFacade.PARAM_DB_ID);
    String name = properties.getProperty(DataSourceFacade.PARAM_DB_NAME);
    String url = properties.getProperty(DataSourceFacade.PARAM_DB_LOC);
    String driver = properties.getProperty(DataSourceFacade.PARAM_DB_DRIVER);
    String user = properties.getProperty(DataSourceFacade.PARAM_DB_USER);
    String password = properties.getProperty(DataSourceFacade.PARAM_DB_PASSWORD);
    String defaultAutoCommit = properties.getProperty(DataSourceFacade.PARAM_DB_AUTO_COMMIT);
    String maxActive = properties.getProperty(DataSourceFacade.PARAM_DB_AUTO_MAX_ACTIVE);
    String maxIdle = properties.getProperty(DataSourceFacade.PARAM_DB_AUTO_MAX_IDLE);
    String maxWait = properties.getProperty(DataSourceFacade.PARAM_DB_AUTO_MAX_WAIT);

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(driver);
    basicDataSource.setUrl(url);//from  w ww .ja  va 2s.  c o  m
    basicDataSource.setUsername(user);
    basicDataSource.setPassword(password);
    basicDataSource.setDefaultAutoCommit(Boolean.parseBoolean(defaultAutoCommit));
    basicDataSource.setMaxActive(maxActive != null ? Integer.parseInt(maxActive) : 100);
    basicDataSource.setMaxIdle(maxIdle != null ? Integer.parseInt(maxIdle) : 30);
    basicDataSource.setMaxWait(maxWait != null ? Integer.parseInt(maxWait) : 10000);

    return basicDataSource;

}

From source file:org.geosde.core.jdbc.JDBCDataStoreFactory.java

/**
 * DataSource access allowing SQL use: intended to allow client code to query available schemas.
 * <p>/*from  w  w  w .  jav  a 2s . c  o m*/
 * This DataSource is the clients responsibility to close() when they are finished using it.
 * </p> 
 * @param params Map of connection parameter.
 * @return DataSource for SQL use
 * @throws IOException
 */
public BasicDataSource createDataSource(Map params) throws IOException {
    //create a datasource
    BasicDataSource dataSource = new BasicDataSource();

    // driver
    dataSource.setDriverClassName(getDriverClassName());

    // url
    dataSource.setUrl(getJDBCUrl(params));

    // username (on embedded dbs it can be optional)
    String user = (String) USER.lookUp(params);
    if (user != null) {
        dataSource.setUsername(user);
    }

    // password
    String passwd = (String) PASSWD.lookUp(params);
    if (passwd != null) {
        dataSource.setPassword(passwd);
    }

    // max wait
    Integer maxWait = (Integer) MAXWAIT.lookUp(params);
    if (maxWait != null && maxWait != -1) {
        dataSource.setMaxWait(maxWait * 1000);
    }

    // connection pooling options
    Integer minConn = (Integer) MINCONN.lookUp(params);
    if (minConn != null) {
        dataSource.setMinIdle(minConn);
    }

    Integer maxConn = (Integer) MAXCONN.lookUp(params);
    if (maxConn != null) {
        dataSource.setMaxActive(maxConn);
    }

    Boolean validate = (Boolean) VALIDATECONN.lookUp(params);
    if (validate != null && validate && getValidationQuery() != null) {
        dataSource.setTestOnBorrow(true);
        dataSource.setValidationQuery(getValidationQuery());
    }

    Boolean testWhileIdle = (Boolean) TEST_WHILE_IDLE.lookUp(params);
    if (testWhileIdle != null) {
        dataSource.setTestWhileIdle(testWhileIdle);
    }

    Integer timeBetweenEvictorRuns = (Integer) TIME_BETWEEN_EVICTOR_RUNS.lookUp(params);
    if (timeBetweenEvictorRuns != null && timeBetweenEvictorRuns > 0) {
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictorRuns * 1000l);
    }

    Integer minEvictableTime = (Integer) MIN_EVICTABLE_TIME.lookUp(params);
    if (minEvictableTime != null) {
        dataSource.setMinEvictableIdleTimeMillis(minEvictableTime * 1000l);
    }

    Integer evictorTestsPerRun = (Integer) EVICTOR_TESTS_PER_RUN.lookUp(params);
    if (evictorTestsPerRun != null) {
        dataSource.setNumTestsPerEvictionRun(evictorTestsPerRun);
    }

    // some datastores might need this
    dataSource.setAccessToUnderlyingConnectionAllowed(true);
    return dataSource;
}

From source file:org.geotoolkit.coverage.postgresql.PGCoverageStoreFactory.java

/**
 * Creates the datasource for the coverage store.
 *//*  w w  w  .  j  a  v a  2  s .co  m*/
private DataSource createDataSource(final ParameterValueGroup params) throws IOException {
    //create a datasource
    final BasicDataSource dataSource = new BasicDataSource();

    // driver
    dataSource.setDriverClassName(getDriverClassName());

    // url
    dataSource.setUrl(getJDBCUrl(params));

    // username
    final String user = (String) params.parameter(USER.getName().toString()).getValue();
    dataSource.setUsername(user);

    // password
    final String passwd = (String) params.parameter(PASSWORD.getName().toString()).getValue();
    if (passwd != null) {
        dataSource.setPassword(passwd);
    }

    // max wait
    final Integer maxWait = (Integer) params.parameter(MAXWAIT.getName().toString()).getValue();
    if (maxWait != null && maxWait != -1) {
        dataSource.setMaxWait(maxWait * 1000);
    }

    // connection pooling options
    final Integer minConn = (Integer) params.parameter(MINCONN.getName().toString()).getValue();
    if (minConn != null) {
        dataSource.setMinIdle(minConn);
    }

    final Integer maxConn = (Integer) params.parameter(MAXCONN.getName().toString()).getValue();
    if (maxConn != null) {
        dataSource.setMaxActive(maxConn);
    }

    final Boolean validate = (Boolean) params.parameter(VALIDATECONN.getName().toString()).getValue();
    if (validate != null && validate && getValidationQuery() != null) {
        dataSource.setTestOnBorrow(true);
        dataSource.setValidationQuery(getValidationQuery());
    }

    // might need this
    dataSource.setAccessToUnderlyingConnectionAllowed(true);

    return new DBCPDataSource(dataSource);
}