Java Code Examples for org.wso2.carbon.identity.core.util.IdentityDatabaseUtil#rollBack()

The following examples show how to use org.wso2.carbon.identity.core.util.IdentityDatabaseUtil#rollBack() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void revokeTokensBatch(String[] tokens) throws IdentityOAuth2Exception {

        String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement ps = null;
        try {
            String sqlQuery = SQLQueries.REVOKE_ACCESS_TOKEN.replace(IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
            ps = connection.prepareStatement(sqlQuery);
            for (String token : tokens) {
                ps.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED);
                ps.setString(2, UUID.randomUUID().toString());
                ps.setString(3, persistenceProcessor.getProcessedAccessTokenIdentifier(token));
                ps.addBatch();
            }
            ps.executeBatch();
            connection.commit();
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollBack(connection);
            throw new IdentityOAuth2Exception("Error occurred while revoking Access Tokens : " + tokens.toString(), e);
        }  finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
        }
    }
 
Example 2
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public Set<String> getActiveTokensForConsumerKey(String consumerKey) throws IdentityOAuth2Exception {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    Set<String> accessTokens = new HashSet<>();
    try {
        String sqlQuery = SQLQueries.GET_ACCESS_TOKENS_FOR_CONSUMER_KEY;
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, consumerKey);
        ps.setString(2, OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE);
        rs = ps.executeQuery();
        while (rs.next()) {
            accessTokens.add(rs.getString(1));
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while getting access tokens from acces token table for " +
                "the application with consumer key : " + consumerKey, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
    return accessTokens;
}
 
Example 3
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public Set<String> getAuthorizationCodesForConsumerKey(String consumerKey) throws IdentityOAuth2Exception {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    Set<String> authorizationCodes = new HashSet<>();
    try {
        String sqlQuery = SQLQueries.GET_AUTHORIZATION_CODES_FOR_CONSUMER_KEY;
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, consumerKey);
        rs = ps.executeQuery();
        while (rs.next()) {
            authorizationCodes.add(rs.getString(1));
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while getting authorization codes from authorization code table for the application with consumer key : " + consumerKey, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
    return authorizationCodes;
}
 
Example 4
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void renameUserStoreDomainInAccessTokenTable(int tenantId, String currentUserStoreDomain, String
        newUserStoreDomain) throws IdentityOAuth2Exception {

    //we do not support access token partitioning here
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    try {

        String sqlQuery = SQLQueries.RENAME_USER_STORE_IN_ACCESS_TOKENS_TABLE;
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, newUserStoreDomain.toUpperCase());
        ps.setInt(2, tenantId);
        ps.setString(3, currentUserStoreDomain.toUpperCase());
        int count = ps.executeUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Number of rows being updated : " + count);
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while renaming user store : " + currentUserStoreDomain +
                " in tenant :" + tenantId, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
}
 
Example 5
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void renameUserStoreDomainInAuthorizationCodeTable(int tenantId, String currentUserStoreDomain, String
        newUserStoreDomain) throws IdentityOAuth2Exception {

    //we do not support access token partitioning here
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    try {
        String sqlQuery = SQLQueries.RENAME_USER_STORE_IN_AUTHORIZATION_CODES_TABLE;
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, newUserStoreDomain.toUpperCase());
        ps.setInt(2, tenantId);
        ps.setString(3, currentUserStoreDomain.toUpperCase());
        int count = ps.executeUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Number of rows being updated : " + count);
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while renaming user store : " + currentUserStoreDomain +
                "in tenant :" + tenantId, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
}
 
Example 6
Source File: DBStsDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This is for adding token to DB.
 *
 * @param token Token
 */
public void addToken(Token token) throws TrustException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet rs = null;

    String query = DBQueries.ADD_TOKEN;

    try {
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, token.getId());
        byte[] tokenByteContainer = getTokenContent(token);
        InputStream tokenInputStream = new ByteArrayInputStream(tokenByteContainer);
        prepStmt.setBinaryStream(2, tokenInputStream, tokenByteContainer.length);
        prepStmt.setTimestamp(3, new Timestamp(token.getCreated().getTime()));
        prepStmt.setTimestamp(4, new Timestamp(token.getExpires().getTime()));
        prepStmt.setInt(5, token.getState());
        prepStmt.execute();
        connection.commit();

    } catch (Exception e) {
        IdentityDatabaseUtil.rollBack(connection);
        String msg = "Failed to add token";
        throw new TrustException(msg, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rs, prepStmt);
    }

}
 
Example 7
Source File: DBStsDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This is for updating the token in DB
 *
 * @param token Token
 */
public void updateToken(Token token) throws TrustException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    String query = DBQueries.UPDATE_TOKEN;

    try {
        prepStmt = connection.prepareStatement(query);
        byte[] tokenByteContainer = getTokenContent(token);
        InputStream tokenInputStream = new ByteArrayInputStream(tokenByteContainer);
        prepStmt.setBinaryStream(1, tokenInputStream, tokenByteContainer.length);
        prepStmt.setTimestamp(2, new Timestamp(token.getCreated().getTime()));
        prepStmt.setTimestamp(3, new Timestamp(token.getExpires().getTime()));
        prepStmt.setInt(4, token.getState());
        prepStmt.setString(5, token.getId());
        prepStmt.executeUpdate();
        connection.commit();

    } catch (Exception e) {
        IdentityDatabaseUtil.rollBack(connection);
        String msg = "Failed to update token ";
        throw new TrustException(msg, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rs, prepStmt);
    }

}
 
Example 8
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void revokeTokensIndividual(String[] tokens) throws IdentityOAuth2Exception {

        String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement ps = null;
        try {
            for (String token: tokens){
                if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
                        OAuth2Util.checkUserNameAssertionEnabled()) {
                    accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromAccessToken(token);
                }
                String sqlQuery = SQLQueries.REVOKE_ACCESS_TOKEN.replace(
                        IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
                ps = connection.prepareStatement(sqlQuery);
                ps.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED);
                ps.setString(2, UUID.randomUUID().toString());
                ps.setString(3, persistenceProcessor.getProcessedAccessTokenIdentifier(token));
                int count = ps.executeUpdate();
                if (log.isDebugEnabled()) {
                    log.debug("Number of rows being updated : " + count);
                }
            }

            connection.commit();
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollBack(connection);
            throw new IdentityOAuth2Exception("Error occurred while revoking Access Token : " + tokens.toString(), e);
        }  finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
        }
    }
 
Example 9
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Ths method is to revoke specific tokens
 *
 * @param tokenId token that needs to be revoked
 * @throws IdentityOAuth2Exception if failed to revoke the access token
 */
public void revokeToken(String tokenId, String userId) throws IdentityOAuth2Exception {

    String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    try {
        if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
            OAuth2Util.checkUserNameAssertionEnabled()) {
            accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromUserId(userId);
        }
        String sqlQuery = SQLQueries.REVOKE_ACCESS_TOKEN_BY_TOKEN_ID.replace(
                IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED);
        ps.setString(2, UUID.randomUUID().toString());
        ps.setString(3, tokenId);
        int count = ps.executeUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Number of rows being updated : " + count);
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while revoking Access Token with ID : " + tokenId, e);
    }  finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
}
 
Example 10
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param authenticatedUser
 * @return
 * @throws IdentityOAuth2Exception
 */
public Set<String> getAuthorizationCodesForUser(AuthenticatedUser authenticatedUser) throws
        IdentityOAuth2Exception {

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    Set<String> authorizationCodes = new HashSet<>();
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authenticatedUser.toString());
    try {
        String sqlQuery = SQLQueries.GET_AUTHORIZATION_CODES_BY_AUTHZUSER;
        if (!isUsernameCaseSensitive) {
            sqlQuery = sqlQuery.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        ps = connection.prepareStatement(sqlQuery);
        if (isUsernameCaseSensitive) {
            ps.setString(1, authenticatedUser.getUserName());
        } else {
            ps.setString(1, authenticatedUser.getUserName().toLowerCase());
        }
        ps.setString(2,Integer.toString(OAuth2Util.getTenantId(authenticatedUser.getTenantDomain())));
        ps.setString(3, authenticatedUser.getUserStoreDomain());
        rs = ps.executeQuery();
        while (rs.next()){
            authorizationCodes.add(rs.getString(1));
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while revoking Access Token with user Name : " +
                authenticatedUser.getUserName() + " tenant ID : " + OAuth2Util.getTenantId(authenticatedUser
                .getTenantDomain()), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
    return authorizationCodes;
}
 
Example 11
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * @param authenticatedUser
 * @return
 * @throws IdentityOAuth2Exception
 */
public Set<String> getAccessTokensForUser(AuthenticatedUser authenticatedUser) throws
        IdentityOAuth2Exception {
    String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    Set<String> accessTokens = new HashSet<>();
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authenticatedUser.toString());
    try {
        if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
                OAuth2Util.checkUserNameAssertionEnabled()) {
            accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromUserId(authenticatedUser.toString());
        }
        String sqlQuery = SQLQueries.GET_ACCESS_TOKEN_BY_AUTHZUSER.replace(
                IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
        if (!isUsernameCaseSensitive){
            sqlQuery = sqlQuery.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        ps = connection.prepareStatement(sqlQuery);
        if (isUsernameCaseSensitive) {
            ps.setString(1, authenticatedUser.getUserName());
        } else {
            ps.setString(1, authenticatedUser.getUserName().toLowerCase());
        }
        ps.setString(2, Integer.toString(OAuth2Util.getTenantId(authenticatedUser.getTenantDomain())));
        ps.setString(3, OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE);
        ps.setString(4, authenticatedUser.getUserStoreDomain());
        rs = ps.executeQuery();
        while (rs.next()){
            accessTokens.add(rs.getString(1));
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while revoking Access Token with user Name : " +
                authenticatedUser.getUserName() + " tenant ID : " + OAuth2Util.getTenantId(authenticatedUser
                .getTenantDomain()), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
    return accessTokens;
}
 
Example 12
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public List<AuthzCodeDO> getLatestAuthorizationCodesOfTenant(int tenantId) throws IdentityOAuth2Exception {

        //we do not support access token partitioning here
        Connection connection = IdentityDatabaseUtil.getDBConnection();;
        PreparedStatement ps = null;
        ResultSet rs = null;

        List<AuthzCodeDO> latestAuthzCodes = new ArrayList<>();
        try {
            String sqlQuery = SQLQueries.LIST_LATEST_AUTHZ_CODES_IN_TENANT;
            ps = connection.prepareStatement(sqlQuery);
            ps.setInt(1, tenantId);
            rs = ps.executeQuery();
            while (rs.next()) {
                String authzCodeId = rs.getString(1);
                String authzCode = rs.getString(2);
                String consumerKey = rs.getString(3);
                String authzUser = rs.getString(4);
                String[] scope = OAuth2Util.buildScopeArray(rs.getString(5));
                Timestamp issuedTime = rs.getTimestamp(6, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
                long validityPeriodInMillis = rs.getLong(7);
                String callbackUrl = rs.getString(8);
                String userStoreDomain = rs.getString(9);

                AuthenticatedUser user = new AuthenticatedUser();
                user.setUserName(authzUser);
                user.setUserStoreDomain(userStoreDomain);
                user.setTenantDomain(OAuth2Util.getTenantDomain(tenantId));
                latestAuthzCodes.add(new AuthzCodeDO(user, scope, issuedTime, validityPeriodInMillis, callbackUrl,
                        consumerKey, authzCode, authzCodeId));
            }
            connection.commit();
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollBack(connection);
            throw new IdentityOAuth2Exception("Error occurred while retrieving latest authorization codes of tenant " +
                    ":" + tenantId, e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, rs, ps);
        }
        return latestAuthzCodes;
    }
 
Example 13
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public List<AuthzCodeDO> getLatestAuthorizationCodesOfUserStore(int tenantId, String userStorDomain) throws
        IdentityOAuth2Exception {

    //we do not support access token partitioning here
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;

    List<AuthzCodeDO> latestAuthzCodes = new ArrayList<>();
    try {
        String sqlQuery = SQLQueries.LIST_LATEST_AUTHZ_CODES_IN_USER_DOMAIN;
        ps = connection.prepareStatement(sqlQuery);
        ps.setInt(1, tenantId);
        ps.setString(2, userStorDomain.toUpperCase());
        rs = ps.executeQuery();
        while (rs.next()) {
            String authzCodeId = rs.getString(1);
            String authzCode = rs.getString(2);
            String consumerKey = rs.getString(3);
            String authzUser = rs.getString(4);
            String[] scope = OAuth2Util.buildScopeArray(rs.getString(5));
            Timestamp issuedTime = rs.getTimestamp(6, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
            long validityPeriodInMillis = rs.getLong(7);
            String callbackUrl = rs.getString(8);

            AuthenticatedUser user = new AuthenticatedUser();
            user.setUserName(authzUser);
            user.setUserStoreDomain(userStorDomain);
            user.setTenantDomain(OAuth2Util.getTenantDomain(tenantId));
            latestAuthzCodes.add(new AuthzCodeDO(user, scope, issuedTime, validityPeriodInMillis, callbackUrl,
                    consumerKey, authzCode, authzCodeId));
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while retrieving latest authorization codes of user " +
                "store : " + userStorDomain + " in tenant :" + tenantId, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rs, ps);
    }
    return latestAuthzCodes;
}
 
Example 14
Source File: IdentityApplicationManagementUtil.java    From carbon-identity-framework with Apache License 2.0 2 votes vote down vote up
/**
 * Utility method to rollback a database connection
 *
 * @param dbConnection Database <code>Connection</code> object
 * @deprecated Please use IdentityDatabaseUtil.rollbackTransaction(Connection dbConnection) instead.
 */
@Deprecated
public static void rollBack(Connection dbConnection) {

    IdentityDatabaseUtil.rollBack(dbConnection);
}
 
Example 15
Source File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 2 votes vote down vote up
/**
 * Utility method to rollback a database connection
 *
 * @param dbConnection Database <code>Connection</code> object
 */
public static void rollBack(Connection dbConnection) {

    IdentityDatabaseUtil.rollBack(dbConnection);
}