Example usage for java.sql Connection TRANSACTION_REPEATABLE_READ

List of usage examples for java.sql Connection TRANSACTION_REPEATABLE_READ

Introduction

In this page you can find the example usage for java.sql Connection TRANSACTION_REPEATABLE_READ.

Prototype

int TRANSACTION_REPEATABLE_READ

To view the source code for java.sql Connection TRANSACTION_REPEATABLE_READ.

Click Source Link

Document

A constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur.

Usage

From source file:org.mybatis.guice.datasource.dbcp.SharedPoolDataSourceProviderTest.java

@Test
public void get_OtherValues() throws Throwable {
    final boolean autoCommit = false;
    final int loginTimeout = 11;
    final boolean defaultReadOnly = false;
    final int defaultTransactionIsolation = Connection.TRANSACTION_REPEATABLE_READ;
    final String description = "test_description2";
    final int minEvictableIdleTimeMillis = 31;
    final int numTestsPerEvictionRun = 41;
    final boolean rollbackAfterValidation = false;
    final boolean testOnBorrow = false;
    final boolean testOnReturn = false;
    final boolean testWhileIdle = false;
    final int timeBetweenEvictionRunsMillis = 51;
    final String validationQuery = "SELECT 2";
    final int maxActive = 61;
    final int maxIdle = 71;
    final int maxWait = 81;
    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override//from  w ww.j a  v a 2 s.  co m
        protected void configure() {
            bind(ConnectionPoolDataSource.class).toInstance(connectionPoolDataSource);
            bindConstant().annotatedWith(Names.named("JDBC.autoCommit")).to(autoCommit);
            bindConstant().annotatedWith(Names.named("JDBC.loginTimeout")).to(loginTimeout);
            bindConstant().annotatedWith(Names.named("DBCP.defaultReadOnly")).to(defaultReadOnly);
            bindConstant().annotatedWith(Names.named("DBCP.defaultTransactionIsolation"))
                    .to(defaultTransactionIsolation);
            bindConstant().annotatedWith(Names.named("DBCP.description")).to(description);
            bindConstant().annotatedWith(Names.named("DBCP.minEvictableIdleTimeMillis"))
                    .to(minEvictableIdleTimeMillis);
            bindConstant().annotatedWith(Names.named("DBCP.numTestsPerEvictionRun")).to(numTestsPerEvictionRun);
            bindConstant().annotatedWith(Names.named("DBCP.rollbackAfterValidation"))
                    .to(rollbackAfterValidation);
            bindConstant().annotatedWith(Names.named("DBCP.testOnBorrow")).to(testOnBorrow);
            bindConstant().annotatedWith(Names.named("DBCP.testOnReturn")).to(testOnReturn);
            bindConstant().annotatedWith(Names.named("DBCP.testWhileIdle")).to(testWhileIdle);
            bindConstant().annotatedWith(Names.named("DBCP.timeBetweenEvictionRunsMillis"))
                    .to(timeBetweenEvictionRunsMillis);
            bindConstant().annotatedWith(Names.named("DBCP.validationQuery")).to(validationQuery);
            bindConstant().annotatedWith(Names.named("DBCP.maxActive")).to(maxActive);
            bindConstant().annotatedWith(Names.named("DBCP.maxIdle")).to(maxIdle);
            bindConstant().annotatedWith(Names.named("DBCP.maxWait")).to(maxWait);
        }
    });
    SharedPoolDataSourceProvider provider = injector.getInstance(SharedPoolDataSourceProvider.class);

    SharedPoolDataSource dataSource = (SharedPoolDataSource) provider.get();

    assertEquals(connectionPoolDataSource, dataSource.getConnectionPoolDataSource());
    assertEquals(autoCommit, dataSource.isDefaultAutoCommit());
    assertEquals(defaultReadOnly, dataSource.isDefaultReadOnly());
    assertEquals(defaultTransactionIsolation, dataSource.getDefaultTransactionIsolation());
    assertEquals(description, dataSource.getDescription());
    assertEquals(loginTimeout, dataSource.getLoginTimeout());
    assertEquals(minEvictableIdleTimeMillis, dataSource.getMinEvictableIdleTimeMillis());
    assertEquals(numTestsPerEvictionRun, dataSource.getNumTestsPerEvictionRun());
    assertEquals(rollbackAfterValidation, dataSource.isRollbackAfterValidation());
    assertEquals(testOnBorrow, dataSource.isTestOnBorrow());
    assertEquals(testOnReturn, dataSource.isTestOnReturn());
    assertEquals(testWhileIdle, dataSource.isTestWhileIdle());
    assertEquals(timeBetweenEvictionRunsMillis, dataSource.getTimeBetweenEvictionRunsMillis());
    assertEquals(validationQuery, dataSource.getValidationQuery());
    assertEquals(maxActive, dataSource.getMaxActive());
    assertEquals(maxIdle, dataSource.getMaxIdle());
    assertEquals(maxWait, dataSource.getMaxWait());
}

From source file:org.noerp.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    ManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }/*  w w  w  .  j  av a  2  s  .c  o m*/
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool pool = new GenericObjectPool(factory, poolConfig);
    factory.setPool(pool);

    mds = new ManagedDataSource(pool, xacf.getTransactionRegistry());
    //mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry()); // Useful to debug the usage of connections in the pool
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.nuxeo.runtime.datasource.BasicManagedDataSourceFactory.java

/**
 * Creates and configures a {@link BasicManagedDataSource} instance based on
 * the given properties.// w  w w .  jav  a  2  s . c o m
 *
 * @param properties the datasource configuration properties
 * @throws Exception if an error occurs creating the data source
 */
public static DataSource createDataSource(Properties properties) throws Exception {
    BasicManagedDataSource dataSource = new BasicManagedDataSource();

    String value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
    if (value != null) {
        dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_DEFAULTREADONLY);
    if (value != null) {
        dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
    if (value != null) {
        int level = UNKNOWN_TRANSACTIONISOLATION;
        if ("NONE".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_NONE;
        } else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_READ_COMMITTED;
        } else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_READ_UNCOMMITTED;
        } else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_REPEATABLE_READ;
        } else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_SERIALIZABLE;
        } else {
            try {
                level = Integer.parseInt(value);
            } catch (NumberFormatException e) {
                System.err.println("Could not parse defaultTransactionIsolation: " + value);
                System.err.println("WARNING: defaultTransactionIsolation not set");
                System.err.println("using default value of database driver");
                level = UNKNOWN_TRANSACTIONISOLATION;
            }
        }
        dataSource.setDefaultTransactionIsolation(level);
    }

    value = properties.getProperty(PROP_DEFAULTCATALOG);
    if (value != null) {
        dataSource.setDefaultCatalog(value);
    }

    value = properties.getProperty(PROP_DRIVERCLASSNAME);
    if (value != null) {
        dataSource.setDriverClassName(value);
    }

    value = properties.getProperty(PROP_MAXACTIVE);
    if (value != null) {
        dataSource.setMaxActive(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_MAXIDLE);
    if (value != null) {
        dataSource.setMaxIdle(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_MINIDLE);
    if (value != null) {
        dataSource.setMinIdle(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_INITIALSIZE);
    if (value != null) {
        dataSource.setInitialSize(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_MAXWAIT);
    if (value != null) {
        dataSource.setMaxWait(Long.parseLong(value));
    }

    value = properties.getProperty(PROP_TESTONBORROW);
    if (value != null) {
        dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_TESTONRETURN);
    if (value != null) {
        dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
    if (value != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
    }

    value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
    if (value != null) {
        dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
    if (value != null) {
        dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
    }

    value = properties.getProperty(PROP_TESTWHILEIDLE);
    if (value != null) {
        dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_PASSWORD);
    if (value != null) {
        dataSource.setPassword(value);
    }

    value = properties.getProperty(PROP_URL);
    if (value != null) {
        dataSource.setUrl(value);
    }

    value = properties.getProperty(PROP_USERNAME);
    if (value != null) {
        dataSource.setUsername(value);
    }

    value = properties.getProperty(PROP_VALIDATIONQUERY);
    if (value != null) {
        dataSource.setValidationQuery(value);
    }

    value = properties.getProperty(PROP_VALIDATIONQUERY_TIMEOUT);
    if (value != null) {
        dataSource.setValidationQueryTimeout(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
    if (value != null) {
        dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_REMOVEABANDONED);
    if (value != null) {
        dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
    if (value != null) {
        dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_LOGABANDONED);
    if (value != null) {
        dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
    if (value != null) {
        dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
    if (value != null) {
        dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_INITCONNECTIONSQLS);
    if (value != null) {
        StringTokenizer tokenizer = new StringTokenizer(value, ";");
        dataSource.setConnectionInitSqls(Collections.list(tokenizer));
    }

    value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
    if (value != null) {
        Properties p = getProperties(value);
        Enumeration<?> e = p.propertyNames();
        while (e.hasMoreElements()) {
            String propertyName = (String) e.nextElement();
            dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
        }
    }

    // Managed: initialize XADataSource

    value = properties.getProperty(PROP_XADATASOURCE);
    if (value != null) {
        Class<?> xaDataSourceClass;
        try {
            xaDataSourceClass = Class.forName(value);
        } catch (Throwable t) {
            throw (SQLException) new SQLException("Cannot load XA data source class '" + value + "'")
                    .initCause(t);
        }
        XADataSource xaDataSource;
        try {
            xaDataSource = (XADataSource) xaDataSourceClass.newInstance();
        } catch (Throwable t) {
            throw (SQLException) new SQLException("Cannot create XA data source of class '" + value + "'")
                    .initCause(t);
        }
        dataSource.setXaDataSourceInstance(xaDataSource);
    }

    // DBCP-215
    // Trick to make sure that initialSize connections are created
    if (dataSource.getInitialSize() > 0) {
        dataSource.getLogWriter();
    }

    // Return the configured DataSource instance
    return dataSource;
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Determine if the database is initialized, or is it already being initialized by another connection. First check if a specified table exists. If it does,
 * check the initialized status./*from   w  w  w.j a v a 2 s  . co  m*/
 * 
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_WAITING_DB_INIT} if there was a problem waiting for the initialization status
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_GET_INIT_STATUS} if there was a problem querying for the initialization status
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_SETTING_ISOLATION} if there was a problem changing the transaction isolation level
 */
private boolean isInitialized(Connection connection, String tablename) throws AnzoException {
    int isolation = Connection.TRANSACTION_REPEATABLE_READ;
    if (configuration.getSupportsIsolation()) {
        try {
            isolation = connection.getTransactionIsolation();
            connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } catch (SQLException e) {
            log.error(LogUtils.RDB_MARKER, "Error setting tranaction isolation", e);
            throw new AnzoException(ExceptionConstants.RDB.FAILED_SETTING_ISOLATION, e);
        }
    }
    try {
        ResultSet rs = null;
        //Need to check all the tables, and not just the server table.  If we only check the server table, we could overwrite tables containing data.
        try {
            try {
                rs = connection.getMetaData().getTables(null, null,
                        configuration.getUsesUppercase() ? serverUpper : serverLower, new String[] { table });
                if (!rs.next()) {
                    return !checkIfTablesExists(connection, true);
                }
                String tbl = rs.getString(3);
                if (!tbl.equalsIgnoreCase(serverUpper)) {
                    return !checkIfTablesExists(connection, true);
                }
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        } catch (SQLException e) {
            log.error(LogUtils.RDB_MARKER, "error checking tables", e);
            throw new AnzoException(ExceptionConstants.RDB.FAILED_GETTING_TABLE_STATUS, e, serverUpper);
        }
        try {
            long initialized = 2;
            int retries = 0;
            //While the server is initializing in another connection, wait. Wait a total of 20 seconds, and then fail.
            while (initialized > 1) {
                if (retries++ < 30) {
                    Long init = ServerRdbWrapper.getInitialized(statementProvider, connection);
                    if (init == null) {
                        return true;
                    }
                    initialized = init.longValue();
                    if (initialized > 1) {
                        if ((System.currentTimeMillis() - initialized) > 60000) {
                            log.error(LogUtils.RDB_MARKER,
                                    "A previous connections was intializing the database, but its been over a minute, so assume a fauilure");
                            ServerRdbWrapper.setInitializingFailed(statementProvider, connection);
                            return false;
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ie) {
                        }
                    }
                } else {
                    throw new AnzoException(ExceptionConstants.RDB.FAILED_WAITING_DB_INIT);
                }
            }
            checkIfTablesExists(connection, false);
            return true;
        } catch (RdbException e) {
            log.error(LogUtils.RDB_MARKER, "Error checking initialization state", e);
            throw new AnzoException(ExceptionConstants.RDB.FAILED_GET_INIT_STATUS, e);
        }
    } finally {
        try {
            if (configuration.getSupportsIsolation()) {
                connection.setTransactionIsolation(isolation);
            }
        } catch (SQLException e) {
            log.error(LogUtils.RDB_MARKER, "Error setting transaction isolation level", e);
            throw new AnzoException(ExceptionConstants.RDB.FAILED_SETTING_ISOLATION, e);
        }
    }
}

From source file:org.openconcerto.sql.model.SQLDataSource.java

public final void setInitialTransactionIsolation(int level) {
    if (level != Connection.TRANSACTION_READ_UNCOMMITTED && level != Connection.TRANSACTION_READ_COMMITTED
            && level != Connection.TRANSACTION_REPEATABLE_READ && level != Connection.TRANSACTION_SERIALIZABLE)
        throw new IllegalArgumentException("Invalid value :" + level);
    synchronized (this) {
        if (this.txIsolation != level) {
            this.txIsolation = level;
            // perhaps do like setInitialSchema() : i.e. call setTransactionIsolation() on
            // existing connections
            this.invalidateAllConnections(false);
        }/*www . ja  v a 2s.c  o m*/
    }
}

From source file:org.rimudb.C3P0PoolTests.java

@Test
public void testConnectionAttributes() throws Exception {
    // Connect to the database
    CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-c3p0-2-jdbcconfig.xml", true);

    cdb.connect("dbid-1");
    Database db = cdb.getDatabase("dbid-1");
    Connection conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();//  w w  w  . ja  va 2 s.co  m

    cdb.connect("dbid-2");
    db = cdb.getDatabase("dbid-2");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-3");
    db = cdb.getDatabase("dbid-3");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-4");
    db = cdb.getDatabase("dbid-4");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.disconnectAllNoException();
}

From source file:org.rimudb.DBCPPoolTests.java

@Test
public void testConnectionAttributes() throws Exception {
    // Connect to the database
    CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-dbcp-2-jdbcconfig.xml", true);

    cdb.connect("dbid-1");
    Database db = cdb.getDatabase("dbid-1");
    Connection conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();/*from  w ww  . j a  v a 2s.  c  o m*/

    cdb.connect("dbid-2");
    db = cdb.getDatabase("dbid-2");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-3");
    db = cdb.getDatabase("dbid-3");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-4");
    db = cdb.getDatabase("dbid-4");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.disconnectAllNoException();
}

From source file:org.sakaiproject.tomcat.jdbc.pool.SakaiBasicDataSource.java

/**
 * Set the default transaction isolation level from a string value, based on the settings and values in java.sql.Connection
 * //from ww  w  .j a v  a 2  s  .  co  m
 * @param defaultTransactionIsolation
 */
public void setDefaultTransactionIsolationString(String defaultTransactionIsolation) {
    if ((defaultTransactionIsolation == null) || (defaultTransactionIsolation.trim().length() == 0)) {
        setDefaultTransactionIsolation(DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_NONE")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_READ_UNCOMMITTED")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_READ_COMMITTED")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_REPEATABLE_READ")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_SERIALIZABLE")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    } else {
        setDefaultTransactionIsolation(DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION);
        M_log.warn("invalid transaction isolation level: " + defaultTransactionIsolation);
    }
}

From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java

@Override
public void openTransaction() throws ODataServiceFault {
    try {// w  w w.ja va2  s.  c om
        if (getTransactionalConnection() == null) {
            Connection connection = this.dataSource.getConnection();
            this.defaultAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            this.defaultTransactionalIsolation = connection.getTransactionIsolation();
            connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            transactionalConnection.set(connection);
        }
    } catch (SQLException e) {
        throw new ODataServiceFault(e, "Connection Error occurred. :" + e.getMessage());
    }
}

From source file:org.wso2.carbon.datasource.core.utils.RDBMSDataSourceUtils.java

public static PoolConfiguration createPoolConfiguration(RDBMSConfiguration config) throws DataSourceException {
    PoolProperties props = new PoolProperties();
    props.setUrl(config.getUrl());/*from   www  .  java  2  s  . c  o  m*/
    if (config.isDefaultAutoCommit() != null) {
        props.setDefaultAutoCommit(config.isDefaultAutoCommit());
    }
    if (config.isDefaultReadOnly() != null) {
        props.setDefaultReadOnly(config.isDefaultReadOnly());
    }
    String isolationLevelString = config.getDefaultTransactionIsolation();
    if (isolationLevelString != null) {
        if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.NONE.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        } else if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.READ_UNCOMMITTED.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.READ_COMMITTED.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.REPEATABLE_READ.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if (RDBMSDataSourceConstants.TX_ISOLATION_LEVELS.SERIALIZABLE.equals(isolationLevelString)) {
            props.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        }
    }
    props.setDefaultCatalog(config.getDefaultCatalog());
    props.setDriverClassName(config.getDriverClassName());
    props.setUsername(config.getUsername());
    props.setPassword(config.getPassword());
    if (config.getMaxActive() != null) {
        props.setMaxActive(config.getMaxActive());
    }
    if (config.getMaxIdle() != null) {
        props.setMaxIdle(config.getMaxIdle());
    }
    if (config.getMinIdle() != null) {
        props.setMinIdle(config.getMinIdle());
    }
    if (config.getInitialSize() != null) {
        props.setInitialSize(config.getInitialSize());
    }
    if (config.getMaxWait() != null) {
        props.setMaxWait(config.getMaxWait());
    }
    if (config.isTestOnBorrow() != null) {
        props.setTestOnBorrow(config.isTestOnBorrow());
    }
    if (config.isTestOnReturn() != null) {
        props.setTestOnReturn(config.isTestOnReturn());
    }
    if (config.isTestWhileIdle() != null) {
        props.setTestWhileIdle(config.isTestWhileIdle());
    }
    props.setValidationQuery(config.getValidationQuery());
    props.setValidatorClassName(config.getValidatorClassName());
    if (config.getTimeBetweenEvictionRunsMillis() != null) {
        props.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis());
    }
    if (config.getNumTestsPerEvictionRun() != null) {
        props.setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun());
    }
    if (config.getMinEvictableIdleTimeMillis() != null) {
        props.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis());
    }
    if (config.isAccessToUnderlyingConnectionAllowed() != null) {
        props.setAccessToUnderlyingConnectionAllowed(config.isAccessToUnderlyingConnectionAllowed());
    }
    if (config.isRemoveAbandoned() != null) {
        props.setRemoveAbandoned(config.isRemoveAbandoned());
    }
    if (config.getRemoveAbandonedTimeout() != null) {
        props.setRemoveAbandonedTimeout(config.getRemoveAbandonedTimeout());
    }
    if (config.isLogAbandoned() != null) {
        props.setLogAbandoned(config.isLogAbandoned());
    }
    props.setConnectionProperties(config.getConnectionProperties());
    props.setInitSQL(config.getInitSQL());
    props.setJdbcInterceptors(config.getJdbcInterceptors());
    if (config.getValidationInterval() != null) {
        props.setValidationInterval(config.getValidationInterval());
    }
    if (config.isJmxEnabled() != null) {
        props.setJmxEnabled(config.isJmxEnabled());
    }
    if (config.isFairQueue() != null) {
        props.setFairQueue(config.isFairQueue());
    }
    if (config.getAbandonWhenPercentageFull() != null) {
        props.setAbandonWhenPercentageFull(config.getAbandonWhenPercentageFull());
    }
    if (config.getMaxAge() != null) {
        props.setMaxAge(config.getMaxAge());
    }
    if (config.isUseEquals() != null) {
        props.setUseEquals(config.isUseEquals());
    }
    if (config.getSuspectTimeout() != null) {
        props.setSuspectTimeout(config.getSuspectTimeout());
    }
    if (config.isAlternateUsernameAllowed() != null) {
        props.setAlternateUsernameAllowed(config.isAlternateUsernameAllowed());
    }
    if (config.getDataSourceClassName() != null) {
        handleExternalDataSource(props, config);
    }
    return props;
}