@Override
  public LoginSession getCreateSession(
      long loggedEntity,
      AuthenticationRealm realm,
      String entityLabel,
      boolean outdatedCredential,
      Date absoluteExpiration) {
    Object transaction = tokensManagement.startTokenTransaction();
    try {
      try {
        LoginSession ret =
            getOwnedSession(new EntityParam(loggedEntity), realm.getName(), transaction);
        if (ret != null) {
          ret.setLastUsed(new Date());
          byte[] contents = ret.getTokenContents();
          tokensManagement.updateToken(
              SESSION_TOKEN_TYPE, ret.getId(), null, contents, transaction);

          if (log.isDebugEnabled())
            log.debug(
                "Using existing session "
                    + ret.getId()
                    + " for logged entity "
                    + ret.getEntityId()
                    + " in realm "
                    + realm.getName());
          tokensManagement.commitTokenTransaction(transaction);
          return ret;
        }
      } catch (EngineException e) {
        throw new InternalException(
            "Can't retrieve current sessions of the " + "authenticated user", e);
      }

      LoginSession ret =
          createSession(
              loggedEntity,
              realm,
              entityLabel,
              outdatedCredential,
              absoluteExpiration,
              transaction);
      tokensManagement.commitTokenTransaction(transaction);
      if (log.isDebugEnabled())
        log.debug(
            "Created a new session "
                + ret.getId()
                + " for logged entity "
                + ret.getEntityId()
                + " in realm "
                + realm.getName());
      return ret;
    } finally {
      tokensManagement.closeTokenTransaction(transaction);
      cleanScheduledRemoval(loggedEntity);
    }
  }
 private LoginSession createSession(
     long loggedEntity,
     AuthenticationRealm realm,
     String entityLabel,
     boolean outdatedCredential,
     Date absoluteExpiration,
     Object transaction) {
   UUID randomid = UUID.randomUUID();
   String id = randomid.toString();
   LoginSession ls =
       new LoginSession(
           id,
           new Date(),
           absoluteExpiration,
           realm.getMaxInactivity() * 1000,
           loggedEntity,
           realm.getName());
   ls.setUsedOutdatedCredential(outdatedCredential);
   ls.setEntityLabel(entityLabel);
   try {
     tokensManagement.addToken(
         SESSION_TOKEN_TYPE,
         id,
         new EntityParam(loggedEntity),
         ls.getTokenContents(),
         ls.getStarted(),
         ls.getExpires(),
         transaction);
   } catch (Exception e) {
     throw new InternalException("Can't create a new session", e);
   }
   return ls;
 }
  @Override
  public void updateSessionAttributes(String id, AttributeUpdater updater)
      throws WrongArgumentException {
    Object transaction = tokensManagement.startTokenTransaction();
    try {
      Token token = tokensManagement.getTokenById(SESSION_TOKEN_TYPE, id, transaction);
      LoginSession session = token2session(token);

      updater.updateAttributes(session.getSessionData());

      byte[] contents = session.getTokenContents();
      tokensManagement.updateToken(SESSION_TOKEN_TYPE, id, null, contents, transaction);
      tokensManagement.commitTokenTransaction(transaction);
    } finally {
      tokensManagement.closeTokenTransaction(transaction);
    }
  }
 private LoginSession getOwnedSession(EntityParam owner, String realm, Object transaction)
     throws EngineException {
   List<Token> tokens = tokensManagement.getOwnedTokens(SESSION_TOKEN_TYPE, owner, transaction);
   for (Token token : tokens) {
     LoginSession ls = token2session(token);
     if (realm.equals(ls.getRealm())) return ls;
   }
   return null;
 }
 @Override
 public void removeSession(String id, boolean soft) {
   sessionBinder.removeLoginSession(id, soft);
   try {
     tokensManagement.removeToken(SESSION_TOKEN_TYPE, id, null);
     if (log.isDebugEnabled()) log.debug("Removed session with id " + id);
   } catch (WrongArgumentException e) {
     // not found - ok
   }
 }
  @Override
  public void updateSessionActivity(String id) throws WrongArgumentException {
    Long lastWrite = recentUsageUpdates.get(id);
    if (lastWrite != null) {
      if (System.currentTimeMillis() < lastWrite + DB_ACTIVITY_WRITE_DELAY) return;
    }

    Object transaction = tokensManagement.startTokenTransaction();
    try {
      Token token = tokensManagement.getTokenById(SESSION_TOKEN_TYPE, id, transaction);
      LoginSession session = token2session(token);
      session.setLastUsed(new Date());
      byte[] contents = session.getTokenContents();
      tokensManagement.updateToken(SESSION_TOKEN_TYPE, id, null, contents, transaction);
      tokensManagement.commitTokenTransaction(transaction);
      log.trace("Updated in db session activity timestamp for " + id);
      recentUsageUpdates.put(id, System.currentTimeMillis());
    } finally {
      tokensManagement.closeTokenTransaction(transaction);
    }
  }
 @Override
 public LoginSession getSession(String id) throws WrongArgumentException {
   Token token = tokensManagement.getTokenById(SESSION_TOKEN_TYPE, id, null);
   return token2session(token);
 }