/** {@inheritDoc} */
  public AccessToken readAccessToken(OAuth2Request request, String tokenId)
      throws ServerException, InvalidGrantException, NotFoundException {

    logger.message("Reading access token");

    JsonValue token;

    // Read from CTS
    try {
      token = tokenStore.read(tokenId);
    } catch (CoreTokenException e) {
      logger.error("Unable to read access token corresponding to id: " + tokenId, e);
      throw new ServerException("Could not read token in CTS: " + e.getMessage());
    }

    if (token == null) {
      logger.error("Unable to read access token corresponding to id: " + tokenId);
      throw new InvalidGrantException("Could not read token in CTS");
    }

    OpenAMAccessToken accessToken = new OpenAMAccessToken(token);
    validateTokenRealm(accessToken.getRealm(), request);

    request.setToken(AccessToken.class, accessToken);
    return accessToken;
  }
  /** {@inheritDoc} */
  public AuthorizationCode readAuthorizationCode(OAuth2Request request, String code)
      throws InvalidGrantException, ServerException, NotFoundException {
    if (logger.messageEnabled()) {
      logger.message("Reading Authorization code: " + code);
    }
    final JsonValue token;

    // Read from CTS
    try {
      token = tokenStore.read(code);
    } catch (CoreTokenException e) {
      logger.error("Unable to read authorization code corresponding to id: " + code, e);
      throw new ServerException("Could not read token from CTS: " + e.getMessage());
    }

    if (token == null) {
      logger.error("Unable to read authorization code corresponding to id: " + code);
      throw new InvalidGrantException("The provided access grant is invalid, expired, or revoked.");
    }

    OpenAMAuthorizationCode authorizationCode = new OpenAMAuthorizationCode(token);
    validateTokenRealm(authorizationCode.getRealm(), request);

    request.setToken(AuthorizationCode.class, authorizationCode);
    return authorizationCode;
  }
  /** {@inheritDoc} */
  public void deleteAccessToken(String accessTokenId) throws ServerException {
    logger.message("Deleting access token");

    // Delete the code
    try {
      tokenStore.delete(accessTokenId);
    } catch (CoreTokenException e) {
      logger.error("Unable to delete access token corresponding to id: " + accessTokenId, e);
      throw new ServerException("Could not delete token from CTS: " + e.getMessage());
    }
  }
  /** {@inheritDoc} */
  public void deleteAuthorizationCode(String authorizationCode) {
    if (logger.messageEnabled()) {
      logger.message(
          "DefaultOAuthTokenStoreImpl::Deleting Authorization code: " + authorizationCode);
    }
    JsonValue oAuthToken;

    // Read from CTS
    try {
      oAuthToken = tokenStore.read(authorizationCode);
    } catch (CoreTokenException e) {
      logger.error(
          "DefaultOAuthTokenStoreImpl::Unable to read authorization code corresponding to id: "
              + authorizationCode,
          e);
      throw new OAuthProblemException(
          Status.SERVER_ERROR_INTERNAL.getCode(),
          "Internal error",
          "Could not read token from CTS: " + e.getMessage(),
          null);
    }

    if (oAuthToken == null) {
      logger.error(
          "DefaultOAuthTokenStoreImpl::Unable to read authorization code corresponding to id: "
              + authorizationCode);
      throw new OAuthProblemException(
          Status.CLIENT_ERROR_NOT_FOUND.getCode(),
          "Not found",
          "Could not find token using CTS",
          null);
    }

    // Delete the code
    try {
      tokenStore.delete(authorizationCode);
    } catch (CoreTokenException e) {
      logger.error(
          "DefaultOAuthTokenStoreImpl::Unable to delete authorization code corresponding to id: "
              + authorizationCode,
          e);
      throw new OAuthProblemException(
          Status.SERVER_ERROR_INTERNAL.getCode(),
          "Internal error",
          "Could not delete token from CTS: " + e.getMessage(),
          null);
    }
  }
  @Override
  public DeviceCode readDeviceCode(String userCode, OAuth2Request request)
      throws ServerException, NotFoundException, InvalidGrantException {
    try {
      JsonValue token = tokenStore.query(equalTo(CoreTokenField.STRING_FOURTEEN, userCode));

      if (token.size() != 1) {
        throw new InvalidGrantException();
      }

      DeviceCode deviceCode = new DeviceCode(json(token.asSet().iterator().next()));
      request.setToken(DeviceCode.class, deviceCode);
      return deviceCode;
    } catch (CoreTokenException e) {
      logger.error("Unable to read device code corresponding to id: " + userCode, e);
      throw new ServerException("Could not read token in CTS: " + e.getMessage());
    }
  }
  @Override
  public DeviceCode readDeviceCode(String clientId, String code, OAuth2Request request)
      throws ServerException, NotFoundException, InvalidGrantException {
    try {
      JsonValue token = tokenStore.read(code);

      if (token == null) {
        return null;
      }

      DeviceCode deviceCode = new DeviceCode(token);
      if (!clientId.equals(deviceCode.getClientId())) {
        throw new InvalidGrantException();
      }
      validateTokenRealm(deviceCode.getRealm(), request);
      request.setToken(DeviceCode.class, deviceCode);
      return deviceCode;
    } catch (CoreTokenException e) {
      logger.error("Unable to read device code corresponding to id: " + code, e);
      throw new ServerException("Could not read token in CTS: " + e.getMessage());
    }
  }
  /** {@inheritDoc} */
  public RefreshToken readRefreshToken(OAuth2Request request, String tokenId)
      throws ServerException, InvalidGrantException, NotFoundException {

    logger.message("Read refresh token");
    JsonValue token;

    try {
      token = tokenStore.read(tokenId);
    } catch (CoreTokenException e) {
      logger.error("Unable to read refresh token corresponding to id: " + tokenId, e);
      throw new ServerException("Could not read token in CTS: " + e.getMessage());
    }

    if (token == null) {
      logger.error("Unable to read refresh token corresponding to id: " + tokenId);
      throw new InvalidGrantException("grant is invalid");
    }

    OpenAMRefreshToken refreshToken = new OpenAMRefreshToken(token);
    validateTokenRealm(refreshToken.getRealm(), request);

    request.setToken(RefreshToken.class, refreshToken);
    return refreshToken;
  }
  /** {@inheritDoc} */
  public RefreshToken createRefreshToken(
      String grantType,
      String clientId,
      String resourceOwnerId,
      String redirectUri,
      Set<String> scope,
      OAuth2Request request)
      throws ServerException, NotFoundException {

    final String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));

    logger.message("Create refresh token");

    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);

    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);

    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();

    final long lifeTime;
    if (clientRegistration == null) {
      lifeTime = providerSettings.getRefreshTokenLifetime();
    } else {
      lifeTime = clientRegistration.getRefreshTokenLifeTime(providerSettings);
    }

    long expiryTime = lifeTime < 0 ? -1 : lifeTime + System.currentTimeMillis();

    AuthorizationCode token = request.getToken(AuthorizationCode.class);
    String authModules = null;
    String acr = null;
    if (token != null) {
      authModules = token.getAuthModules();
      acr = token.getAuthenticationContextClassReference();
    }

    RefreshToken currentRefreshToken = request.getToken(RefreshToken.class);
    if (currentRefreshToken != null) {
      authModules = currentRefreshToken.getAuthModules();
      acr = currentRefreshToken.getAuthenticationContextClassReference();
    }

    RefreshToken refreshToken =
        new OpenAMRefreshToken(
            id,
            resourceOwnerId,
            clientId,
            redirectUri,
            scope,
            expiryTime,
            OAuth2Constants.Bearer.BEARER,
            OAuth2Constants.Token.OAUTH_REFRESH_TOKEN,
            grantType,
            realm,
            authModules,
            acr,
            auditId);

    try {
      tokenStore.create(refreshToken);
      if (auditLogger.isAuditLogEnabled()) {
        String[] obs = {"CREATED_REFRESH_TOKEN", refreshToken.toString()};
        auditLogger.logAccessMessage("CREATED_REFRESH_TOKEN", obs, null);
      }
    } catch (CoreTokenException e) {
      if (auditLogger.isAuditLogEnabled()) {
        String[] obs = {"FAILED_CREATE_REFRESH_TOKEN", refreshToken.toString()};
        auditLogger.logErrorMessage("FAILED_CREATE_REFRESH_TOKEN", obs, null);
      }
      logger.error("Unable to create refresh token: " + refreshToken.getTokenInfo(), e);
      throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }

    request.setToken(RefreshToken.class, refreshToken);

    return refreshToken;
  }
  /** {@inheritDoc} */
  public AccessToken createAccessToken(
      String grantType,
      String accessTokenType,
      String authorizationCode,
      String resourceOwnerId,
      String clientId,
      String redirectUri,
      Set<String> scope,
      RefreshToken refreshToken,
      String nonce,
      String claims,
      OAuth2Request request)
      throws ServerException, NotFoundException {

    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);

    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();

    String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));

    long expiryTime = 0;
    if (clientRegistration == null) {
      expiryTime = providerSettings.getAccessTokenLifetime() + System.currentTimeMillis();
    } else {
      expiryTime =
          clientRegistration.getAccessTokenLifeTime(providerSettings) + System.currentTimeMillis();
    }

    final AccessToken accessToken;
    if (refreshToken == null) {
      accessToken =
          new OpenAMAccessToken(
              id,
              authorizationCode,
              resourceOwnerId,
              clientId,
              redirectUri,
              scope,
              expiryTime,
              null,
              OAuth2Constants.Token.OAUTH_ACCESS_TOKEN,
              grantType,
              nonce,
              realm,
              claims,
              auditId);
    } else {
      accessToken =
          new OpenAMAccessToken(
              id,
              authorizationCode,
              resourceOwnerId,
              clientId,
              redirectUri,
              scope,
              expiryTime,
              refreshToken.getTokenId(),
              OAuth2Constants.Token.OAUTH_ACCESS_TOKEN,
              grantType,
              nonce,
              realm,
              claims,
              auditId);
    }
    try {
      tokenStore.create(accessToken);
      if (auditLogger.isAuditLogEnabled()) {
        String[] obs = {"CREATED_TOKEN", accessToken.toString()};
        auditLogger.logAccessMessage("CREATED_TOKEN", obs, null);
      }
    } catch (CoreTokenException e) {
      logger.error("Could not create token in CTS: " + e.getMessage());
      if (auditLogger.isAuditLogEnabled()) {
        String[] obs = {"FAILED_CREATE_TOKEN", accessToken.toString()};
        auditLogger.logErrorMessage("FAILED_CREATE_TOKEN", obs, null);
      }
      throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }
    request.setToken(AccessToken.class, accessToken);
    return accessToken;
  }