public String[] addOAuthConsumer(String username, int tenantId)
      throws IdentityOAuthAdminException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    String sqlStmt = null;
    String consumerKey;
    String consumerSecret = OAuthUtil.getRandomNumber();

    do {
      consumerKey = OAuthUtil.getRandomNumber();
    } while (isDuplicateConsumer(consumerKey));

    try {
      connection = JDBCPersistenceManager.getInstance().getDBConnection();
      sqlStmt = SQLQueries.OAuthAppDAOSQLQueries.ADD_OAUTH_CONSUMER;
      prepStmt = connection.prepareStatement(sqlStmt);
      prepStmt.setString(1, consumerKey);
      prepStmt.setString(2, consumerSecret);
      prepStmt.setString(3, username);
      prepStmt.setInt(4, tenantId);
      // it is assumed that the OAuth version is 1.0a because this is required with OAuth 1.0a
      prepStmt.setString(5, OAuthConstants.OAuthVersions.VERSION_1A);
      prepStmt.execute();

      connection.commit();

    } catch (IdentityException e) {
      String errorMsg = "Error when getting an Identity Persistence Store instance.";
      log.error(errorMsg, e);
      throw new IdentityOAuthAdminException(errorMsg, e);
    } catch (SQLException e) {
      log.error("Error when executing the SQL : " + sqlStmt);
      log.error(e.getMessage(), e);
      throw new IdentityOAuthAdminException("Error when adding a new OAuth consumer.");
    } finally {
      IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
    return new String[] {consumerKey, consumerSecret};
  }
  /**
   * Revoke tokens issued to OAuth clients
   *
   * @param revokeRequestDTO DTO representing consumerKey, consumerSecret and tokens[]
   * @return revokeRespDTO DTO representing success or failure message
   */
  public OAuthRevocationResponseDTO revokeTokenByOAuthClient(
      OAuthRevocationRequestDTO revokeRequestDTO) {

    // fix here remove associated cache entry
    TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
    OAuthRevocationResponseDTO revokeResponseDTO = new OAuthRevocationResponseDTO();

    try {
      if (StringUtils.isNotEmpty(revokeRequestDTO.getConsumerKey())
          && StringUtils.isNotEmpty(revokeRequestDTO.getToken())) {

        boolean refreshTokenFirst = false;
        if (StringUtils.equals(
            GrantType.REFRESH_TOKEN.toString(), revokeRequestDTO.getToken_type())) {
          refreshTokenFirst = true;
        }

        RefreshTokenValidationDataDO refreshTokenDO = null;
        AccessTokenDO accessTokenDO = null;

        if (refreshTokenFirst) {

          refreshTokenDO =
              tokenMgtDAO.validateRefreshToken(
                  revokeRequestDTO.getConsumerKey(), revokeRequestDTO.getToken());

          if (refreshTokenDO == null
              || StringUtils.isEmpty(refreshTokenDO.getRefreshTokenState())
              || !(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(
                      refreshTokenDO.getRefreshTokenState())
                  || OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED.equals(
                      refreshTokenDO.getRefreshTokenState()))) {

            accessTokenDO = tokenMgtDAO.retrieveAccessToken(revokeRequestDTO.getToken(), true);
            refreshTokenDO = null;
          }

        } else {
          accessTokenDO = tokenMgtDAO.retrieveAccessToken(revokeRequestDTO.getToken(), true);
          if (accessTokenDO == null) {

            refreshTokenDO =
                tokenMgtDAO.validateRefreshToken(
                    revokeRequestDTO.getConsumerKey(), revokeRequestDTO.getToken());

            if (refreshTokenDO == null
                || StringUtils.isEmpty(refreshTokenDO.getRefreshTokenState())
                || !(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(
                        refreshTokenDO.getRefreshTokenState())
                    || OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED.equals(
                        refreshTokenDO.getRefreshTokenState()))) {
              return revokeResponseDTO;
            }
          }
        }

        String grantType = StringUtils.EMPTY;

        if (accessTokenDO != null) {
          grantType = accessTokenDO.getGrantType();
        } else if (refreshTokenDO != null) {
          grantType = refreshTokenDO.getGrantType();
        }

        if (!StringUtils.equals(OAuthConstants.GrantTypes.IMPLICIT, grantType)
            && !OAuth2Util.authenticateClient(
                revokeRequestDTO.getConsumerKey(), revokeRequestDTO.getConsumerSecret())) {

          OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
          revokeRespDTO.setError(true);
          revokeRespDTO.setErrorCode(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
          revokeRespDTO.setErrorMsg("Unauthorized Client");

          return revokeRespDTO;
        }

        if (refreshTokenDO != null) {

          org.wso2.carbon.identity.oauth.OAuthUtil.clearOAuthCache(
              revokeRequestDTO.getConsumerKey(),
              refreshTokenDO.getAuthorizedUser(),
              OAuth2Util.buildScopeString(refreshTokenDO.getScope()));

          org.wso2.carbon.identity.oauth.OAuthUtil.clearOAuthCache(
              revokeRequestDTO.getConsumerKey(), refreshTokenDO.getAuthorizedUser());

          org.wso2.carbon.identity.oauth.OAuthUtil.clearOAuthCache(refreshTokenDO.getAccessToken());
          tokenMgtDAO.revokeTokens(new String[] {refreshTokenDO.getAccessToken()});

          addRevokeResponseHeaders(
              revokeResponseDTO,
              refreshTokenDO.getAccessToken(),
              revokeRequestDTO.getToken(),
              refreshTokenDO.getAuthorizedUser().toString());

        } else if (accessTokenDO != null) {
          org.wso2.carbon.identity.oauth.OAuthUtil.clearOAuthCache(
              revokeRequestDTO.getConsumerKey(),
              accessTokenDO.getAuthzUser(),
              OAuth2Util.buildScopeString(accessTokenDO.getScope()));
          org.wso2.carbon.identity.oauth.OAuthUtil.clearOAuthCache(
              revokeRequestDTO.getConsumerKey(), accessTokenDO.getAuthzUser());
          org.wso2.carbon.identity.oauth.OAuthUtil.clearOAuthCache(revokeRequestDTO.getToken());
          tokenMgtDAO.revokeTokens(new String[] {revokeRequestDTO.getToken()});
          addRevokeResponseHeaders(
              revokeResponseDTO,
              revokeRequestDTO.getToken(),
              accessTokenDO.getRefreshToken(),
              accessTokenDO.getAuthzUser().toString());
        }

        return revokeResponseDTO;

      } else {
        revokeResponseDTO.setError(true);
        revokeResponseDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
        revokeResponseDTO.setErrorMsg("Invalid revocation request");
        return revokeResponseDTO;
      }

    } catch (InvalidOAuthClientException e) {
      log.error("Unauthorized Client", e);
      OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
      revokeRespDTO.setError(true);
      revokeRespDTO.setErrorCode(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
      revokeRespDTO.setErrorMsg("Unauthorized Client");
      return revokeRespDTO;
    } catch (IdentityException e) {
      log.error("Error occurred while revoking authorization grant for applications", e);
      OAuthRevocationResponseDTO revokeRespDTO = new OAuthRevocationResponseDTO();
      revokeRespDTO.setError(true);
      revokeRespDTO.setErrorCode(OAuth2ErrorCodes.SERVER_ERROR);
      revokeRespDTO.setErrorMsg(
          "Error occurred while revoking authorization grant for applications");
      return revokeRespDTO;
    }
  }