org.apache.catalina.Session Java Examples

The following examples show how to use org.apache.catalina.Session. 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: JvmRouteBinderValve.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * change session id and send to all cluster nodes
 * 
 * @param request current request
 * @param sessionId
 *            original session id
 * @param newSessionID
 *            new session id for node migration
 * @param catalinaSession
 *            current session with original session id
 */
protected void changeSessionID(Request request, String sessionId,
        String newSessionID, Session catalinaSession) {
    fireLifecycleEvent("Before session migration", catalinaSession);
    catalinaSession.setId(newSessionID, false);
    // FIXME: Why we remove change data from other running request?
    // setId also trigger resetDeltaRequest!!
    if (catalinaSession instanceof DeltaSession)
        ((DeltaSession) catalinaSession).resetDeltaRequest();
    changeRequestSessionID(request, sessionId, newSessionID);

    // now sending the change to all other clusternodes!
    sendSessionIDClusterBackup(request,sessionId, newSessionID);

    fireLifecycleEvent("After session migration", catalinaSession);
    if (log.isDebugEnabled()) {
        log.debug(sm.getString("jvmRoute.changeSession", sessionId,
                newSessionID));
    }   
}
 
Example #2
Source File: PersistentValve.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Indicate whether the session has been idle for longer
 * than its expiration date as of the supplied time.
 *
 * FIXME: Probably belongs in the Session class.
 * @param session The session to check
 * @param timeNow The current time to check for
 * @return <code>true</code> if the session is past its expiration
 */
protected boolean isSessionStale(Session session, long timeNow) {

    if (session != null) {
        int maxInactiveInterval = session.getMaxInactiveInterval();
        if (maxInactiveInterval >= 0) {
            int timeIdle = // Truncate, do not round up
                (int) ((timeNow - session.getThisAccessedTime()) / 1000L);
            if (timeIdle >= maxInactiveInterval) {
                return true;
            }
        }
    }

    return false;
}
 
Example #3
Source File: CatalinaSessionTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void saveAccountInfo(OidcKeycloakAccount account) {
    RefreshableKeycloakSecurityContext securityContext = (RefreshableKeycloakSecurityContext) account.getKeycloakSecurityContext();
    Set<String> roles = account.getRoles();
    GenericPrincipal principal = principalFactory.createPrincipal(request.getContext().getRealm(), account.getPrincipal(), roles);

    SerializableKeycloakAccount sAccount = new SerializableKeycloakAccount(roles, account.getPrincipal(), securityContext);
    Session session = request.getSessionInternal(true);
    session.setPrincipal(principal);
    session.setAuthType("KEYCLOAK");
    session.getSession().setAttribute(SerializableKeycloakAccount.class.getName(), sAccount);
    session.getSession().setAttribute(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
    String username = securityContext.getToken().getSubject();
    log.fine("userSessionManagement.login: " + username);
    this.sessionManagement.login(session);
}
 
Example #4
Source File: ReplicationValve.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Send all changed cross context sessions to backups
 * @param containerCluster
 */
protected void sendCrossContextSession(CatalinaCluster containerCluster) {
    List<DeltaSession> sessions = crossContextSessions.get();
    if(sessions != null && sessions.size() >0) {
        for(Iterator<DeltaSession> iter = sessions.iterator(); iter.hasNext() ;) {          
            Session session = iter.next();
            if(log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.crossContext.sendDelta",  
                        session.getManager().getContainer().getName() ));
            sendMessage(session,(ClusterManager)session.getManager(),containerCluster);
            if(doStatistics()) {
                nrOfCrossContextSendRequests++;
            }
        }
    }
}
 
Example #5
Source File: BackupManager.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Stop this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * This will disconnect the cluster communication channel and stop the
 * listener thread.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void stopInternal() throws LifecycleException {

    if (log.isDebugEnabled())
        log.debug(sm.getString("backupManager.stopped", getName()));

    setState(LifecycleState.STOPPING);

    if (sessions instanceof LazyReplicatedMap) {
        LazyReplicatedMap<String,Session> map =
                (LazyReplicatedMap<String,Session>)sessions;
        map.breakdown();
    }

    super.stopInternal();
}
 
Example #6
Source File: BackupManager.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Start this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * Starts the cluster communication channel, this will connect with the
 * other nodes in the cluster, and request the current session state to be
 * transferred to this node.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {

    super.startInternal();

    try {
        if (cluster == null) throw new LifecycleException(sm.getString("backupManager.noCluster", getName()));
        LazyReplicatedMap<String,Session> map = new LazyReplicatedMap<>(
                this, cluster.getChannel(), rpcTimeout, getMapName(),
                getClassLoaders(), terminateOnStartFailure);
        map.setChannelSendOptions(mapSendOptions);
        map.setAccessTimeout(accessTimeout);
        this.sessions = map;
    }  catch ( Exception x ) {
        log.error(sm.getString("backupManager.startUnable", getName()),x);
        throw new LifecycleException(sm.getString("backupManager.startFailed", getName()),x);
    }
    setState(LifecycleState.STARTING);
}
 
Example #7
Source File: ManagerBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Invalidate all sessions that have expired.
 */
public void processExpires() {

    long timeNow = System.currentTimeMillis();
    Session sessions[] = findSessions();
    int expireHere = 0 ;

    if(log.isDebugEnabled())
        log.debug("Start expire sessions " + getName() + " at " + timeNow + " sessioncount " + sessions.length);
    for (int i = 0; i < sessions.length; i++) {
        if (sessions[i]!=null && !sessions[i].isValid()) {
            expireHere++;
        }
    }
    long timeEnd = System.currentTimeMillis();
    if(log.isDebugEnabled())
         log.debug("End expire sessions " + getName() + " processingTime " + (timeEnd - timeNow) + " expired sessions: " + expireHere);
    processingTime += ( timeEnd - timeNow );

}
 
Example #8
Source File: DeltaManager.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Stop this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void stopInternal() throws LifecycleException {

    if (log.isDebugEnabled())
        log.debug(sm.getString("deltaManager.stopped", getName()));

    setState(LifecycleState.STOPPING);
    
    // Expire all active sessions
    if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.expireSessions", getName()));
    Session sessions[] = findSessions();
    for (int i = 0; i < sessions.length; i++) {
        DeltaSession session = (DeltaSession) sessions[i];
        if (!session.isValid())
            continue;
        try {
            session.expire(true, isExpireSessionsOnShutdown());
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        } 
    }

    // Require a new random number generator if we are restarted
    super.stopInternal();
}
 
Example #9
Source File: DeltaManager.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Stop this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void stopInternal() throws LifecycleException {

    if (log.isDebugEnabled())
        log.debug(sm.getString("deltaManager.stopped", getName()));

    setState(LifecycleState.STOPPING);

    // Expire all active sessions
    if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.expireSessions", getName()));
    Session sessions[] = findSessions();
    for (int i = 0; i < sessions.length; i++) {
        DeltaSession session = (DeltaSession) sessions[i];
        if (!session.isValid())
            continue;
        try {
            session.expire(true, isExpireSessionsOnShutdown());
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        }
    }

    // Require a new random number generator if we are restarted
    super.stopInternal();
}
 
Example #10
Source File: PersistentManagerBase.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Save all currently active sessions in the appropriate persistence
 * mechanism, if any.  If persistence is not supported, this method
 * returns without doing anything.
 * <p>
 * Note that by default, this method is not called by the MiddleManager
 * class. In order to use it, a subclass must specifically call it,
 * for example in the stop() and/or processPersistenceChecks() methods.
 */
@Override
public void unload() {

    if (store == null)
        return;

    Session sessions[] = findSessions();
    int n = sessions.length;
    if (n == 0)
        return;

    if (log.isDebugEnabled())
        log.debug(sm.getString("persistentManager.unloading",
                         String.valueOf(n)));

    for (int i = 0; i < n; i++)
        try {
            swapOut(sessions[i]);
        } catch (IOException e) {
            // This is logged in writeSession()
        }

}
 
Example #11
Source File: TomcatValve.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
public boolean logout(HttpServletRequest servletRequest)
{
    if (servletRequestMatches(servletRequest))
    {
        Session session = getSession(request, false);
        if (session != null)
        {
            session.setPrincipal(null);
            session.setAuthType(null);
            session.removeNote(Constants.SESS_USERNAME_NOTE);
            session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
        return true;
    }
    return false;
}
 
Example #12
Source File: SingleSignOn.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a single Session from a SingleSignOn.  Called when
 * a session is timed out and no longer active.
 *
 * @param ssoId Single sign on identifier from which to remove the session.
 * @param session the session to be removed.
 */
protected void removeSession(String ssoId, Session session) {

    if (containerLog.isDebugEnabled()) {
        containerLog.debug(sm.getString("singleSignOn.debug.removeSession", session, ssoId));
    }

    // Get a reference to the SingleSignOn
    SingleSignOnEntry entry = cache.get(ssoId);
    if (entry == null) {
        return;
    }

    // Remove the inactive session from SingleSignOnEntry
    entry.removeSession(session);

    // If there are not sessions left in the SingleSignOnEntry,
    // deregister the entry.
    if (entry.findSessions().size() == 0) {
        deregister(ssoId);
    }
}
 
Example #13
Source File: DeltaManager.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
public void changeSessionId(Session session, boolean notify) {
    // original sessionID
    String orgSessionID = session.getId();
    super.changeSessionId(session);
    if (notify && cluster.getMembers().length > 0) {
        // changed sessionID
        String newSessionID = session.getId();
        try {
            // serialize sessionID
            byte[] data = serializeSessionId(newSessionID);
            // notify change sessionID
            SessionMessage msg = new SessionMessageImpl(getName(),
                    SessionMessage.EVT_CHANGE_SESSION_ID, data,
                    orgSessionID, orgSessionID + "-"
                            + System.currentTimeMillis());
            msg.setTimestamp(System.currentTimeMillis());
            counterSend_EVT_CHANGE_SESSION_ID++;
            send(msg);
        } catch (IOException e) {
            log.error(sm.getString("deltaManager.unableSerializeSessionID",
                    newSessionID), e);
        }
    }
}
 
Example #14
Source File: PersistentValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Indicate whether the session has been idle for longer
 * than its expiration date as of the supplied time.
 *
 * FIXME: Probably belongs in the Session class.
 */
protected boolean isSessionStale(Session session, long timeNow) {

    if (session != null) {
        int maxInactiveInterval = session.getMaxInactiveInterval();
        if (maxInactiveInterval >= 0) {
            int timeIdle = // Truncate, do not round up
                (int) ((timeNow - session.getThisAccessedTime()) / 1000L);
            if (timeIdle >= maxInactiveInterval) {
                return true;
            }
        }
    }

    return false;
}
 
Example #15
Source File: ManagerBase.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Invalidate all sessions that have expired.
 */
public void processExpires() {

    long timeNow = System.currentTimeMillis();
    Session sessions[] = findSessions();
    int expireHere = 0 ;
    
    if(log.isDebugEnabled())
        log.debug("Start expire sessions " + getName() + " at " + timeNow + " sessioncount " + sessions.length);
    for (int i = 0; i < sessions.length; i++) {
        if (sessions[i]!=null && !sessions[i].isValid()) {
            expireHere++;
        }
    }
    long timeEnd = System.currentTimeMillis();
    if(log.isDebugEnabled())
         log.debug("End expire sessions " + getName() + " processingTime " + (timeEnd - timeNow) + " expired sessions: " + expireHere);
    processingTime += ( timeEnd - timeNow );

}
 
Example #16
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected boolean validateToken(Request request, HttpServletResponse response, FedizContext fedConfig) {
    Session session = request.getSessionInternal();
    if (session != null) {

        FedizResponse wfRes = (FedizResponse)session.getNote(FEDERATION_NOTE);
        Instant tokenExpires = wfRes.getTokenExpires();
        if (tokenExpires == null) {
            LOG.debug("Token doesn't expire");
            return true;
        }

        Instant currentTime = Instant.now();
        if (!currentTime.isAfter(tokenExpires)) {
            return true;
        } else {
            LOG.warn("Token already expired. Clean up and redirect");

            session.removeNote(FEDERATION_NOTE);
            session.setPrincipal(null);
            request.getSession().removeAttribute(SECURITY_TOKEN);
        }
    } else {
        LOG.debug("Session should not be null after authentication");
    }
    return false;
}
 
Example #17
Source File: ReplicationValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Send all changed cross context sessions to backups
 * @param containerCluster
 */
protected void sendCrossContextSession(CatalinaCluster containerCluster) {
    List<DeltaSession> sessions = crossContextSessions.get();
    if(sessions != null && sessions.size() >0) {
        for(Iterator<DeltaSession> iter = sessions.iterator(); iter.hasNext() ;) {          
            Session session = iter.next();
            if(log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.crossContext.sendDelta",  
                        session.getManager().getContainer().getName() ));
            sendMessage(session,(ClusterManager)session.getManager(),containerCluster);
            if(doStatistics()) {
                nrOfCrossContextSendRequests++;
            }
        }
    }
}
 
Example #18
Source File: ManagerBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void remove(Session session, boolean update) {
    // If the session has expired - as opposed to just being removed from
    // the manager because it is being persisted - update the expired stats
    if (update) {
        long timeNow = System.currentTimeMillis();
        int timeAlive =
            (int) (timeNow - session.getCreationTimeInternal())/1000;
        updateSessionMaxAliveTime(timeAlive);
        expiredSessions.incrementAndGet();
        SessionTiming timing = new SessionTiming(timeNow, timeAlive);
        synchronized (sessionExpirationTiming) {
            sessionExpirationTiming.add(timing);
            sessionExpirationTiming.poll();
        }
    }

    if (session.getIdInternal() != null) {
        sessions.remove(session.getIdInternal());
    }
}
 
Example #19
Source File: ManagerBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Returns information about the session with the given session id.
 *
 * <p>The session information is organized as a HashMap, mapping
 * session attribute names to the String representation of their values.
 *
 * @param sessionId Session id
 *
 * @return HashMap mapping session attribute names to the String
 * representation of their values, or null if no session with the
 * specified id exists, or if the session does not have any attributes
 */
public HashMap<String, String> getSession(String sessionId) {
    Session s = sessions.get(sessionId);
    if (s == null) {
        if (log.isInfoEnabled()) {
            log.info("Session not found " + sessionId);
        }
        return null;
    }

    Enumeration<String> ee = s.getSession().getAttributeNames();
    if (ee == null || !ee.hasMoreElements()) {
        return null;
    }

    HashMap<String, String> map = new HashMap<>();
    while (ee.hasMoreElements()) {
        String attrName = ee.nextElement();
        map.put(attrName, getSessionAttribute(sessionId, attrName));
    }

    return map;
}
 
Example #20
Source File: FormAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Return the request URI (with the corresponding query string, if any)
 * from the saved request so that we can redirect to it.
 *
 * @param session Our current session
 */
protected String savedRequestURL(Session session) {

    SavedRequest saved =
        (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
    if (saved == null) {
        return (null);
    }
    StringBuilder sb = new StringBuilder(saved.getRequestURI());
    if (saved.getQueryString() != null) {
        sb.append('?');
        sb.append(saved.getQueryString());
    }
    return (sb.toString());

}
 
Example #21
Source File: Tomcat7Valve.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
static Session getSession(Request request, boolean create) 
{

    HttpServletRequest hreq = (HttpServletRequest)request.getRequest();
    HttpSession hses = hreq.getSession(create);

    if (hses == null)
        return null;

    Manager manager = request.getContext().getManager();
    if (manager == null)
        return null;

    try 
    {
        return manager.findSession(hses.getId());
    }
    catch (IOException e) 
    {
        Log.getLogger(LogCategories.SECURITY).error("Error in TomcatValve getting session id " + hses.getId() + " : " + ExceptionUtil.toString(e));
        return null;
    }
}
 
Example #22
Source File: DeltaManager.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * send a block of session to sender
 * @param sender
 * @param currentSessions
 * @param sendTimestamp
 * @throws IOException
 */
protected void sendSessions(Member sender, Session[] currentSessions,long sendTimestamp) throws IOException {
    byte[] data = serializeSessions(currentSessions);
    if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingAfter",getName()));
    SessionMessage newmsg = new SessionMessageImpl(name,SessionMessage.EVT_ALL_SESSION_DATA, data,"SESSION-STATE", "SESSION-STATE-" + getName());
    newmsg.setTimestamp(sendTimestamp);
    if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionData",getName()));
    counterSend_EVT_ALL_SESSION_DATA++;
    cluster.send(newmsg, sender);
}
 
Example #23
Source File: PersistentManagerBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Remove this Session from the Store.
 */
@Override
public void remove(Session session, boolean update) {

    super.remove (session, update);

    if (store != null){
        removeSession(session.getIdInternal());
    }
}
 
Example #24
Source File: JspHelper.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public static String getDisplayCreationTimeForSession(Session in_session) {
    try {
        if (in_session.getCreationTime() == 0) {
            return "";
        }
        DateFormat formatter = new SimpleDateFormat(DATE_TIME_FORMAT);
        return formatter.format(new Date(in_session.getCreationTime()));
    } catch (IllegalStateException ise) {
        //ignore: invalidated session
        return "";
    }
}
 
Example #25
Source File: TomcatLogoutHandler.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean signout(HttpServletRequest req, HttpServletResponse resp) {
    // Direct Logout
    Session session = request.getSessionInternal();
    session.removeNote(FederationAuthenticator.FEDERATION_NOTE);
    session.setPrincipal(null);
    return super.signout(req, resp);
}
 
Example #26
Source File: SessionUtils.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
public static long getUsedTimeForSession(Session in_session) {
    try {
        long diffMilliSeconds = in_session.getThisAccessedTime() - in_session.getCreationTime();
        return diffMilliSeconds;
    } catch (IllegalStateException ise) {
        //ignore: invalidated session
        return -1;
    }
}
 
Example #27
Source File: TomcatValve4150.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
public Principal login(String username, String password, HttpServletRequest servletRequest)
{
    Realm realm = container.getRealm();
    if (realm == null)
        return null;
    Principal principal = realm.authenticate(username, password);

    if (principal != null) 
    {
        if (this.request != null && this.request.getRequest() == servletRequest)
        {
            request.setAuthType("flexmessaging"); //was "flashgateway"
            request.setUserPrincipal(principal);

            Session session = getSession(request, true);

            // Cache the authentication information in our session, if any
            if (session != null) 
            {
                session.setAuthType("flexmessaging"); //was "flashgateway"
                session.setPrincipal(principal);
                if (username != null)
                    session.setNote(Constants.SESS_USERNAME_NOTE, username);
                else
                    session.removeNote(Constants.SESS_USERNAME_NOTE);
                if (password != null)
                    session.setNote(Constants.SESS_PASSWORD_NOTE, password);
                else
                    session.removeNote(Constants.SESS_PASSWORD_NOTE);
            }
        }
    }

    return principal;
}
 
Example #28
Source File: SessionUtils.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public static long getInactiveTimeForSession(Session in_session) {
    try {
        long diffMilliSeconds =  System.currentTimeMillis() - in_session.getThisAccessedTime();
        return diffMilliSeconds;
    } catch (IllegalStateException ise) {
        //ignore: invalidated session
        return -1;
    }
}
 
Example #29
Source File: PersistentManagerBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * This method checks the persistence store if persistence is enabled,
 * otherwise just uses the functionality from ManagerBase.
 */
@Override
public Session findSession(String id) throws IOException {

    Session session = super.findSession(id);
    // OK, at this point, we're not sure if another thread is trying to
    // remove the session or not so the only way around this is to lock it
    // (or attempt to) and then try to get it by this session id again. If
    // the other code ran swapOut, then we should get a null back during
    // this run, and if not, we lock it out so we can access the session
    // safely.
    if(session != null) {
        synchronized(session){
            session = super.findSession(session.getIdInternal());
            if(session != null){
               // To keep any external calling code from messing up the
               // concurrency.
               session.access();
               session.endAccess();
            }
        }
    }
    if (session != null)
        return session;

    // See if the Session is in the Store
    session = swapIn(id);
    return session;
}
 
Example #30
Source File: PersistentManagerBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void reactivateLoadedSession(String id, Session session) {
    if(log.isDebugEnabled())
        log.debug(sm.getString("persistentManager.swapIn", id));

    session.setManager(this);
    // make sure the listeners know about it.
    ((StandardSession)session).tellNew();
    add(session);
    ((StandardSession)session).activate();
    // endAccess() to ensure timeouts happen correctly.
    // access() to keep access count correct or it will end up
    // negative
    session.access();
    session.endAccess();
}