Example usage for java.sql Connection TRANSACTION_READ_COMMITTED

List of usage examples for java.sql Connection TRANSACTION_READ_COMMITTED

Introduction

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

Prototype

int TRANSACTION_READ_COMMITTED

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

Click Source Link

Document

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

Usage

From source file:org.cloudgraph.rdb.service.RDBGraphService.java

public SnapshotMap commit(DataGraph dataGraph, String username) {
    if (dataGraph == null)
        throw new IllegalArgumentException("expected non-null 'dataGraph' argument");
    if (username == null)
        throw new IllegalArgumentException("expected non-null 'username' argument");
    if (username.trim().length() == 0)
        throw new IllegalArgumentException("unexpected zero length 'username' argument");
    SnapshotMap snapshotMap = new SnapshotMap(new Timestamp((new Date()).getTime()));
    if (log.isDebugEnabled())
        log.debug("getting connection");
    Connection con = null;/*from   www. j  a  v  a2  s .  c  om*/
    try {
        con = ProviderManager.instance().getConnection();
        if (con.getAutoCommit()) {
            if (log.isDebugEnabled())
                log.debug("turning off connection autocommit for graph commit");
            con.setAutoCommit(false);
        }
        // TODO: make transaction isolation configurable
        con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        if (log.isDebugEnabled())
            log.debug(
                    "using transaction isolation level " + con.getTransactionIsolation() + " forgraph commit");
    } catch (SQLException e2) {
        if (con != null) {
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        throw new DataAccessException(e2);
    }
    DataGraphDispatcher dispatcher = new GraphDispatcher(snapshotMap, username, con);
    try {
        dispatcher.commit(dataGraph);
        con.commit();
        return snapshotMap;
    } catch (DataAccessException e) {
        if (log.isDebugEnabled())
            log.debug(e.getMessage(), e);
        try {
            con.rollback();
        } catch (SQLException e1) {
            log.error(e.getMessage(), e1);
        }
        throw e;
    } catch (Throwable t) {
        if (log.isDebugEnabled())
            log.debug(t.getMessage(), t);
        try {
            con.rollback();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        throw new DataAccessException(t);
    } finally {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        dispatcher.close();
    }
}

From source file:io.vitess.jdbc.VitessMySQLDatabaseMetadata.java

public boolean supportsTransactionIsolationLevel(int level) throws SQLException {
    switch (level) {
    case Connection.TRANSACTION_READ_COMMITTED:
    case Connection.TRANSACTION_READ_UNCOMMITTED:
    case Connection.TRANSACTION_REPEATABLE_READ:
    case Connection.TRANSACTION_SERIALIZABLE:
        return true;

    default://from ww w .j av a 2 s  .  com
        return false;
    }
}

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

@Test
public void get_PerUserDefaultTransactionIsolation() throws Throwable {
    final Map<String, Integer> defaultTransactionIsolation = new HashMap<String, Integer>();
    defaultTransactionIsolation.put("test_user", Connection.TRANSACTION_READ_COMMITTED);
    defaultTransactionIsolation.put("test_user2", Connection.TRANSACTION_SERIALIZABLE);
    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override//from   w ww .j av  a  2s.  c  o m
        protected void configure() {
            bind(new TypeLiteral<Map<String, Integer>>() {
            }).annotatedWith(PerUserDefaultTransactionIsolation.class).toInstance(defaultTransactionIsolation);
        }
    });
    PerUserPoolDataSourceProvider provider = injector.getInstance(PerUserPoolDataSourceProvider.class);

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

    assertEquals((Integer) Connection.TRANSACTION_READ_COMMITTED,
            dataSource.getPerUserDefaultTransactionIsolation("test_user"));
    assertEquals((Integer) Connection.TRANSACTION_SERIALIZABLE,
            dataSource.getPerUserDefaultTransactionIsolation("test_user2"));
}

From source file:org.apache.openjpa.jdbc.kernel.JDBCFetchConfigurationImpl.java

public JDBCFetchConfiguration setIsolation(int level) {
    if (level != -1 && level != DEFAULT && level != Connection.TRANSACTION_NONE
            && level != Connection.TRANSACTION_READ_UNCOMMITTED
            && level != Connection.TRANSACTION_READ_COMMITTED && level != Connection.TRANSACTION_REPEATABLE_READ
            && level != Connection.TRANSACTION_SERIALIZABLE)
        throw new IllegalArgumentException(_loc.get("bad-level", Integer.valueOf(level)).getMessage());

    if (level == DEFAULT)
        _state.isolationLevel = -1;//from ww w .  j av  a 2s  .c  om
    else
        _state.isolationLevel = level;
    return this;
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseInitializer.java

/**
 * Returns an database connection for the Dashboards Data source
 *
 * @return Database connection// www  .  ja  va2 s  . co m
 * @throws DashboardPortalException Exception to be thrown when we cannot connect to the DB source
 */
Connection getDBConnection() throws DashboardPortalException {
    try {
        Connection dbConnection = dataSource.getConnection();
        dbConnection.setAutoCommit(false);
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        return dbConnection;
    } catch (SQLException e) {
        throw new DashboardPortalException("Error connecting to the database", e);
    }
}

From source file:massbank.DatabaseManager.java

private void openConnection() {
    Connection con = null;//from   w  ww  .j  av  a 2  s.c om
    try {
        Class.forName(DatabaseManager.driver);
        con = DriverManager.getConnection(this.connectUrl, DatabaseManager.user, DatabaseManager.password);
        con.setAutoCommit(false);
        con.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED);
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.con = con;
}

From source file:JDBCPool.dbcp.demo.sourcecode.BasicDataSourceFactory.java

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

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

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

    value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
    if (value != null) {
        int level = PoolableConnectionFactory.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 = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
            }
        }
        dataSource.setDefaultTransactionIsolation(level);
    }

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

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

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

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

    value = properties.getProperty(PROP_MAXTOTAL);
    if (value != null) {
        dataSource.setMaxTotal(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_MAXWAITMILLIS);
    if (value != null) {
        dataSource.setMaxWaitMillis(Long.parseLong(value));
    }

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

    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_SOFTMINEVICTABLEIDLETIMEMILLIS);
    if (value != null) {
        dataSource.setSoftMinEvictableIdleTimeMillis(Long.parseLong(value));
    }

    value = properties.getProperty(PROP_EVICTIONPOLICYCLASSNAME);
    if (value != null) {
        dataSource.setEvictionPolicyClassName(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_REMOVEABANDONEDONBORROW);
    if (value != null) {
        dataSource.setRemoveAbandonedOnBorrow(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_REMOVEABANDONEDONMAINTENANCE);
    if (value != null) {
        dataSource.setRemoveAbandonedOnMaintenance(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_CONNECTIONINITSQLS); //?ConnectionSQL?
    if (value != null) {
        dataSource.setConnectionInitSqls(parseList(value, ';'));
    }

    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));
        }
    }

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

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

    value = properties.getProperty(PROP_JMX_NAME);
    if (value != null) {
        dataSource.setJmxName(value);
    }

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

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

    value = properties.getProperty(PROP_DEFAULT_QUERYTIMEOUT);
    if (value != null) {
        dataSource.setDefaultQueryTimeout(Integer.valueOf(value));
    }

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

    value = properties.getProperty(PROP_DISCONNECTION_SQL_CODES);
    if (value != null) {
        dataSource.setDisconnectionSqlCodes(parseList(value, ','));
    }

    // 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:com.frameworkset.commons.dbcp2.BasicDataSourceFactory.java

/**
 * Creates and configures a {@link BasicDataSource} instance based on the
 * given properties.//from  ww w.ja v a 2  s .  c  om
 *
 * @param properties the datasource configuration properties
 * @throws Exception if an error occurs creating the data source
 */
public static BasicDataSource createDataSource(Properties properties) throws Exception {
    BasicDataSource dataSource = new BasicDataSource();
    String value = null;

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

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

    value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
    if (value != null) {
        int level = PoolableConnectionFactory.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 = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
            }
        }
        dataSource.setDefaultTransactionIsolation(level);
    }

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

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

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

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

    value = properties.getProperty(PROP_MAXTOTAL);
    if (value != null) {
        dataSource.setMaxTotal(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_MAXWAITMILLIS);
    if (value != null) {
        dataSource.setMaxWaitMillis(Long.parseLong(value));
    }

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

    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_SOFTMINEVICTABLEIDLETIMEMILLIS);
    if (value != null) {
        dataSource.setSoftMinEvictableIdleTimeMillis(Long.parseLong(value));
    }

    value = properties.getProperty(PROP_EVICTIONPOLICYCLASSNAME);
    if (value != null) {
        dataSource.setEvictionPolicyClassName(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_REMOVEABANDONEDONBORROW);
    if (value != null) {
        dataSource.setRemoveAbandonedOnBorrow(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_REMOVEABANDONEDONMAINTENANCE);
    if (value != null) {
        dataSource.setRemoveAbandonedOnMaintenance(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_CONNECTIONINITSQLS);
    if (value != null) {
        dataSource.setConnectionInitSqls(parseList(value, ';'));
    }

    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));
        }
    }

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

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

    value = properties.getProperty(PROP_JMX_NAME);
    if (value != null) {
        dataSource.setJmxName(value);
    }

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

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

    value = properties.getProperty(PROP_DEFAULT_QUERYTIMEOUT);
    if (value != null) {
        dataSource.setDefaultQueryTimeout(Integer.valueOf(value));
    }

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

    value = properties.getProperty(PROP_DISCONNECTION_SQL_CODES);
    if (value != null) {
        dataSource.setDisconnectionSqlCodes(parseList(value, ','));
    }

    // 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.forgerock.openidm.repo.jdbc.impl.JDBCRepoService.java

/**
 * Updates the specified object in the object set.
 * <p/>/*from ww w. jav  a2s.c om*/
 * This implementation requires MVCC and hence enforces that clients state what revision they expect
 * to be updating
 * <p/>
 * If successful, this method updates metadata properties within the passed object,
 * including: a new {@code _rev} value for the revised object's version
 *
 * @param fullId the identifier of the object to be put, or {@code null} to request a generated identifier.
 * @param rev    the version of the object to update; or {@code null} if not provided.
 * @param obj    the contents of the object to put in the object set.
 * @throws ConflictException           if version is required but is {@code null}.
 * @throws ForbiddenException          if access to the object is forbidden.
 * @throws NotFoundException           if the specified object could not be found.
 * @throws PreconditionFailedException if version did not match the existing object in the set.
 * @throws BadRequestException         if the passed identifier is invalid
 */
public void update(String fullId, String rev, Map<String, Object> obj) throws ObjectSetException {

    String localId = getLocalId(fullId);
    String type = getObjectType(fullId);

    if (rev == null) {
        throw new ConflictException("Object passed into update does not have revision it expects set.");
    }

    Connection connection = null;
    Integer previousIsolationLevel = null;
    boolean retry = false;
    int tryCount = 0;
    do {
        TableHandler handler = getTableHandler(type);
        if (handler == null) {
            throw new ObjectSetException("No handler configured for resource type " + type);
        }
        retry = false;
        ++tryCount;
        try {
            connection = getConnection();
            previousIsolationLevel = new Integer(connection.getTransactionIsolation());
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            connection.setAutoCommit(false);

            handler.update(fullId, type, localId, rev, obj, connection);

            connection.commit();
            logger.debug("Commited updated object for id: {}", fullId);
        } catch (SQLException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("SQL Exception in update of {} with error code {}, sql state {}",
                        new Object[] { fullId, ex.getErrorCode(), ex.getSQLState(), ex });
            }
            rollback(connection);
            if (handler.isRetryable(ex, connection)) {
                if (tryCount <= maxTxRetry) {
                    retry = true;
                    logger.debug("Retryable exception encountered, retry {}", ex.getMessage());
                }
            }
            if (!retry) {
                throw new InternalServerErrorException("Updating object failed " + ex.getMessage(), ex);
            }
        } catch (ObjectSetException ex) {
            logger.debug("ObjectSetException in update of {}", fullId, ex);
            rollback(connection);
            throw ex;
        } catch (java.io.IOException ex) {
            logger.debug("IO Exception in update of {}", fullId, ex);
            rollback(connection);
            throw new InternalServerErrorException("Conversion of object to update failed", ex);
        } catch (RuntimeException ex) {
            logger.debug("Runtime Exception in update of {}", fullId, ex);
            rollback(connection);
            throw new InternalServerErrorException(
                    "Updating object failed with unexpected failure: " + ex.getMessage(), ex);
        } finally {
            if (connection != null) {
                try {
                    if (previousIsolationLevel != null) {
                        connection.setTransactionIsolation(previousIsolationLevel.intValue());
                    }
                } catch (SQLException ex) {
                    logger.warn("Failure in resetting connection isolation level ", ex);
                }
                CleanupHelper.loggedClose(connection);
            }
        }
    } while (retry);
}

From source file:org.cloudgraph.rdb.service.RDBGraphService.java

public SnapshotMap commit(DataGraph[] dataGraphs, String username) {
    if (dataGraphs == null)
        throw new IllegalArgumentException("expected non-null 'dataGraphs' argument");
    if (username == null)
        throw new IllegalArgumentException("expected non-null 'username' argument");
    if (username.trim().length() == 0)
        throw new IllegalArgumentException("unexpected zero length 'username' argument");
    SnapshotMap snapshotMap = new SnapshotMap(new Timestamp((new Date()).getTime()));
    Connection con = null;//from  w w  w  . j a  va 2s .c  o m
    try {
        if (log.isDebugEnabled())
            log.debug("getting connection");
        con = ProviderManager.instance().getConnection();
        if (con.getAutoCommit()) {
            if (log.isDebugEnabled())
                log.debug("turning off connection autocommit for multi graph commit");
            con.setAutoCommit(false);
        }
        // TODO: make transaction isolation configurable
        con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        if (log.isDebugEnabled())
            log.debug("using transaction isolation level " + con.getTransactionIsolation()
                    + " for multi graph commit");
    } catch (SQLException e2) {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        throw new DataAccessException(e2);
    }
    DataGraphDispatcher dispatcher = new GraphDispatcher(snapshotMap, username, con);

    try {
        dispatcher.commit(dataGraphs);
        con.commit();
        return snapshotMap;
    } catch (DataAccessException e) {
        try {
            con.rollback();
        } catch (SQLException e1) {
            log.error(e1.getMessage(), e1);
        }
        throw e;
    } catch (Throwable t) {
        try {
            con.rollback();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        throw new DataAccessException(t);
    } finally {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        dispatcher.close();
    }
}