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.wso2.carbon.registry.core.jdbc.dataaccess.JDBCTransactionManager.java

public void beginTransaction() throws RegistryException {
    if (dataAccessManager.getDatabaseTransaction().getNestedDepth() != 0) {
        if (log.isTraceEnabled()) {
            log.trace("The transaction was not started, because it is called within a "
                    + "transaction, nested depth: "
                    + dataAccessManager.getDatabaseTransaction().getNestedDepth() + ".");
        }/*from   w  w w .  j  a va2 s. c  o  m*/
        dataAccessManager.getDatabaseTransaction().incNestedDepth();
        if (JDBCDatabaseTransaction.getConnection() != null) {
            return;
        } else {
            // If we get here, there has been some issue related to connection failure.
            // There is no point in using the connection that is already existing on this
            // thread. We need to start using a new one.
            while (dataAccessManager.getDatabaseTransaction().getNestedDepth() > 0) {
                dataAccessManager.getDatabaseTransaction().decNestedDepth();
            }
            while (dataAccessManager.getDatabaseTransaction().getNestedDepth() < 0) {
                dataAccessManager.getDatabaseTransaction().incNestedDepth();
            }
        }
    }

    Connection conn;
    try {
        if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
            String msg = "Failed to begin transaction. Invalid data access manager.";
            log.error(msg);
            throw new RegistryException(msg);
        }
        DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource();
        conn = dataSource.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);
        dataAccessManager.getDatabaseTransaction().incNestedDepth();
    } catch (SQLException e) {
        String msg = "Failed to start new registry transaction.";
        log.error(msg, e);
        throw new RegistryException(msg, e);
    }

    JDBCDatabaseTransaction.setConnection(conn);
}

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

private void addLogRecords(LogRecord[] logRecords, JDBCDataAccessManager dataAccessManager)
        throws RepositoryException {
    PreparedStatement s = null;//from   www .jav  a2  s.co m
    Connection conn = null;

    try {
        conn = dataAccessManager.getDataSource().getConnection();
        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        conn.setAutoCommit(false);
        String sql = "INSERT INTO REG_LOG (REG_PATH, REG_USER_ID, REG_LOGGED_TIME, "
                + "REG_ACTION, REG_ACTION_DATA, REG_TENANT_ID) " + "VALUES (?, ?, ?, ?, ?, ?)";

        s = conn.prepareStatement(sql);
        for (LogRecord logRecord : logRecords) {
            s.clearParameters();
            s.setString(1, logRecord.getResourcePath());
            s.setString(2, logRecord.getUserName());
            s.setTimestamp(3, new Timestamp(logRecord.getTimestamp().getTime()));
            s.setInt(4, logRecord.getAction().getId());
            s.setString(5, logRecord.getActionData());
            s.setInt(6, logRecord.getTenantId());
            s.addBatch();
        }
        int[] status = s.executeBatch();
        if (log.isDebugEnabled()) {
            log.debug("Successfully added " + status.length + " log records.");
        }
        conn.commit();

    } catch (SQLException e) {
        try {
            if (conn != null) {
                conn.rollback();
            }
        } catch (SQLException e1) {
            log.error("Failed to rollback log insertion.", e);
        }
        String msg = "Failed to update log batch records " + ". " + e.getMessage();
        log.error(msg, e);
        throw new RepositoryDBException(msg, e);
    } finally {
        try {
            if (s != null) {
                s.close();
            }
            if (conn != null && !(conn.isClosed())) {
                conn.close();
            }
        } catch (SQLException ex) {
            String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

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

/**
 * Method to add resource path entry to the database.
 *
 * @param path         the path to add./*from ww w . j  a v a2 s. com*/
 * @param parentPathId the parent path's id.
 *
 * @return the path's id.
 * @throws RepositoryException if the data access manager was invalid.
 * @throws SQLException      if an error occurs while adding the entry.
 */
public int addEntry(String path, int parentPathId) throws SQLException, RepositoryException {
    ResultSet results = null;
    PreparedStatement ps = null;
    PreparedStatement ps1 = null;
    DataAccessManager dataAccessManager;

    if (CurrentContext.getRespository() != null
            && InternalUtils.getRepositoryContext(CurrentContext.getRespository()) != null) {
        dataAccessManager = InternalUtils.getRepositoryContext(CurrentContext.getRespository())
                .getDataAccessManager();
    } else {
        dataAccessManager = RepositoryContext.getBaseInstance().getDataAccessManager();
    }

    if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
        String msg = "Failed to add path entry. Invalid data access manager.";
        log.error(msg);
        throw new RepositoryServerException(msg);
    }

    DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource();
    Connection conn = dataSource.getConnection();

    if (conn != null) {
        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        conn.setAutoCommit(false);
    } else {
        log.error("Unable to acquire connection to database.");
        return -1;
    }

    boolean success = false;
    int pathId = 0;

    try {
        String sql = "INSERT INTO REG_PATH(REG_PATH_VALUE, REG_PATH_PARENT_ID, REG_TENANT_ID) VALUES (?, ?, ?)";
        String sql1 = "SELECT MAX(REG_PATH_ID) FROM REG_PATH";

        String dbProductName = conn.getMetaData().getDatabaseProductName();
        boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName);

        if (returnsGeneratedKeys) {
            ps = conn.prepareStatement(sql,
                    new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "REG_PATH_ID") });
        } else {
            ps = conn.prepareStatement(sql);
        }

        ps.setString(1, path);
        ps.setInt(2, parentPathId);
        ps.setInt(3, CurrentContext.getTenantId());

        if (returnsGeneratedKeys) {
            ps.executeUpdate();
            results = ps.getGeneratedKeys();
        } else {
            synchronized (ADD_ENTRY_LOCK) {
                ps.executeUpdate();
                ps1 = conn.prepareStatement(sql1);
                results = ps1.executeQuery();
            }
        }

        if (results.next()) {
            pathId = results.getInt(1);
            if (pathId > 0) {
                success = true;
                return pathId;
            }
        }
    } catch (SQLException e) {
        // we have to be expecting an exception with the duplicate value for the path value
        // which can be further checked from here..
        String msg = "Failed to insert resource to " + path + ". " + e.getMessage();
        log.error(msg, e);
        throw e;
    } finally {
        if (success) {
            try {
                conn.commit();
                RepositoryCacheEntry e = new RepositoryCacheEntry(pathId);
                String connectionId = null;

                if (conn.getMetaData() != null) {
                    connectionId = InternalUtils.getConnectionId(conn);
                }

                RepositoryCacheKey key = InternalUtils.buildRegistryCacheKey(connectionId,
                        CurrentContext.getTenantId(), path);
                getCache().put(key, e);
            } catch (SQLException e) {
                String msg = "Failed to commit transaction. Inserting " + path + ". " + e.getMessage();
                log.error(msg, e);
            } finally {
                try {
                    try {
                        if (results != null) {
                            results.close();
                        }
                    } finally {
                        try {
                            if (ps1 != null) {
                                ps1.close();
                            }
                        } finally {
                            try {
                                if (ps != null) {
                                    ps.close();
                                }
                            } finally {
                                conn.close();
                            }
                        }
                    }
                } catch (SQLException e) {
                    String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR + e.getMessage();
                    log.error(msg, e);
                }
            }
        } else {
            try {
                conn.rollback();

            } catch (SQLException e) {
                String msg = "Failed to rollback transaction. Inserting " + path + ". " + e.getMessage();
                log.error(msg, e);
            } finally {
                try {
                    try {
                        if (results != null) {
                            results.close();
                        }
                    } finally {
                        try {
                            if (ps != null) {
                                ps.close();
                            }
                        } finally {
                            if (conn != null) {
                                conn.close();
                            }
                        }
                    }
                } catch (SQLException e) {
                    String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR + e.getMessage();
                    log.error(msg, e);
                }
            }
        }
    }
    return -1;
}

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

public int getChildCount(CollectionImpl collection, DataAccessManager dataAccessManager)
        throws RepositoryException {
    int childCount = -1;
    if (Transaction.isStarted()) {
        childCount = getChildCount(collection, JDBCDatabaseTransaction.getConnection());
    } else {// w ww  . j  a v a  2 s . co  m
        Connection conn = null;
        boolean transactionSucceeded = false;
        try {
            if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
                String msg = "Failed to get child count. Invalid data access manager.";
                log.error(msg);
                throw new RepositoryException(msg);
            }
            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);

            childCount = getChildCount(collection, conn);
            transactionSucceeded = true;
        } catch (SQLException e) {
            String msg = "Failed to get the child count of resource " + collection.getPath() + ". "
                    + e.getMessage();
            log.error(msg, e);
            throw new RepositoryException(msg, e);
        } finally {
            if (transactionSucceeded) {
                try {
                    conn.commit();
                } catch (SQLException e) {
                    log.error("Failed to commit the database connection used in "
                            + "getting child count of the collection " + collection.getPath());
                }
            } else if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException e) {
                    log.error("Failed to rollback the database connection used in "
                            + "getting child count of the collection " + collection.getPath());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("Failed to close the database connection used in "
                            + "getting child count of collection " + collection.getPath());
                }
            }
        }
    }
    return childCount;
}

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

public void fillChildren(CollectionImpl collection, DataAccessManager dataAccessManager)
        throws RepositoryException {
    if (Transaction.isStarted()) {
        fillChildren(collection, 0, -1, JDBCDatabaseTransaction.getConnection());
    } else {// www  . j  ava 2s  . c  o  m
        Connection conn = null;
        boolean transactionSucceeded = false;
        try {
            if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
                String msg = "Failed to fill children. Invalid data access manager.";
                log.error(msg);
                throw new RepositoryException(msg);
            }
            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);

            fillChildren(collection, 0, -1, conn);
            transactionSucceeded = true;
        } catch (SQLException e) {

            String msg = "Failed to get child paths of " + collection.getPath() + ". " + e.getMessage();
            log.error(msg, e);
            throw new RepositoryException(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 " + collection.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 " + collection.getPath());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("Failed to close the database connection opened in "
                            + "getting the child paths of " + collection.getPath(), e);
                }
            }
        }
    }
}

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

public String[] getChildren(CollectionImpl collection, int start, int pageLen,
        DataAccessManager dataAccessManager) throws RepositoryException {
    String[] childPaths = null;// w  w  w .  j av a 2 s .c om

    if (Transaction.isStarted()) {
        childPaths = getChildren(collection, start, pageLen, JDBCDatabaseTransaction.getConnection());
    } else {
        Connection conn = null;
        boolean transactionSucceeded = false;
        try {
            if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
                String msg = "Failed to get children. Invalid data access manager.";
                log.error(msg);
                throw new RepositoryDBException(msg);
            }
            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 = getChildren(collection, start, pageLen, conn);
            transactionSucceeded = true;
        } catch (SQLException e) {

            String msg = "Failed to get the child paths " + pageLen + " child paths from " + start
                    + " of resource " + collection.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 " + collection.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 " + collection.getPath());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("Failed to close the database connection used in "
                            + "getting child paths of the collection " + collection.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 a v  a  2s . com

    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.repository.core.jdbc.dataaccess.JDBCTransactionManager.java

public void beginTransaction() throws RepositoryException {
    if (dataAccessManager.getDatabaseTransaction().getNestedDepth() != 0) {
        if (log.isTraceEnabled()) {
            log.trace(//from   ww w . j a v a 2s . c  om
                    "The transaction was not started, because it is called within a transaction, nested depth: "
                            + dataAccessManager.getDatabaseTransaction().getNestedDepth() + ".");
        }

        dataAccessManager.getDatabaseTransaction().incNestedDepth();

        if (JDBCDatabaseTransaction.getConnection() != null) {
            return;
        } else {
            // If we get here, there has been some issue related to connection failure.
            // There is no point in using the connection that is already existing on this
            // thread. We need to start using a new one.
            while (dataAccessManager.getDatabaseTransaction().getNestedDepth() > 0) {
                dataAccessManager.getDatabaseTransaction().decNestedDepth();
            }

            while (dataAccessManager.getDatabaseTransaction().getNestedDepth() < 0) {
                dataAccessManager.getDatabaseTransaction().incNestedDepth();
            }
        }
    }

    Connection conn;

    try {
        if (!(dataAccessManager instanceof JDBCDataAccessManager)) {
            String msg = "Failed to begin transaction. Invalid data access manager.";
            log.error(msg);
            throw new RepositoryDBException(msg);
        }

        DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource();
        conn = dataSource.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);
        dataAccessManager.getDatabaseTransaction().incNestedDepth();
    } catch (SQLException e) {
        String msg = "Failed to start new registry transaction.";
        log.error(msg, e);
        throw new RepositoryDBException(msg, e);
    }

    JDBCDatabaseTransaction.setConnection(conn);
}

From source file:org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager.java

/**
 * @return/*from w  w  w . j  av  a 2  s  . c  o  m*/
 * @throws SQLException
 * @throws UserStoreException
 */
protected Connection getDBConnection() throws SQLException, UserStoreException {
    Connection dbConnection = getJDBCDataSource().getConnection();
    dbConnection.setAutoCommit(false);
    if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    }
    return dbConnection;
}

From source file:org.wso2.carbon.user.core.util.DatabaseUtil.java

public static Connection getDBConnection(DataSource dataSource) throws SQLException {
    Connection dbConnection = dataSource.getConnection();
    dbConnection.setAutoCommit(false);/* w ww  . ja  va  2 s . c  o m*/
    if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    }
    return dbConnection;
}