package org.eclipse.jetty.server.session;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import jakarta.servlet.http.HttpServletRequest;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.statistic.CounterStatistic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ManagedObject
public class DefaultSessionCache extends AbstractSessionCache
{
private static final Logger LOG = LoggerFactory.getLogger(DefaultSessionCache.class);
protected ConcurrentHashMap<String, Session> _sessions = new ConcurrentHashMap<>();
private final CounterStatistic _stats = new CounterStatistic();
public DefaultSessionCache(SessionHandler manager)
{
super(manager);
}
@ManagedAttribute(value = "current sessions in cache", readonly = true)
public long getSessionsCurrent()
{
return _stats.getCurrent();
}
@ManagedAttribute(value = "max sessions in cache", readonly = true)
public long getSessionsMax()
{
return _stats.getMax();
}
@ManagedAttribute(value = "total sessions in cache", readonly = true)
public long getSessionsTotal()
{
return _stats.getTotal();
}
@ManagedOperation(value = "reset statistics", impact = "ACTION")
public void resetStats()
{
_stats.reset();
}
@Override
public Session doGet(String id)
{
if (id == null)
return null;
return _sessions.get(id);
}
@Override
public Session doPutIfAbsent(String id, Session session)
{
Session s = _sessions.putIfAbsent(id, session);
if (s == null)
_stats.increment();
return s;
}
@Override
protected Session doComputeIfAbsent(String id, Function<String, Session> mappingFunction)
{
return _sessions.computeIfAbsent(id, k ->
{
Session s = mappingFunction.apply(k);
if (s != null)
_stats.increment();
return s;
});
}
@Override
public Session doDelete(String id)
{
Session s = _sessions.remove(id);
if (s != null)
_stats.decrement();
return s;
}
@Override
public void shutdown()
{
if (LOG.isDebugEnabled())
LOG.debug("Shutdown sessions, invalidating = {}", isInvalidateOnShutdown());
int loop = 100;
while (!_sessions.isEmpty() && loop-- > 0)
{
for (Session session : _sessions.values())
{
if (isInvalidateOnShutdown())
{
try
{
session.invalidate();
}
catch (Exception e)
{
LOG.trace("IGNORED", e);
}
}
else
{
if (_sessionDataStore.isPassivating())
session.willPassivate();
try
{
_sessionDataStore.store(session.getId(), session.getSessionData());
}
catch (Exception e)
{
LOG.warn("Unable to store {}", session, e);
}
doDelete(session.getId());
session.setResident(false);
}
}
}
}
@Override
public Session newSession(HttpServletRequest request, SessionData data)
{
return new Session(getSessionHandler(), request, data);
}
@Override
public Session newSession(SessionData data)
{
return new Session(getSessionHandler(), data);
}
@Override
public boolean doReplace(String id, Session oldValue, Session newValue)
{
return _sessions.replace(id, oldValue, newValue);
}
}