Example usage for java.sql Connection getTransactionIsolation

List of usage examples for java.sql Connection getTransactionIsolation

Introduction

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

Prototype

int getTransactionIsolation() throws SQLException;

Source Link

Document

Retrieves this Connection object's current transaction isolation level.

Usage

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

public DataGraph[] find(Query query, int maxResults) {
    if (query == null)
        throw new IllegalArgumentException("expected non-null 'query' argument");
    validate(query);/*w  w  w.  j  a v  a 2  s .  c o  m*/
    if (log.isDebugEnabled()) {
        log(query);
    }
    Connection con = null;
    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 graph query");
            con.setAutoCommit(false);
        }

        // TODO: make transaction isolation configurable
        RDBMSVendorName vendor = PlasmaRuntime.getInstance()
                .getRDBMSProviderVendor(DataAccessProviderName.JDBC);
        switch (vendor) {
        case ORACLE:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        case MYSQL:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        default:
        }
        if (log.isDebugEnabled())
            log.debug(
                    "using transaction isolation level " + con.getTransactionIsolation() + " for graph query");
    } 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);
    }
    GraphQuery dispatcher = new GraphQuery(con);
    try {
        DataGraph[] results = null;

        if (maxResults > 0)
            results = dispatcher.find(query, maxResults, new Timestamp((new Date()).getTime()));
        else
            results = dispatcher.find(query, new Timestamp((new Date()).getTime()));
        return results;
    } finally {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
    }
}

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

public List<DataGraph[]> find(Query[] queries) {
    if (queries == null)
        throw new IllegalArgumentException("expected non-null 'queries' argument");
    Connection con = null;
    try {/*from  w  w  w . j a v a2  s .  c  o  m*/
        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 query");
            con.setAutoCommit(false);
        }

        // TODO: make transaction isolation configurable
        RDBMSVendorName vendor = PlasmaRuntime.getInstance()
                .getRDBMSProviderVendor(DataAccessProviderName.JDBC);
        switch (vendor) {
        case ORACLE:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        case MYSQL:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        default:
        }
        if (log.isDebugEnabled())
            log.debug("using transaction isolation level " + con.getTransactionIsolation()
                    + " for multi graph query");
    } 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);
    }
    GraphQuery dispatcher = new GraphQuery(con);
    List<DataGraph[]> list = new ArrayList<DataGraph[]>();
    Timestamp snapshotDate = new Timestamp((new Date()).getTime());
    try {
        for (int i = 0; i < queries.length; i++) {
            validate(queries[i]);
            if (log.isDebugEnabled()) {
                log(queries[i]);
            }
            DataGraph[] results = dispatcher.find(queries[i], snapshotDate);
            list.add(results);
        }
        return list;
    } finally {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                if (con != null)
                    con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
    }
}

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;
    try {/*from ww w  .ja v  a2 s.co  m*/
        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: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;
    try {/*from   w w  w.j  a va 2  s  .  c o  m*/
        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();
    }
}

From source file:org.craftercms.cstudio.alfresco.activityfeed.CStudioActivityFeedDaoServiceImpl.java

@Override
public void initIndexes() {
    DataSource dataSource = sqlMapper.getDataSource();
    Connection connection = null;
    int oldval = -1;
    try {//from  w  ww  .j ava2 s .  co  m
        connection = dataSource.getConnection();
        oldval = connection.getTransactionIsolation();
        if (oldval != Connection.TRANSACTION_READ_COMMITTED) {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }

        List<HashMap> checkTable = sqlMapper.queryForList(STATEMENT_CHECK_TABLE_EXISTS);
        if (checkTable == null || checkTable.size() < 1) {
            ScriptRunner scriptRunner = new ScriptRunner(connection, false, true);
            scriptRunner.runScript(Resources.getResourceAsReader(initializeScriptPath));
        }
        connection.commit();
        List<TableIndexCheckTO> indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_USER_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_USER_IDX);
        }
        indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_SITE_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_SITE_IDX);
        }
        indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_CONTENT_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_CONTENT_IDX);
        }
        connection.commit();
        if (oldval != -1) {
            connection.setTransactionIsolation(oldval);
        }
    } catch (SQLException e) {
        LOGGER.error("Error while initializing CStudio Activity DB indexes.", e);
    } catch (IOException e) {
        LOGGER.error("Error while initializing CStudio Activity DB indexes.", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
            connection = null;
        }
    }
}

From source file:org.craftercms.cstudio.alfresco.objectstate.ObjectStateDAOServiceImpl.java

@Override
public void initIndexes() {
    DataSource dataSource = _sqlMapClient.getDataSource();
    Connection connection = null;
    int oldval = -1;
    try {//  w  ww  .j  a va 2  s.c  o m
        connection = dataSource.getConnection();
        oldval = connection.getTransactionIsolation();
        if (oldval != Connection.TRANSACTION_READ_COMMITTED) {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        List<HashMap> checkTable = _sqlMapClient.queryForList(STATEMENT_CHECK_TABLE_EXISTS);
        if (checkTable == null || checkTable.size() < 1) {
            ScriptRunner scriptRunner = new ScriptRunner(connection, false, true);
            scriptRunner.runScript(Resources.getResourceAsReader(initializeScriptPath));
        } else {
            Integer checkColumnCTEUsername = (Integer) _sqlMapClient.queryForObject(STATEMENT_CHECK_PATH_SIZE);
            if (checkColumnCTEUsername < 2000) {
                ScriptRunner scriptRunner = new ScriptRunner(connection, false, true);
                scriptRunner.runScript(Resources.getResourceAsReader(
                        initializeScriptPath.replace("initialize.sql", "alter_path_column_size.sql")));
            }

        }
        List<HashMap> indexCheckResult = _sqlMapClient.queryForList(STATEMENT_CHECK_OBJECT_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            _sqlMapClient.insert(STATEMENT_ADD_OBJECT_IDX);
        }
        connection.commit();
        if (oldval != -1) {
            connection.setTransactionIsolation(oldval);
        }
    } catch (SQLException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Error while initializing Object State table DB indexes.", e);
        }
    } catch (IOException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Error while initializing Sequence table DB indexes.", e);
        }
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
            connection = null;
        }
    }
}

From source file:org.executequery.datasource.ConnectionPoolImpl.java

private void configureTransactionIsolationLevel(Connection connection) {

    try {// ww w  . ja  v a  2  s. co m

        defaultTxIsolation = connection.getTransactionIsolation();
        supportsTransactions = connection.getMetaData().supportsTransactions();

    } catch (SQLException e) {

        rethrowAsDataSourceException(e);
    }

}

From source file:org.forgerock.openidm.repo.jdbc.impl.JDBCRepoService.java

/**
 * Updates the specified object in the object set.
 * <p/>/*w  w w  . j a va 2 s.co  m*/
 * 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.geoserver.security.jdbc.AbstractJDBCService.java

/**
 * Get a new connection from the datasource,
 * check/set autocommit == false and isolation level
 * according to {@link #DEFAULT_ISOLATION_LEVEL}
 * //from  w  w w .  j a  va 2s. com
 * @return
 * @throws SQLException
 */
protected Connection getConnection() throws SQLException {
    Connection con = getDataSource().getConnection();
    if (con.getAutoCommit())
        con.setAutoCommit(false);
    if (con.getTransactionIsolation() != DEFAULT_ISOLATION_LEVEL)
        con.setTransactionIsolation(DEFAULT_ISOLATION_LEVEL);

    return con;
}

From source file:org.jboss.dashboard.database.NonPooledDataSource.java

protected void setIsolation(Connection conn, int isolation) {
    try {//from   www  . j a v a2  s  .  co  m
        if (conn.getTransactionIsolation() != isolation) {
            conn.setTransactionIsolation(isolation);
        }
    } catch (SQLException e) {
        log.debug("Can not set connection isolation.", e);
    }
}