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 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);
    }
  }
 @Override
 public void addSessionParticipant(SessionParticipant... participant) {
   InvocationContext invocationContext = InvocationContext.getCurrent();
   LoginSession ls = invocationContext.getLoginSession();
   try {
     SessionParticipants.AddParticipantToSessionTask addTask =
         new SessionParticipants.AddParticipantToSessionTask(
             participantTypesRegistry, participant);
     updateSessionAttributes(ls.getId(), addTask);
   } catch (WrongArgumentException e) {
     throw new InternalException("Can not add session participant to the existing session?", e);
   }
 }
  @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);
    }
  }
 @Override
 public void run() {
   List<Token> tokens = tokensManagement.getAllTokens(SESSION_TOKEN_TYPE);
   long now = System.currentTimeMillis();
   for (Token t : tokens) {
     if (t.getExpires() != null) continue;
     LoginSession session = token2session(t);
     long inactiveFor = now - session.getLastUsed().getTime();
     if (inactiveFor > session.getMaxInactivity()) {
       log.debug("Expiring login session " + session + " inactive for: " + inactiveFor);
       try {
         removeSession(session.getId(), false);
       } catch (Exception e) {
         log.error("Can't expire the session " + session, e);
       }
     }
   }
 }
  @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);
    }
  }
 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;
 }
 private LoginSession token2session(Token token) {
   LoginSession session = new LoginSession();
   session.deserialize(token);
   return session;
 }