Example usage for java.sql Connection setTransactionIsolation

List of usage examples for java.sql Connection setTransactionIsolation

Introduction

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

Prototype

void setTransactionIsolation(int level) throws SQLException;

Source Link

Document

Attempts to change the transaction isolation level for this Connection object to the one given.

Usage

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

/**
 * Convenience method to create a new Connection configured for TRANSACTION_READ_COMMITED
 * isolation and with auto-commit transactions disabled.
 *//* w w  w.j  ava2s.c om*/
private Connection newConnection() throws SQLException {
    final Connection connection = DriverManager.getConnection(_connectionURL);
    try {
        connection.setAutoCommit(false);
        connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    } catch (SQLException sqlEx) {
        try {
            connection.close();
        } finally {
            throw sqlEx;
        }
    }
    return connection;
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceVersionDAO.java

public String[] getChildPaths(ResourceIDImpl resourceID, VersionRetriever versionRetriever,
        int parentVersionIndex, int start, int pageLen, long snapshotID, DataAccessManager dataAccessManager)
        throws RegistryException {
    String[] childPaths = null;/*  w w  w .  j a  v  a 2  s . c  o  m*/

    if (Transaction.isStarted()) {
        childPaths = getChildPaths(resourceID, versionRetriever, parentVersionIndex, start, pageLen, snapshotID,
                JDBCDatabaseTransaction.getConnection());

    } else {

        Connection conn = null;
        boolean transactionSucceeded = false;
        try {
            conn = ((JDBCDataAccessManager) dataAccessManager).getDataSource().getConnection();

            // If a managed connection already exists, use that instead of a new connection.
            JDBCDatabaseTransaction.ManagedRegistryConnection temp = JDBCDatabaseTransaction
                    .getManagedRegistryConnection(conn);
            if (temp != null) {
                conn.close();
                conn = temp;
            }
            if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            }
            conn.setAutoCommit(false);

            childPaths = getChildPaths(resourceID, versionRetriever, parentVersionIndex, start, pageLen,
                    snapshotID, conn);
            transactionSucceeded = true;
        } catch (SQLException e) {

            String msg = "Failed to get the child paths " + pageLen + " child paths from " + start
                    + " of resource " + resourceID.getPath() + ". " + e.getMessage();
            log.error(msg, e);
            throw new RegistryException(msg, e);

        } finally {
            if (transactionSucceeded) {
                try {
                    conn.commit();
                } catch (SQLException e) {
                    log.error("Failed to commit the database connection used in "
                            + "getting child paths of the collection " + resourceID.getPath());
                }
            } else if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException e) {
                    log.error("Failed to rollback the database connection used in "
                            + "getting child paths of the collection " + resourceID.getPath());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("Failed to close the database connection used in "
                            + "getting child paths of collection " + resourceID.getPath());
                }
            }
        }
    }
    return childPaths;
}

From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCResourceVersionDAO.java

public String[] getChildPaths(ResourceIDImpl resourceID, VersionRetriever versionRetriever,
        int parentVersionIndex, int start, int pageLen, long snapshotID, DataAccessManager dataAccessManager)
        throws RepositoryException {
    String[] childPaths = null;//from   ww w  .j  ava2s.c o m

    if (Transaction.isStarted()) {
        childPaths = getChildPaths(resourceID, versionRetriever, parentVersionIndex, start, pageLen, snapshotID,
                JDBCDatabaseTransaction.getConnection());

    } else {
        Connection conn = null;
        boolean transactionSucceeded = false;

        try {
            conn = ((JDBCDataAccessManager) dataAccessManager).getDataSource().getConnection();

            // If a managed connection already exists, use that instead of a new connection.
            JDBCDatabaseTransaction.ManagedRegistryConnection temp = JDBCDatabaseTransaction
                    .getManagedRegistryConnection(conn);

            if (temp != null) {
                conn.close();
                conn = temp;
            }

            if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            }

            conn.setAutoCommit(false);

            childPaths = getChildPaths(resourceID, versionRetriever, parentVersionIndex, start, pageLen,
                    snapshotID, conn);
            transactionSucceeded = true;
        } catch (SQLException e) {
            String msg = "Failed to get the child paths " + pageLen + " child paths from " + start
                    + " of resource " + resourceID.getPath() + ". " + e.getMessage();
            log.error(msg, e);
            throw new RepositoryDBException(msg, e);
        } finally {
            if (transactionSucceeded) {
                try {
                    conn.commit();
                } catch (SQLException e) {
                    log.error("Failed to commit the database connection used in "
                            + "getting child paths of the collection " + resourceID.getPath());
                }
            } else if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException e) {
                    log.error("Failed to rollback the database connection used in "
                            + "getting child paths of the collection " + resourceID.getPath());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("Failed to close the database connection used in "
                            + "getting child paths of collection " + resourceID.getPath());
                }
            }
        }
    }
    return childPaths;
}

From source file:org.wso2.carbon.user.core.hybrid.HybridRoleManager.java

/**
 * @param filter/*ww  w  .j a  v a 2s  . co m*/
 * @return
 * @throws UserStoreException
 */
public String[] getHybridRoles(String filter) throws UserStoreException {

    Connection dbConnection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;

    String sqlStmt = HybridJDBCConstants.GET_ROLES;
    int maxItemLimit = UserCoreConstants.MAX_USER_ROLE_LIST;
    int searchTime = UserCoreConstants.MAX_SEARCH_TIME;

    try {
        maxItemLimit = Integer.parseInt(
                realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_ROLE_LIST));
    } catch (Exception e) {
        maxItemLimit = DEFAULT_MAX_ROLE_LIST_SIZE;
    }

    try {
        searchTime = Integer.parseInt(
                realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = DEFAULT_MAX_SEARCH_TIME;
    }

    try {
        if (filter != null && filter.trim().length() != 0) {
            filter = filter.trim();
            filter = filter.replace("*", "%");
            filter = filter.replace("?", "_");
        } else {
            filter = "%";
        }

        dbConnection = DatabaseUtil.getDBConnection(dataSource);

        if (dbConnection == null) {
            throw new UserStoreException("null connection");
        }

        dbConnection.setAutoCommit(false);
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setString(1, filter);
        if (sqlStmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) {
            prepStmt.setInt(2, tenantId);
        }
        prepStmt.setMaxRows(maxItemLimit);
        try {
            prepStmt.setQueryTimeout(searchTime);
        } catch (Exception e) {
            // this can be ignored since timeout method is not implemented
            log.debug(e);
        }
        List<String> filteredRoles = new ArrayList<String>();

        try {
            rs = prepStmt.executeQuery();
        } catch (SQLException e) {
            log.error("Error while retrieving roles from Internal JDBC role store", e);
            // May be due time out, therefore ignore this exception
        }

        if (rs != null) {
            while (rs.next()) {
                String name = rs.getString(1);
                // Append the domain
                if (!name.contains(UserCoreConstants.DOMAIN_SEPARATOR)) {
                    name = UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + name;
                }
                filteredRoles.add(name);
            }
        }
        return filteredRoles.toArray(new String[filteredRoles.size()]);
    } catch (SQLException e) {
        String errorMessage = "Error occurred while getting hybrid roles from filter : " + filter;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
    }
}

From source file:com.frameworkset.commons.dbcp2.datasources.PerUserPoolDataSource.java

@Override
protected void setupDefaults(Connection con, String username) throws SQLException {
    Boolean defaultAutoCommit = isDefaultAutoCommit();
    if (username != null) {
        Boolean userMax = getPerUserDefaultAutoCommit(username);
        if (userMax != null) {
            defaultAutoCommit = userMax;
        }//from   ww w .ja  v a 2 s  . c  om
    }

    Boolean defaultReadOnly = isDefaultReadOnly();
    if (username != null) {
        Boolean userMax = getPerUserDefaultReadOnly(username);
        if (userMax != null) {
            defaultReadOnly = userMax;
        }
    }

    int defaultTransactionIsolation = getDefaultTransactionIsolation();
    if (username != null) {
        Integer userMax = getPerUserDefaultTransactionIsolation(username);
        if (userMax != null) {
            defaultTransactionIsolation = userMax.intValue();
        }
    }

    if (defaultAutoCommit != null && con.getAutoCommit() != defaultAutoCommit.booleanValue()) {
        con.setAutoCommit(defaultAutoCommit.booleanValue());
    }

    if (defaultTransactionIsolation != UNKNOWN_TRANSACTIONISOLATION) {
        con.setTransactionIsolation(defaultTransactionIsolation);
    }

    if (defaultReadOnly != null && con.isReadOnly() != defaultReadOnly.booleanValue()) {
        con.setReadOnly(defaultReadOnly.booleanValue());
    }
}

From source file:org.freebxml.omar.server.persistence.rdb.SQLPersistenceManagerImpl.java

/**
 * Get a database connection. The connection is of autocommit off and with
 * transaction isolation level "transaction read committed"
 *///from www. ja  v a 2s .com
public Connection getConnection(ServerRequestContext context) throws RegistryException {
    Connection connection = null;
    if (log.isTraceEnabled()) {
        log.debug("SQLPersistenceManagerImpl.getConnection");
        numConnectionsOpen++;
    }
    try {
        if (useConnectionPool) {
            if (ds != null) {
                connection = ds.getConnection();
                if (connection == null) {
                    log.info(ServerResourceBundle.getInstance().getString(
                            "message.ErrorUnableToOpenDbConnctionForDataSource=", new Object[] { ds }));
                }
            }

            if (connection == null) {
                //Default to registry server ConnectionPool
                connection = connectionPool.getConnection(context.getId());
            }
            connection.setTransactionIsolation(transactionIsolation);
            connection.setAutoCommit(false);
        } else {
            // create connection directly
            if ((user != null) && (user.length() > 0)) {
                connection = java.sql.DriverManager.getConnection(databaseURL, user, password);
            } else {
                connection = java.sql.DriverManager.getConnection(databaseURL);
            }
            // Set Transaction Isolation and AutoComit
            // WARNING: till present Oracle dirvers (9.2.0.5) do not accept
            // setTransactionIsolation being called after setAutoCommit(false)
            connection.setTransactionIsolation(transactionIsolation);
            connection.setAutoCommit(false);
        }
    } catch (SQLException e) {
        throw new RegistryException(
                ServerResourceBundle.getInstance().getString("message.connectToDatabaseFailed"), e);
    }

    return connection;
}

From source file:it.cnr.icar.eric.server.persistence.rdb.SQLPersistenceManagerImpl.java

/**
 * Get a database connection. The connection is of autocommit off and with
 * transaction isolation level "transaction read committed"
 *//*from ww w  .j  a  v a  2s  .com*/
public Connection getConnection(ServerRequestContext context) throws RegistryException {
    Connection connection = null;
    if (log.isTraceEnabled()) {
        log.debug("SQLPersistenceManagerImpl.getConnection");
        numConnectionsOpen++;
    }
    try {
        if (useConnectionPool) {
            if (ds != null) {
                connection = ds.getConnection();
                if (connection == null) {
                    log.info(ServerResourceBundle.getInstance().getString(
                            "message.ErrorUnableToOpenDbConnctionForDataSource=", new Object[] { ds }));
                }
            }

            if (connection == null) {
                // Default to registry server ConnectionPool
                connection = connectionPool.getConnection(context.getId());
            }
            connection.setTransactionIsolation(transactionIsolation);
            connection.setAutoCommit(false);
        } else {
            // create connection directly
            if ((user != null) && (user.length() > 0)) {
                connection = java.sql.DriverManager.getConnection(databaseURL, user, password);
            } else {
                connection = java.sql.DriverManager.getConnection(databaseURL);
            }
            // Set Transaction Isolation and AutoComit
            // WARNING: till present Oracle dirvers (9.2.0.5) do not accept
            // setTransactionIsolation being called after
            // setAutoCommit(false)
            connection.setTransactionIsolation(transactionIsolation);
            connection.setAutoCommit(false);
        }
    } catch (SQLException e) {
        throw new RegistryException(
                ServerResourceBundle.getInstance().getString("message.connectToDatabaseFailed"), e);
    }

    return connection;
}

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 .  com
 * 
 * @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:fll.db.Queries.java

/**
 * Insert or update a performance score.
 * //  w  w w  . j  a  va  2s .com
 * @throws SQLException on a database error.
 * @throws RuntimeException if a parameter is missing.
 * @throws ParseException if the team number cannot be parsed
 */
public static void insertOrUpdatePerformanceScore(final ChallengeDescription description,
        final Connection connection, final HttpServletRequest request)
        throws SQLException, ParseException, RuntimeException {
    final int oldTransactionIsolation = connection.getTransactionIsolation();
    final boolean oldAutoCommit = connection.getAutoCommit();
    try {
        // make sure that we don't get into a race with another thread
        connection.setAutoCommit(false);
        connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

        final int rowsUpdated = updatePerformanceScore(description, connection, request);
        if (rowsUpdated < 1) {
            insertPerformanceScore(description, connection, request);
        }
        connection.commit();
    } finally {
        connection.setTransactionIsolation(oldTransactionIsolation);
        connection.setAutoCommit(oldAutoCommit);
    }
}

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

final synchronized void setTransactionIsolation(Connection conn) throws SQLException {
    if (this.dbTxIsolation == null) {
        this.dbTxIsolation = conn.getTransactionIsolation();
        assert this.dbTxIsolation != null;
    }/*from   w  w w .  j a v  a 2s  .c om*/
    // no need to try to change the level if the DB doesn't support transactions
    if (this.dbTxIsolation != Connection.TRANSACTION_NONE
            && (!this.checkOnceDBTxIsolation || this.dbTxIsolation != this.txIsolation)) {
        // if not check once, it's the desired action, so don't log
        if (this.checkOnceDBTxIsolation)
            Log.get().config("Setting transaction isolation to " + this.txIsolation);
        conn.setTransactionIsolation(this.txIsolation);
    }
}