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

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

Introduction

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

Prototype

public synchronized void setDefaultTransactionIsolation(int defaultTransactionIsolation) 

Source Link

Document

Sets the default transaction isolation state for returned connections.

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

Usage

From source file:net.sf.taverna.t2.provenance.api.ProvenanceAccess.java

/**
 * Initialises a named JNDI DataSource if not already set up externally.
 * The DataSource is named jdbc/taverna//  w  w w . jav a2s.  co m
 *
 * @param driverClassName - the classname for the driver to be used.
 * @param jdbcUrl - the jdbc connection url
 * @param username - the username, if required (otherwise null)
 * @param password - the password, if required (oteherwise null)
 * @param minIdle - if the driver supports multiple connections, then the minumum number of idle connections in the pool
 * @param maxIdle - if the driver supports multiple connections, then the maximum number of idle connections in the pool
 * @param maxActive - if the driver supports multiple connections, then the minumum number of connections in the pool
 */
public static void initDataSource(String driverClassName, String jdbcUrl, String username, String password,
        int minIdle, int maxIdle, int maxActive) {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setMaxIdle(maxIdle);
    ds.setDefaultAutoCommit(true);
    if (username != null) {
        ds.setUsername(username);
    }
    if (password != null) {
        ds.setPassword(password);
    }

    ds.setUrl(jdbcUrl);

    InitialContext context;
    try {
        context = new InitialContext();
        context.rebind("jdbc/taverna", ds);
    } catch (NamingException ex) {
        logger.error("Problem rebinding the jdbc context: " + ex);
    }

}

From source file:com.lawulu.bdc.etl.batch.config.DatabaseConfiguration.java

@Bean(destroyMethod = "close")
public DataSource dbcpDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    dataSource.setMaxActive(20);//from   ww  w . j av a2s . co  m
    dataSource.setMaxIdle(20);
    dataSource.setMaxWait(10000);
    dataSource.setInitialSize(5);
    dataSource.setValidationQuery("SELECT 1");
    dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return dataSource;
}

From source file:com.bstek.dorado.core.store.SqlBaseStoreSupport.java

protected synchronized DataSource getDataSource() throws Exception {
    if (dataSource != null) {
        return dataSource;
    }/* w ww .ja v a  2s . co m*/

    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:jetsennet.orm.datasource.DbcpDataSourceCreator.java

@Override
public DataSource createDatasource(ConnectionInfo conn, DbPoolInfo props) throws SQLException {
    org.apache.commons.dbcp.BasicDataSource dataSource = new org.apache.commons.dbcp.BasicDataSource();
    dataSource.setDriverClassName(conn.driver);
    dataSource.setUrl(conn.url);/*from  w  w  w. j  a  v  a2 s  .c  o  m*/
    dataSource.setUsername(conn.user);
    dataSource.setPassword(conn.pwd);

    String connectionProperties = props.get("connectionProperties");
    if (connectionProperties != null && connectionProperties.trim().length() > 0) {
        dataSource.setConnectionProperties(connectionProperties);
    }
    Boolean defaultAutoCommit = Utils.str2Boolean(props.get("defaultAutoCommit"));
    if (defaultAutoCommit != null) {
        dataSource.setDefaultAutoCommit(defaultAutoCommit);
    }
    Boolean defaultReadOnly = Utils.str2Boolean(props.get("defaultReadOnly"));
    if (defaultReadOnly != null) {
        dataSource.setDefaultReadOnly(defaultReadOnly);
    }
    Integer defaultTransactionIsolation = Utils.strToInteger(props.get("defaultTransactionIsolation"));
    if (defaultTransactionIsolation != null) {
        dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
    }
    String defaultCatalog = props.get("defaultCatalog");
    if (defaultCatalog != null && defaultCatalog.trim().length() > 0) {
        dataSource.setDefaultCatalog(defaultCatalog);
    }

    int initialSize = Utils.strToInt(props.get("initialSize"));
    if (initialSize > 0) {
        dataSource.setInitialSize(initialSize);
    }
    int maxActive = Utils.strToInt(props.get("maxActive"));
    if (maxActive > 0) {
        dataSource.setMaxActive(maxActive);
    }
    int maxIdle = Utils.strToInt(props.get("maxIdle"));
    if (maxIdle > 0) {
        dataSource.setMaxIdle(maxIdle);
    }
    int minIdle = Utils.strToInt(props.get("minIdle"));
    if (minIdle > 0) {
        dataSource.setMinIdle(minIdle);
    }
    int maxWait = Utils.strToInt(props.get("maxWait"));
    if (maxWait > 0) {
        dataSource.setMaxWait(maxWait);
    }

    String validationQuery = props.get("validationQuery");
    if (validationQuery != null && validationQuery.trim().length() > 0) {
        dataSource.setValidationQuery(validationQuery);
    }
    Integer validationQueryTimeout = Utils.strToInteger(props.get("validationQueryTimeout"));
    if (validationQueryTimeout != null) {
        dataSource.setValidationQueryTimeout(validationQueryTimeout);
    }
    Boolean testOnBorrow = Utils.str2Boolean(props.get("testOnBorrow"));
    if (testOnBorrow != null) {
        dataSource.setTestOnBorrow(testOnBorrow);
    }
    Boolean testOnReturn = Utils.str2Boolean(props.get("testOnReturn"));
    if (testOnReturn != null) {
        dataSource.setTestOnReturn(testOnReturn);
    }
    Boolean testWhileIdle = Utils.str2Boolean(props.get("testWhileIdle"));
    if (testWhileIdle != null) {
        dataSource.setTestWhileIdle(testWhileIdle);
    }
    Integer timeBetweenEvictionRunsMillis = Utils.strToInteger(props.get("timeBetweenEvictionRunsMillis"));
    if (timeBetweenEvictionRunsMillis != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    }
    Integer numTestsPerEvictionRun = Utils.strToInteger(props.get("numTestsPerEvictionRun"));
    if (numTestsPerEvictionRun != null) {
        dataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    }
    int minEvictableIdleTimeMillis = Utils.strToInt(props.get("minEvictableIdleTimeMillis"));
    if (minEvictableIdleTimeMillis > 0) {
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    }

    Boolean removeAbandoned = Utils.str2Boolean(props.get("removeAbandoned"));
    if (removeAbandoned != null) {
        dataSource.setRemoveAbandoned(removeAbandoned);
    }
    int removeAbandonedTimeout = Utils.strToInt(props.get("removeAbandonedTimeout"));
    if (removeAbandonedTimeout > 0) {
        dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
    }
    Boolean logAbandoned = Utils.str2Boolean(props.get("logAbandoned"));
    if (logAbandoned != null) {
        dataSource.setLogAbandoned(logAbandoned);
    }
    return dataSource;
}

From source file:com.openddal.test.BaseTestCase.java

private BasicDataSource newDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);/*w w  w  .  jav  a2 s  .  c om*/
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return ds;
}

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.jav  a 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());
}

From source file:org.apache.metamodel.jdbc.JdbcUpdateCallbackTest.java

@Test
public void testTransactionalUpdateScripts() throws Exception {
    DerbyTest.initDerbySettings();//from w  w  w  .  j a  v  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.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  ww w .j a  va  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 w w w  .  j  a  v  a  2s  .c o  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;
}

From source file:org.apache.taverna.provenance.api.ProvenanceAccess.java

/**
 * Initialises a named JNDI DataSource if not already set up externally. The
 * DataSource is named jdbc/taverna/* w  w w .  j  a  v  a  2  s .c o  m*/
 * 
 * @param driverClassName
 *            - the classname for the driver to be used.
 * @param jdbcUrl
 *            - the jdbc connection url
 * @param username
 *            - the username, if required (otherwise null)
 * @param password
 *            - the password, if required (oteherwise null)
 * @param minIdle
 *            - if the driver supports multiple connections, then the
 *            minumum number of idle connections in the pool
 * @param maxIdle
 *            - if the driver supports multiple connections, then the
 *            maximum number of idle connections in the pool
 * @param maxActive
 *            - if the driver supports multiple connections, then the
 *            minumum number of connections in the pool
 */
public static void initDataSource(String driverClassName, String jdbcUrl, String username, String password,
        int minIdle, int maxIdle, int maxActive) {
    System.setProperty(INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setDefaultTransactionIsolation(TRANSACTION_READ_UNCOMMITTED);
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setMaxIdle(maxIdle);
    ds.setDefaultAutoCommit(true);
    if (username != null)
        ds.setUsername(username);
    if (password != null)
        ds.setPassword(password);
    ds.setUrl(jdbcUrl);

    try {
        new InitialContext().rebind("jdbc/taverna", ds);
    } catch (NamingException ex) {
        logger.error("Problem rebinding the jdbc context", ex);
    }
}