Making session tests work; incorporating renewing session id keeping old object.

This commit is contained in:
Jan Bartel 2012-10-27 18:44:35 +11:00
parent 605b0360e1
commit b8d6b4da8b
49 changed files with 1150 additions and 612 deletions

View File

@ -179,5 +179,19 @@ public class NoSqlSession extends AbstractSession
{ {
return _version; return _version;
} }
@Override
public void setClusterId(String clusterId)
{
super.setClusterId(clusterId);
}
@Override
public void setNodeId(String nodeId)
{
super.setNodeId(nodeId);
}
} }

View File

@ -307,6 +307,34 @@ public abstract class NoSqlSessionManager extends AbstractSessionManager impleme
_saveAllAttributes = saveAllAttributes; _saveAllAttributes = saveAllAttributes;
} }
/* ------------------------------------------------------------ */
@Override
public void renewSessionId(String oldClusterId, String oldNodeId, String newClusterId, String newNodeId)
{
// Take the old session out of the list of sessions
// Change to the new id
// Put it back into the list of sessions
// Update permanent storage
synchronized (this)
{
try
{
NoSqlSession session = _sessions.remove(oldClusterId);
update (session, newClusterId, newNodeId);
session.setClusterId(newClusterId);
session.setNodeId(newNodeId);
_sessions.put(newClusterId, session);
}
catch (Exception e)
{
__log.warn(e);
}
}
}
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
abstract protected NoSqlSession loadSession(String clusterId); abstract protected NoSqlSession loadSession(String clusterId);
@ -318,5 +346,8 @@ public abstract class NoSqlSessionManager extends AbstractSessionManager impleme
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
abstract protected boolean remove(NoSqlSession session); abstract protected boolean remove(NoSqlSession session);
/* ------------------------------------------------------------ */
abstract protected void update(NoSqlSession session, String newClusterId, String newNodeId) throws Exception;
} }

View File

@ -25,6 +25,7 @@ import java.util.Random;
import java.util.Set; import java.util.Set;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
@ -69,6 +70,9 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
final static DBObject __valid_false = new BasicDBObject(MongoSessionManager.__VALID,false); final static DBObject __valid_false = new BasicDBObject(MongoSessionManager.__VALID,false);
final static DBObject __valid_true = new BasicDBObject(MongoSessionManager.__VALID,true); final static DBObject __valid_true = new BasicDBObject(MongoSessionManager.__VALID,true);
final static long __defaultScavengeDelay = 10 * 6 * 1000; // wait at least 10 minutes
final static long __defaultScavengePeriod = 30 * 60 * 1000; // every 30 minutes
final DBCollection _sessions; final DBCollection _sessions;
protected Server _server; protected Server _server;
@ -79,8 +83,8 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
private long _scavengeDelay = 30 * 60 * 1000; // every 30 minutes private long _scavengeDelay = __defaultScavengeDelay;
private long _scavengePeriod = 10 * 6 * 1000; // wait at least 10 minutes private long _scavengePeriod = __defaultScavengePeriod;
/** /**
@ -145,8 +149,8 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
*/ */
protected void scavenge() protected void scavenge()
{ {
__log.debug("SessionIdManager:scavenge:called with delay" + _scavengeDelay); long now = System.currentTimeMillis();
__log.debug("SessionIdManager:scavenge:at " + now);
synchronized (_sessionsIds) synchronized (_sessionsIds)
{ {
/* /*
@ -158,7 +162,8 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
*/ */
BasicDBObject query = new BasicDBObject(); BasicDBObject query = new BasicDBObject();
query.put(MongoSessionManager.__ID,new BasicDBObject("$in", _sessionsIds )); query.put(MongoSessionManager.__ID,new BasicDBObject("$in", _sessionsIds ));
query.put(MongoSessionManager.__ACCESSED, new BasicDBObject("$lt",System.currentTimeMillis() - _scavengeDelay));
query.put(MongoSessionManager.__ACCESSED, new BasicDBObject("$lt",now - _scavengePeriod));
DBCursor checkSessions = _sessions.find(query, new BasicDBObject(MongoSessionManager.__ID, 1)); DBCursor checkSessions = _sessions.find(query, new BasicDBObject(MongoSessionManager.__ID, 1));
@ -301,16 +306,22 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
*/ */
public void setScavengeDelay(long scavengeDelay) public void setScavengeDelay(long scavengeDelay)
{ {
this._scavengeDelay = scavengeDelay; if (scavengeDelay <= 0)
this._scavengeDelay = __defaultScavengeDelay;
else
this._scavengeDelay = TimeUnit.SECONDS.toMillis(scavengeDelay);
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public void setScavengePeriod(long scavengePeriod) public void setScavengePeriod(long scavengePeriod)
{ {
this._scavengePeriod = scavengePeriod; if (scavengePeriod <= 0)
_scavengePeriod = __defaultScavengePeriod;
else
_scavengePeriod = TimeUnit.SECONDS.toMillis(scavengePeriod);
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public void setPurgeDelay(long purgeDelay) public void setPurgeDelay(long purgeDelay)
{ {
@ -539,5 +550,36 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
return clusterId; return clusterId;
} }
/* ------------------------------------------------------------ */
@Override
public void renewSessionId(String oldClusterId, String oldNodeId, HttpServletRequest request)
{
//generate a new id
String newClusterId = newSessionId(request.hashCode());
synchronized (_sessionsIds)
{
_sessionsIds.remove(oldClusterId);//remove the old one from the list
_sessionsIds.add(newClusterId); //add in the new session id to the list
//tell all contexts to update the id
Handler[] contexts = _server.getChildHandlersByClass(ContextHandler.class);
for (int i=0; contexts!=null && i<contexts.length; i++)
{
SessionHandler sessionHandler = (SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class);
if (sessionHandler != null)
{
SessionManager manager = sessionHandler.getSessionManager();
if (manager != null && manager instanceof MongoSessionManager)
{
((MongoSessionManager)manager).renewSessionId(oldClusterId, oldNodeId, newClusterId, getNodeId(newClusterId, request));
}
}
}
}
}
} }

View File

@ -42,6 +42,7 @@ import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection; import com.mongodb.DBCollection;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.MongoException; import com.mongodb.MongoException;
import com.mongodb.WriteResult;
@ManagedObject("Mongo Session Manager") @ManagedObject("Mongo Session Manager")
@ -88,8 +89,9 @@ public class MongoSessionManager extends NoSqlSessionManager
{ {
super.doStart(); super.doStart();
String[] hosts = getContextHandler().getVirtualHosts(); String[] hosts = getContextHandler().getVirtualHosts();
if (hosts == null || hosts.length == 0) //TODO: can this be replaced?
hosts = getContextHandler().getConnectorNames(); /*if (hosts == null || hosts.length == 0)
hosts = getContextHandler().getConnectorNames();*/
if (hosts == null || hosts.length == 0) if (hosts == null || hosts.length == 0)
hosts = new String[] hosts = new String[]
{ "::" }; // IPv6 equiv of 0.0.0.0 { "::" }; // IPv6 equiv of 0.0.0.0
@ -415,6 +417,18 @@ public class MongoSessionManager extends NoSqlSessionManager
} }
} }
/*------------------------------------------------------------ */
@Override
protected void update(NoSqlSession session, String newClusterId, String newNodeId) throws Exception
{
// Form query for update - use object's existing session id
BasicDBObject key = new BasicDBObject(__ID, session.getClusterId());
BasicDBObject sets = new BasicDBObject();
BasicDBObject update = new BasicDBObject(__ID, newClusterId);
sets.put("$set", update);
_sessions.update(key, sets, false, false);
}
/*------------------------------------------------------------ */ /*------------------------------------------------------------ */
protected String encodeName(String name) protected String encodeName(String name)
{ {
@ -613,4 +627,5 @@ public class MongoSessionManager extends NoSqlSessionManager
} }
} }
} }

View File

@ -23,9 +23,9 @@ import java.security.Principal;
import java.util.Collection; import java.util.Collection;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -42,8 +42,7 @@ import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context; import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.server.handler.HandlerWrapper; import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.session.AbstractSessionManager; import org.eclipse.jetty.server.session.AbstractSession;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.Logger;
@ -329,7 +328,7 @@ public abstract class SecurityHandler extends HandlerWrapper implements Authenti
if (request.isSecure()) if (request.isSecure())
{ {
se.getSession().setAttribute(AbstractSessionManager.SESSION_KNOWN_ONLY_TO_AUTHENTICATED, Boolean.TRUE); se.getSession().setAttribute(AbstractSession.SESSION_KNOWN_ONLY_TO_AUTHENTICATED, Boolean.TRUE);
} }
} }
}); });

View File

@ -26,9 +26,10 @@ import javax.servlet.http.HttpSession;
import org.eclipse.jetty.security.Authenticator; import org.eclipse.jetty.security.Authenticator;
import org.eclipse.jetty.security.IdentityService; import org.eclipse.jetty.security.IdentityService;
import org.eclipse.jetty.security.LoginService; import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.server.Authentication; import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.UserIdentity; import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.session.AbstractSessionManager; import org.eclipse.jetty.server.session.AbstractSession;
import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.Logger;
@ -51,7 +52,7 @@ public abstract class LoginAuthenticator implements Authenticator
UserIdentity user = _loginService.login(username,password); UserIdentity user = _loginService.login(username,password);
if (user!=null) if (user!=null)
{ {
renewSession((HttpServletRequest)request, null); renewSession((HttpServletRequest)request, (request instanceof Request? ((Request)request).getResponse() : null));
return user; return user;
} }
return null; return null;
@ -95,11 +96,22 @@ public abstract class LoginAuthenticator implements Authenticator
{ {
//if we should renew sessions, and there is an existing session that may have been seen by non-authenticated users //if we should renew sessions, and there is an existing session that may have been seen by non-authenticated users
//(indicated by SESSION_SECURED not being set on the session) then we should change id //(indicated by SESSION_SECURED not being set on the session) then we should change id
if (httpSession.getAttribute(AbstractSessionManager.SESSION_KNOWN_ONLY_TO_AUTHENTICATED)!=Boolean.TRUE) if (httpSession.getAttribute(AbstractSession.SESSION_KNOWN_ONLY_TO_AUTHENTICATED)!=Boolean.TRUE)
{ {
HttpSession newSession = AbstractSessionManager.renewSession(request, httpSession,true); if (httpSession instanceof AbstractSession)
LOG.debug("renew {}->{}",httpSession.getId(),newSession.getId()); {
httpSession=newSession; AbstractSession abstractSession = (AbstractSession)httpSession;
String oldId = abstractSession.getId();
abstractSession.renewId(request);
abstractSession.setAttribute(AbstractSession.SESSION_KNOWN_ONLY_TO_AUTHENTICATED, Boolean.TRUE);
if (abstractSession.isIdChanged() && response != null && (response instanceof Response))
((Response)response).addCookie(abstractSession.getSessionManager().getSessionCookie(abstractSession, request.getContextPath(), request.isSecure()));
LOG.debug("renew {}->{}",oldId,abstractSession.getId());
}
else
LOG.warn("Unable to renew session "+httpSession);
return httpSession;
} }
} }
} }

View File

@ -33,6 +33,7 @@ import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.server.Authentication; import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.UserIdentity; import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.UserIdentity.Scope; import org.eclipse.jetty.server.UserIdentity.Scope;
import org.eclipse.jetty.server.session.AbstractSession;
import org.eclipse.jetty.server.session.AbstractSessionManager; import org.eclipse.jetty.server.session.AbstractSessionManager;
import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.Logger;
@ -107,7 +108,7 @@ public class SessionAuthentication implements Authentication.User, Serializable,
if (security!=null) if (security!=null)
security.logout(this); security.logout(this);
if (_session!=null) if (_session!=null)
_session.removeAttribute(AbstractSessionManager.SESSION_KNOWN_ONLY_TO_AUTHENTICATED); _session.removeAttribute(AbstractSession.SESSION_KNOWN_ONLY_TO_AUTHENTICATED);
} }
@Override @Override

View File

@ -68,6 +68,7 @@ import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context; import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.server.session.AbstractSession;
import org.eclipse.jetty.server.session.AbstractSessionManager; import org.eclipse.jetty.server.session.AbstractSessionManager;
import org.eclipse.jetty.util.Attributes; import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.AttributesMap; import org.eclipse.jetty.util.AttributesMap;
@ -1207,7 +1208,15 @@ public class Request implements HttpServletRequest
if (session == null) if (session == null)
throw new IllegalStateException("No session"); throw new IllegalStateException("No session");
AbstractSessionManager.renewSession(this, session, getRemoteUser()!=null); if (session instanceof AbstractSession)
{
AbstractSession abstractSession = ((AbstractSession)session);
abstractSession.renewId(this);
if (getRemoteUser() != null)
abstractSession.setAttribute(AbstractSession.SESSION_KNOWN_ONLY_TO_AUTHENTICATED, Boolean.TRUE);
if (abstractSession.isIdChanged())
_channel.getResponse().addCookie(_sessionManager.getSessionCookie(abstractSession, getContextPath(), isSecure()));
}
return session.getId(); return session.getId();
} }

View File

@ -59,6 +59,8 @@ public interface SessionIdManager extends LifeCycle
*/ */
public String newSessionId(HttpServletRequest request,long created); public String newSessionId(HttpServletRequest request,long created);
public String getWorkerName(); public String getWorkerName();
@ -78,4 +80,15 @@ public interface SessionIdManager extends LifeCycle
*/ */
public String getNodeId(String clusterId,HttpServletRequest request); public String getNodeId(String clusterId,HttpServletRequest request);
/* ------------------------------------------------------------ */
/** Change the existing session id.
*
* @param oldClusterId
* @param oldNodeId
* @param request
*/
public void renewSessionId(String oldClusterId, String oldNodeId, HttpServletRequest request);
} }

View File

@ -304,4 +304,14 @@ public interface SessionManager extends LifeCycle
* @param remote True if absolute URLs are check for remoteness before being session encoded. * @param remote True if absolute URLs are check for remoteness before being session encoded.
*/ */
public void setCheckingRemoteSessionIdEncoding(boolean remote); public void setCheckingRemoteSessionIdEncoding(boolean remote);
/* ------------------------------------------------------------ */
/** Change the existing session id.
*
* @param oldClusterId
* @param oldNodeId
* @param newClusterId
* @param newNodeId
*/
public void renewSessionId(String oldClusterId, String oldNodeId, String newClusterId, String newNodeId);
} }

View File

@ -36,6 +36,7 @@ import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionContext; import javax.servlet.http.HttpSessionContext;
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionEvent;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.Logger;
/** /**
@ -49,10 +50,10 @@ import org.eclipse.jetty.util.log.Logger;
public abstract class AbstractSession implements AbstractSessionManager.SessionIf public abstract class AbstractSession implements AbstractSessionManager.SessionIf
{ {
final static Logger LOG = SessionHandler.LOG; final static Logger LOG = SessionHandler.LOG;
public final static String SESSION_KNOWN_ONLY_TO_AUTHENTICATED="org.eclipse.jetty.security.sessionKnownOnlytoAuthenticated";
private String _clusterId; // ID unique within cluster
private String _nodeId; // ID unique within node
private final AbstractSessionManager _manager; private final AbstractSessionManager _manager;
private final String _clusterId; // ID unique within cluster
private final String _nodeId; // ID unique within node
private final Map<String,Object> _attributes=new HashMap<String, Object>(); private final Map<String,Object> _attributes=new HashMap<String, Object>();
private boolean _idChanged; private boolean _idChanged;
private final long _created; private final long _created;
@ -271,7 +272,34 @@ public abstract class AbstractSession implements AbstractSessionManager.SessionI
return (String[])_attributes.keySet().toArray(a); return (String[])_attributes.keySet().toArray(a);
} }
} }
/* ------------------------------------------------------------ */
public void renewId(HttpServletRequest request)
{
_manager._sessionIdManager.renewSessionId(getClusterId(), getNodeId(), request);
setIdChanged(true);
}
/* ------------------------------------------------------------- */
public SessionManager getSessionManager()
{
return _manager;
}
/* ------------------------------------------------------------ */
protected void setClusterId (String clusterId)
{
_clusterId = clusterId;
}
/* ------------------------------------------------------------ */
protected void setNodeId (String nodeId)
{
_nodeId = nodeId;
}
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
protected boolean access(long time) protected boolean access(long time)
{ {

View File

@ -117,32 +117,46 @@ public abstract class AbstractSessionIdManager extends AbstractLifeCycle impleme
} }
// pick a new unique ID! // pick a new unique ID!
String id=null; String id = newSessionId(request.hashCode());
while (id==null||id.length()==0||idInUse(id))
{
long r0=_weakRandom
?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^(((long)request.hashCode())<<32))
:_random.nextLong();
if (r0<0)
r0=-r0;
long r1=_weakRandom
?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^(((long)request.hashCode())<<32))
:_random.nextLong();
if (r1<0)
r1=-r1;
id=Long.toString(r0,36)+Long.toString(r1,36);
//add in the id of the node to ensure unique id across cluster
//NOTE this is different to the node suffix which denotes which node the request was received on
if (_workerName!=null)
id=_workerName + id;
}
request.setAttribute(__NEW_SESSION_ID,id); request.setAttribute(__NEW_SESSION_ID,id);
return id; return id;
} }
} }
/* ------------------------------------------------------------ */
public String newSessionId(long seedTerm)
{
// pick a new unique ID!
String id=null;
while (id==null||id.length()==0||idInUse(id))
{
long r0=_weakRandom
?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^((seedTerm)<<32))
:_random.nextLong();
if (r0<0)
r0=-r0;
long r1=_weakRandom
?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^((seedTerm)<<32))
:_random.nextLong();
if (r1<0)
r1=-r1;
id=Long.toString(r0,36)+Long.toString(r1,36);
//add in the id of the node to ensure unique id across cluster
//NOTE this is different to the node suffix which denotes which node the request was received on
if (_workerName!=null)
id=_workerName + id;
}
return id;
}
/* ------------------------------------------------------------ */
public abstract void renewSessionId(String oldClusterId, String oldNodeId, HttpServletRequest request);
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@Override @Override
protected void doStart() throws Exception protected void doStart() throws Exception

View File

@ -75,7 +75,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
new HashSet<SessionTrackingMode>( new HashSet<SessionTrackingMode>(
Arrays.asList(new SessionTrackingMode[]{SessionTrackingMode.COOKIE,SessionTrackingMode.URL}))); Arrays.asList(new SessionTrackingMode[]{SessionTrackingMode.COOKIE,SessionTrackingMode.URL})));
public final static String SESSION_KNOWN_ONLY_TO_AUTHENTICATED="org.eclipse.jetty.security.sessionKnownOnlytoAuthenticated";
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public final static int __distantFuture=60*60*24*7*52*20; public final static int __distantFuture=60*60*24*7*52*20;
@ -130,27 +130,6 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
protected final SampleStatistic _sessionTimeStats = new SampleStatistic(); protected final SampleStatistic _sessionTimeStats = new SampleStatistic();
/* ------------------------------------------------------------ */
public static HttpSession renewSession (HttpServletRequest request, HttpSession httpSession, boolean authenticated)
{
Map<String,Object> attributes = new HashMap<String, Object>();
for (Enumeration<String> e=httpSession.getAttributeNames();e.hasMoreElements();)
{
String name=e.nextElement();
attributes.put(name,httpSession.getAttribute(name));
httpSession.removeAttribute(name);
}
httpSession.invalidate();
httpSession = request.getSession(true);
if (authenticated)
httpSession.setAttribute(SESSION_KNOWN_ONLY_TO_AUTHENTICATED, Boolean.TRUE);
for (Map.Entry<String, Object> entry: attributes.entrySet())
httpSession.setAttribute(entry.getKey(),entry.getValue());
return httpSession;
}
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public AbstractSessionManager() public AbstractSessionManager()
{ {

View File

@ -218,5 +218,40 @@ public class HashSessionIdManager extends AbstractSessionIdManager
sessions.clear(); sessions.clear();
} }
} }
/* ------------------------------------------------------------ */
public void renewSessionId (String oldClusterId, String oldNodeId, HttpServletRequest request)
{
//generate a new id
String newClusterId = newSessionId(request.hashCode());
synchronized (this)
{
Set<WeakReference<HttpSession>> sessions = _sessions.remove(oldClusterId); //get the list of sessions with same id from other contexts
if (sessions!=null)
{
for (Iterator<WeakReference<HttpSession>> iter = sessions.iterator(); iter.hasNext();)
{
WeakReference<HttpSession> ref = iter.next();
HttpSession s = ref.get();
if (s == null)
{
continue;
}
else
{
if (s instanceof AbstractSession)
{
AbstractSession abstractSession = (AbstractSession)s;
abstractSession.getSessionManager().renewSessionId(oldClusterId, oldNodeId, newClusterId, getNodeId(newClusterId, request));
}
}
}
_sessions.put(newClusterId, sessions);
}
}
}
} }

View File

@ -51,7 +51,7 @@ import org.eclipse.jetty.util.log.Logger;
*/ */
public class HashSessionManager extends AbstractSessionManager public class HashSessionManager extends AbstractSessionManager
{ {
final static Logger __log = SessionHandler.LOG; final static Logger LOG = SessionHandler.LOG;
protected final ConcurrentMap<String,HashedSession> _sessions=new ConcurrentHashMap<String,HashedSession>(); protected final ConcurrentMap<String,HashedSession> _sessions=new ConcurrentHashMap<String,HashedSession>();
private static int __id; private static int __id;
@ -152,10 +152,10 @@ public class HashSessionManager extends AbstractSessionManager
public int getSessions() public int getSessions()
{ {
int sessions=super.getSessions(); int sessions=super.getSessions();
if (__log.isDebugEnabled()) if (LOG.isDebugEnabled())
{ {
if (_sessions.size()!=sessions) if (_sessions.size()!=sessions)
__log.warn("sessions: "+_sessions.size()+"!="+sessions); LOG.warn("sessions: "+_sessions.size()+"!="+sessions);
} }
return sessions; return sessions;
} }
@ -225,7 +225,7 @@ public class HashSessionManager extends AbstractSessionManager
} }
catch (Exception e) catch (Exception e)
{ {
__log.warn(e); LOG.warn(e);
} }
} }
}; };
@ -320,7 +320,7 @@ public class HashSessionManager extends AbstractSessionManager
} }
catch (Throwable t) catch (Throwable t)
{ {
__log.warn("Problem scavenging sessions", t); LOG.warn("Problem scavenging sessions", t);
} }
finally finally
{ {
@ -348,7 +348,7 @@ public class HashSessionManager extends AbstractSessionManager
} }
catch(Exception e) catch(Exception e)
{ {
__log.warn(e); LOG.warn(e);
} }
} }
@ -398,6 +398,37 @@ public class HashSessionManager extends AbstractSessionManager
sessions=new ArrayList<HashedSession>(_sessions.values()); sessions=new ArrayList<HashedSession>(_sessions.values());
} }
} }
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.server.SessionManager#renewSessionId(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public void renewSessionId(String oldClusterId, String oldNodeId, String newClusterId, String newNodeId)
{
try
{
Map<String,HashedSession> sessions=_sessions;
if (sessions == null)
return;
HashedSession session = sessions.remove(oldClusterId);
if (session == null)
return;
session.remove(); //delete any previously saved session
session.setClusterId(newClusterId); //update ids
session.setNodeId(newNodeId);
session.save(); //save updated session: TODO consider only saving file if idled
sessions.put(newClusterId, session);
}
catch (Exception e)
{
LOG.warn(e);
}
}
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@Override @Override
@ -467,7 +498,7 @@ public class HashSessionManager extends AbstractSessionManager
if (!_storeDir.canRead()) if (!_storeDir.canRead())
{ {
__log.warn ("Unable to restore Sessions: Cannot read from Session storage directory "+_storeDir.getAbsolutePath()); LOG.warn ("Unable to restore Sessions: Cannot read from Session storage directory "+_storeDir.getAbsolutePath());
return; return;
} }
@ -503,11 +534,11 @@ public class HashSessionManager extends AbstractSessionManager
if (file.exists()) if (file.exists())
{ {
file.delete(); file.delete();
__log.warn("Deleting file for unrestorable session "+idInCuster, e); LOG.warn("Deleting file for unrestorable session "+idInCuster, e);
} }
} }
else else
__log.warn("Problem restoring session "+idInCuster, e); LOG.warn("Problem restoring session "+idInCuster, e);
} }
return null; return null;
@ -523,12 +554,12 @@ public class HashSessionManager extends AbstractSessionManager
if (!_storeDir.canWrite()) if (!_storeDir.canWrite())
{ {
__log.warn ("Unable to save Sessions: Session persistence storage directory "+_storeDir.getAbsolutePath()+ " is not writeable"); LOG.warn ("Unable to save Sessions: Session persistence storage directory "+_storeDir.getAbsolutePath()+ " is not writeable");
return; return;
} }
for (HashedSession session : _sessions.values()) for (HashedSession session : _sessions.values())
session.save(true); session.save(reactivate);
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -88,8 +88,16 @@ public class HashedSession extends AbstractSession
throws IllegalStateException throws IllegalStateException
{ {
super.doInvalidate(); super.doInvalidate();
remove();
// Remove from the disk }
/* ------------------------------------------------------------ */
/**
* Remove from the disk
*/
synchronized void remove ()
{
if (_hashSessionManager._storeDir!=null && getId()!=null) if (_hashSessionManager._storeDir!=null && getId()!=null)
{ {
String id=getId(); String id=getId();
@ -107,41 +115,57 @@ public class HashedSession extends AbstractSession
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
LOG.debug("Saving {} {}",super.getId(),reactivate); LOG.debug("Saving {} {}",super.getId(),reactivate);
File file = null;
FileOutputStream fos = null;
try try
{ {
file = new File(_hashSessionManager._storeDir, super.getId());
if (file.exists())
file.delete();
file.createNewFile();
fos = new FileOutputStream(file);
willPassivate(); willPassivate();
save(fos); save();
if (reactivate) if (reactivate)
didActivate(); didActivate();
else else
clearAttributes(); clearAttributes();
} }
catch (Exception e) catch (Exception e)
{ {
saveFailed(); // We won't try again for this session
LOG.warn("Problem saving session " + super.getId(), e); LOG.warn("Problem saving session " + super.getId(), e);
_idled=false; // assume problem was before _values.clear();
}
}
}
synchronized void save ()
throws Exception
{
File file = null;
FileOutputStream fos = null;
if (!_saveFailed && _hashSessionManager._storeDir != null)
{
try
{
file = new File(_hashSessionManager._storeDir, super.getId());
if (file.exists())
file.delete();
file.createNewFile();
fos = new FileOutputStream(file);
save(fos);
}
catch (Exception e)
{
saveFailed();
if (fos != null) if (fos != null)
{ {
// Must not leave the file open if the saving failed // Must not leave the file open if the saving failed
IO.close(fos); IO.close(fos);
// No point keeping the file if we didn't save the whole session // No point keeping the file if we didn't save the whole session
file.delete(); file.delete();
_idled=false; // assume problem was before _values.clear(); throw e;
} }
} }
} }
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public synchronized void save(OutputStream os) throws IOException public synchronized void save(OutputStream os) throws IOException
{ {

View File

@ -386,6 +386,28 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
} }
} }
} }
public void addSession(String id)
{
if (id == null)
return;
synchronized (_sessionIds)
{
try
{
insert(id);
_sessionIds.add(id);
}
catch (Exception e)
{
LOG.warn("Problem storing session id="+id, e);
}
}
}
public void removeSession(HttpSession session) public void removeSession(HttpSession session)
{ {
@ -507,6 +529,35 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
} }
public void renewSessionId (String oldClusterId, String oldNodeId, HttpServletRequest request)
{
//generate a new id
String newClusterId = newSessionId(request.hashCode());
synchronized (_sessionIds)
{
removeSession(oldClusterId);//remove the old one from the list (and database)
addSession(newClusterId); //add in the new session id to the list (and database)
//tell all contexts to update the id
Handler[] contexts = _server.getChildHandlersByClass(ContextHandler.class);
for (int i=0; contexts!=null && i<contexts.length; i++)
{
SessionHandler sessionHandler = (SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class);
if (sessionHandler != null)
{
SessionManager manager = sessionHandler.getSessionManager();
if (manager != null && manager instanceof JDBCSessionManager)
{
((JDBCSessionManager)manager).renewSessionId(oldClusterId, oldNodeId, newClusterId, getNodeId(newClusterId, request));
}
}
}
}
}
/** /**
* Start up the id manager. * Start up the id manager.
* *
@ -655,7 +706,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
" where "+_sessionTableRowId+" = ?"; " where "+_sessionTableRowId+" = ?";
_updateSession = "update "+_sessionTable+ _updateSession = "update "+_sessionTable+
" set lastNode = ?, accessTime = ?, lastAccessTime = ?, lastSavedTime = ?, expiryTime = ?, map = ? where "+_sessionTableRowId+" = ?"; " set sessionId = ?, lastNode = ?, accessTime = ?, lastAccessTime = ?, lastSavedTime = ?, expiryTime = ?, map = ? where "+_sessionTableRowId+" = ?";
_updateSessionNode = "update "+_sessionTable+ _updateSessionNode = "update "+_sessionTable+
" set lastNode = ? where "+_sessionTableRowId+" = ?"; " set lastNode = ? where "+_sessionTableRowId+" = ?";

View File

@ -84,7 +84,7 @@ public class JDBCSessionManager extends AbstractSessionManager
*/ */
public class SessionData public class SessionData
{ {
private final String _id; private String _id;
private String _rowId; private String _rowId;
private long _accessed; private long _accessed;
private long _lastAccessed; private long _lastAccessed;
@ -120,6 +120,11 @@ public class JDBCSessionManager extends AbstractSessionManager
{ {
return _id; return _id;
} }
public synchronized void setId (String id)
{
_id = id;
}
public synchronized long getCreated () public synchronized long getCreated ()
{ {
@ -311,8 +316,38 @@ public class JDBCSessionManager extends AbstractSessionManager
_dirty=true; _dirty=true;
} }
@Override @Override
protected void cookieSet() protected void setClusterId(String clusterId)
{
super.setClusterId(clusterId);
_data.setId(clusterId);
_dirty = true;
}
@Override
protected void setNodeId(String nodeId)
{
_data.setLastNode(nodeId);
super.setNodeId(nodeId);
_dirty = true;
}
protected void save() throws Exception
{
try
{
updateSession(_data);
}
finally
{
_dirty = false;
}
}
@Override
protected void cookieSet()
{ {
_data.setCookieSet(_data.getAccessed()); _data.setCookieSet(_data.getAccessed());
} }
@ -638,6 +673,35 @@ public class JDBCSessionManager extends AbstractSessionManager
//any other nodes //any other nodes
} }
/**
*
* @see org.eclipse.jetty.server.SessionManager#renewSessionId(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void renewSessionId (String oldClusterId, String oldNodeId, String newClusterId, String newNodeId)
{
Session session = null;
synchronized (this)
{
try
{
session = (Session)_sessions.remove(oldClusterId);
if (session != null)
{
session.setClusterId(newClusterId); //update ids
session.setNodeId(newNodeId);
_sessions.put(newClusterId, session); //put it into list in memory
session.save(); //update database
}
}
catch (Exception e)
{
LOG.warn(e);
}
}
}
/** /**
* Invalidate a session. * Invalidate a session.
@ -971,11 +1035,12 @@ public class JDBCSessionManager extends AbstractSessionManager
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
connection.setAutoCommit(true); connection.setAutoCommit(true);
statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSession); statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSession);
statement.setString(1, getSessionIdManager().getWorkerName());//my node id statement.setString(1, data.getId());
statement.setLong(2, data.getAccessed());//accessTime statement.setString(2, getSessionIdManager().getWorkerName());//my node id
statement.setLong(3, data.getLastAccessed()); //lastAccessTime statement.setLong(3, data.getAccessed());//accessTime
statement.setLong(4, now); //last saved time statement.setLong(4, data.getLastAccessed()); //lastAccessTime
statement.setLong(5, data.getExpiryTime()); statement.setLong(5, now); //last saved time
statement.setLong(6, data.getExpiryTime());
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos); ObjectOutputStream oos = new ObjectOutputStream(baos);
@ -983,8 +1048,8 @@ public class JDBCSessionManager extends AbstractSessionManager
byte[] bytes = baos.toByteArray(); byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
statement.setBinaryStream(6, bais, bytes.length);//attribute map as blob statement.setBinaryStream(7, bais, bytes.length);//attribute map as blob
statement.setString(7, data.getRowId()); //rowId statement.setString(8, data.getRowId()); //rowId
statement.executeUpdate(); statement.executeUpdate();
data.setLastSaved(now); data.setLastSaved(now);

View File

@ -104,6 +104,13 @@ public class SessionCookieTest
return clusterId+'.'+_workerName; return clusterId+'.'+_workerName;
} }
@Override
public void renewSessionId(String oldClusterId, String oldNodeId, HttpServletRequest request)
{
// TODO Auto-generated method stub
}
} }
public class MockSessionManager extends AbstractSessionManager public class MockSessionManager extends AbstractSessionManager
@ -149,6 +156,13 @@ public class SessionCookieTest
return false; return false;
} }
@Override
public void renewSessionId(String oldClusterId, String oldNodeId, String newClusterId, String newNodeId)
{
// TODO Auto-generated method stub
}
} }
@Test @Test

View File

@ -410,6 +410,8 @@
<module>examples/embedded</module> <module>examples/embedded</module>
<module>examples/async-rest</module> <module>examples/async-rest</module>
<module>jetty-rewrite</module> <module>jetty-rewrite</module>
<module>jetty-nosql</module>
<module>tests/test-sessions</module>
<!-- modules that need fixed and added back, or simply dropped and not maintained <!-- modules that need fixed and added back, or simply dropped and not maintained
<module>tests</module> <module>tests</module>
@ -421,7 +423,6 @@
<module>jetty-monitor</module> <module>jetty-monitor</module>
<module>jetty-nested</module> <module>jetty-nested</module>
<module>jetty-overlay-deployer</module> <module>jetty-overlay-deployer</module>
<module>jetty-nosql</module>
<module>jetty-http-spi</module> <module>jetty-http-spi</module>
<module>test-jetty-nested</module> <module>test-jetty-nested</module>
--> -->

View File

@ -32,6 +32,7 @@
<module>test-sessions-common</module> <module>test-sessions-common</module>
<module>test-hash-sessions</module> <module>test-hash-sessions</module>
<module>test-jdbc-sessions</module> <module>test-jdbc-sessions</module>
<module>test-mongodb-sessions</module> <!-- Requires mongodb server running -->
<!-- module>test-mongodb-sessions</module -->
</modules> </modules>
</project> </project>

View File

@ -0,0 +1,39 @@
package org.eclipse.jetty.server.session;
import java.io.File;
import org.eclipse.jetty.server.SessionManager;
import org.junit.Test;
public class SessionRenewTest extends AbstractSessionRenewTest
{
@Override
public AbstractTestServer createServer(int port, int max, int scavenge)
{
return new HashTestServer(port, max, scavenge)
{
@Override
public SessionManager newSessionManager()
{
HashSessionManager sessionManager = (HashSessionManager)super.newSessionManager();
sessionManager.setSavePeriod(2);
File tmpDir = new File(System.getProperty("java.io.tmpdir"), "hash-session-renew-test");
tmpDir.deleteOnExit();
tmpDir.mkdirs();
sessionManager.setStoreDirectory(tmpDir);
return sessionManager;
}
};
}
@Test
public void testSessionRenewal() throws Exception
{
super.testSessionRenewal();
}
}

View File

@ -18,7 +18,6 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import org.eclipse.jetty.util.log.Log;
import org.junit.Test; import org.junit.Test;
/** /**

View File

@ -25,17 +25,17 @@ import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.concurrent.Future;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.log.Log;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -73,7 +73,6 @@ public class MaxInactiveMigrationTest
testServer1.start(); testServer1.start();
testServer2.start(); testServer2.start();
client = new HttpClient(); client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
} }
@ -99,22 +98,19 @@ public class MaxInactiveMigrationTest
int port=server.getPort(); int port=server.getPort();
//Log.getLog().setDebugEnabled(true); //Log.getLog().setDebugEnabled(true);
Request request = client.newRequest("http://localhost:" + port + "" + "/test");
ContentExchange exchange1 = new ContentExchange(true);
exchange1.setMethod(HttpMethods.GET);
exchange1.setURL("http://localhost:" + port + "" + "/test");
if (sessionCookie != null) if (sessionCookie != null)
exchange1.getRequestFields().add("Cookie", sessionCookie); request.header("Cookie", sessionCookie);
client.send(exchange1); Future<ContentResponse> future = request.send();
exchange1.waitForDone(); ContentResponse response = future.get();
assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus()); assertEquals(HttpServletResponse.SC_OK, response.getStatus());
sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie"); sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue( sessionCookie != null ); assertTrue( sessionCookie != null );
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
return exchange1.getResponseContent(); return response.getContentAsString();
} }

View File

@ -0,0 +1,22 @@
package org.eclipse.jetty.server.session;
import org.junit.Test;
public class SessionRenewTest extends AbstractSessionRenewTest
{
@Override
public AbstractTestServer createServer(int port, int max, int scavenge)
{
return new JdbcTestServer(port, max, scavenge);
}
@Test
public void testSessionRenewal() throws Exception
{
super.testSessionRenewal();
}
}

View File

@ -18,7 +18,6 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import org.eclipse.jetty.util.log.Log;
import org.junit.Test; import org.junit.Test;
/** /**
@ -31,7 +30,7 @@ public class SessionValueSavingTest extends AbstractSessionValueSavingTest
return new JdbcTestServer(port,max,scavenge); return new JdbcTestServer(port,max,scavenge);
} }
@Override @Test
public void testSessionValueSaving() throws Exception public void testSessionValueSaving() throws Exception
{ {
super.testSessionValueSaving(); super.testSessionValueSaving();

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.nosql.mongodb;
import org.eclipse.jetty.server.session.AbstractLastAccessTimeTest; import org.eclipse.jetty.server.session.AbstractLastAccessTimeTest;
import org.eclipse.jetty.server.session.AbstractTestServer; import org.eclipse.jetty.server.session.AbstractTestServer;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
public class LastAccessTimeTest extends AbstractLastAccessTimeTest public class LastAccessTimeTest extends AbstractLastAccessTimeTest

View File

@ -58,10 +58,10 @@ public class MongoTestServer extends AbstractTestServer
{ {
try try
{ {
System.err.println("MongoTestServer:SessionIdManager:" + _maxInactivePeriod + "/" + _scavengePeriod); System.err.println("MongoTestServer:SessionIdManager scavenge: delay:"+ _scavengePeriod + " period:"+_maxInactivePeriod);
MongoSessionIdManager idManager = new MongoSessionIdManager(_server); MongoSessionIdManager idManager = new MongoSessionIdManager(_server);
idManager.setWorkerName("w"+(__workers++)); idManager.setWorkerName("w"+(__workers++));
idManager.setScavengeDelay((int)TimeUnit.SECONDS.toMillis(_scavengePeriod)); idManager.setScavengeDelay((_scavengePeriod));
idManager.setScavengePeriod(_maxInactivePeriod); idManager.setScavengePeriod(_maxInactivePeriod);
return idManager; return idManager;

View File

@ -0,0 +1,39 @@
//
// ========================================================================
// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.nosql.mongodb;
import org.eclipse.jetty.server.session.AbstractSessionRenewTest;
import org.eclipse.jetty.server.session.AbstractTestServer;
import org.junit.Test;
public class SessionRenewTest extends AbstractSessionRenewTest
{
@Override
public AbstractTestServer createServer(int port, int max, int scavenge)
{
return new MongoTestServer(port, max, scavenge);
}
@Test
public void testSessionRenewal() throws Exception
{
super.testSessionRenewal();
}
}

View File

@ -26,6 +26,7 @@ import java.io.PrintWriter;
import java.io.Serializable; import java.io.Serializable;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.util.concurrent.Future;
import javax.management.remote.JMXServiceURL; import javax.management.remote.JMXServiceURL;
import javax.servlet.ServletException; import javax.servlet.ServletException;
@ -33,15 +34,14 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.jmx.ConnectorServer; import org.eclipse.jetty.jmx.ConnectorServer;
import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.nosql.NoSqlSession; import org.eclipse.jetty.nosql.NoSqlSession;
import org.eclipse.jetty.server.session.AbstractSessionValueSavingTest; import org.eclipse.jetty.server.session.AbstractSessionValueSavingTest;
import org.eclipse.jetty.server.session.AbstractTestServer; import org.eclipse.jetty.server.session.AbstractTestServer;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
public class SessionSavingValueTest extends AbstractSessionValueSavingTest public class SessionSavingValueTest extends AbstractSessionValueSavingTest
@ -51,31 +51,31 @@ public class SessionSavingValueTest extends AbstractSessionValueSavingTest
public AbstractTestServer createServer(int port, int max, int scavenge) public AbstractTestServer createServer(int port, int max, int scavenge)
{ {
// ConnectorServer srv = null; ConnectorServer srv = null;
try try
{ {
// srv = new ConnectorServer( srv = new ConnectorServer(
// new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:0/jettytest"), new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:0/jettytest"),
// "org.eclipse.jetty:name=rmiconnectorserver"); "org.eclipse.jetty:name=rmiconnectorserver");
// srv.start(); srv.start();
MongoTestServer server = new MongoTestServer(port,max,scavenge,true); MongoTestServer server = new MongoTestServer(port,max,scavenge,true);
// MBeanContainer mbean = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); MBeanContainer mbean = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
//
// server.getServer().getContainer().addEventListener(mbean); //server.getServer().getContainer().addEventListener(mbean);
// server.getServer().addBean(mbean); server.getServer().addBean(mbean);
//
// mbean.start(); //mbean.start();
return server; return server;
} }
// catch (MalformedURLException e) catch (MalformedURLException e)
// { {
// // TODO Auto-generated catch block // TODO Auto-generated catch block
// e.printStackTrace(); e.printStackTrace();
// } }
catch (Exception e) catch (Exception e)
{ {
// TODO Auto-generated catch block // TODO Auto-generated catch block
@ -86,7 +86,7 @@ public class SessionSavingValueTest extends AbstractSessionValueSavingTest
} }
@Test @Test
@Ignore ("requires mongodb server") //@Ignore ("requires mongodb server")
public void testSessionValueSaving() throws Exception public void testSessionValueSaving() throws Exception
{ {
String contextPath = ""; String contextPath = "";
@ -101,7 +101,6 @@ public class SessionSavingValueTest extends AbstractSessionValueSavingTest
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
@ -109,19 +108,17 @@ public class SessionSavingValueTest extends AbstractSessionValueSavingTest
{ "0", "null" }; { "0", "null" };
// Perform one request to server1 to create a session // Perform one request to server1 to create a session
ContentExchange exchange1 = new ContentExchange(true); Request request = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
exchange1.setMethod(HttpMethods.GET); Future<ContentResponse> future = request.send();
exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping + "?action=init"); ContentResponse response = future.get();
client.send(exchange1); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String[] sessionTestResponse = exchange1.getResponseContent().split("/"); String[] sessionTestResponse = response.getContentAsString().split("/");
assertTrue(Long.parseLong(sessionTestValue[0]) < Long.parseLong(sessionTestResponse[0])); assertTrue(Long.parseLong(sessionTestValue[0]) < Long.parseLong(sessionTestResponse[0]));
sessionTestValue = sessionTestResponse; sessionTestValue = sessionTestResponse;
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie"); String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=","$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=","$1\\$Path=");
@ -135,22 +132,21 @@ public class SessionSavingValueTest extends AbstractSessionValueSavingTest
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
{ {
ContentExchange exchange2 = new ContentExchange(true); Request request2 = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping);
exchange2.setMethod(HttpMethods.GET); request2.header("Cookie",sessionCookie);
exchange2.setURL("http://localhost:" + port1 + contextPath + servletMapping); Future<ContentResponse> future2 = request2.send();
exchange2.getRequestFields().add("Cookie",sessionCookie); ContentResponse response2 = future2.get();
client.send(exchange2);
exchange2.waitForDone(); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
sessionTestResponse = exchange2.getResponseContent().split("/"); sessionTestResponse = response2.getContentAsString().split("/");
assertTrue(Long.parseLong(sessionTestValue[0]) < Long.parseLong(sessionTestResponse[0])); assertTrue(Long.parseLong(sessionTestValue[0]) < Long.parseLong(sessionTestResponse[0]));
assertTrue(Long.parseLong(sessionTestValue[1]) < Long.parseLong(sessionTestResponse[1])); assertTrue(Long.parseLong(sessionTestValue[1]) < Long.parseLong(sessionTestResponse[1]));
sessionTestValue = sessionTestResponse; sessionTestValue = sessionTestResponse;
String setCookie = exchange1.getResponseFields().getStringField("Set-Cookie"); String setCookie = response2.getHeaders().getStringField("Set-Cookie");
if (setCookie != null) if (setCookie != null)
sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=","$1\\$Path="); sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=","$1\\$Path=");

View File

@ -18,9 +18,11 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.concurrent.Future;
import java.util.Random;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -28,14 +30,12 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
@ -67,31 +67,25 @@ public abstract class AbstractClientCrossContextSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
// Perform a request to contextA // Perform a request to contextA
ContentExchange exchangeA = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port + contextA + servletMapping);
exchangeA.setMethod(HttpMethods.GET); ContentResponse response = future.get();
exchangeA.setURL("http://localhost:" + port + contextA + servletMapping);
client.send(exchangeA); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
exchangeA.waitForDone(); String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertEquals(HttpServletResponse.SC_OK,exchangeA.getResponseStatus());
String sessionCookie = exchangeA.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Perform a request to contextB with the same session cookie // Perform a request to contextB with the same session cookie
ContentExchange exchangeB = new ContentExchange(true); Request request = client.newRequest("http://localhost:" + port + contextB + servletMapping);
exchangeB.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchangeB.setURL("http://localhost:" + port + contextB + servletMapping); future = request.send();
System.err.println("Cookie = "+sessionCookie); ContentResponse responseB = future.get();
exchangeB.getRequestFields().add("Cookie", sessionCookie); assertEquals(HttpServletResponse.SC_OK,responseB.getStatus());
client.send(exchangeB);
exchangeB.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchangeB.getResponseStatus());
assertEquals(servletA.sessionId, servletB.sessionId); assertEquals(servletA.sessionId, servletB.sessionId);
} }
finally finally

View File

@ -18,9 +18,12 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -28,12 +31,10 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
@ -58,38 +59,32 @@ public abstract class AbstractImmortalSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
int value = 42; int value = 42;
ContentExchange exchange = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=set&value=" + value);
exchange.setMethod(HttpMethods.GET); ContentResponse response = future.get();
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=set&value=" + value); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
client.send(exchange); String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
String sessionCookie = exchange.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
String response = exchange.getResponseContent(); String resp = response.getContentAsString();
assertEquals(response.trim(),String.valueOf(value)); assertEquals(resp.trim(),String.valueOf(value));
// Let's wait for the scavenger to run, waiting 2.5 times the scavenger period // Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
Thread.sleep(scavengePeriod * 2500L); Thread.sleep(scavengePeriod * 2500L);
// Be sure the session is still there // Be sure the session is still there
exchange = new ContentExchange(true); Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=get");
exchange.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=get"); future = request.send();
exchange.getRequestFields().add("Cookie", sessionCookie); response = future.get();
client.send(exchange); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
exchange.waitForDone(); resp = response.getContentAsString();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus()); assertEquals(String.valueOf(value),resp.trim());
response = exchange.getResponseContent();
assertEquals(String.valueOf(value),response.trim());
} }
finally finally
{ {

View File

@ -18,8 +18,11 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -27,12 +30,11 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* AbstractInvalidationSessionTest * AbstractInvalidationSessionTest
@ -53,16 +55,19 @@ public abstract class AbstractInvalidationSessionTest
server1.addContext(contextPath).addServlet(TestServlet.class, servletMapping); server1.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
server1.start(); server1.start();
int port1 = server1.getPort(); int port1 = server1.getPort();
System.err.println("Port1="+port1);
try try
{ {
AbstractTestServer server2 = createServer(0); AbstractTestServer server2 = createServer(0);
server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping); server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
server2.start(); server2.start();
int port2=server2.getPort(); int port2=server2.getPort();
System.err.println("port2="+port2);
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET); QueuedThreadPool executor = new QueuedThreadPool();
client.setExecutor(executor);
client.start(); client.start();
try try
{ {
@ -71,45 +76,37 @@ public abstract class AbstractInvalidationSessionTest
urls[1] = "http://localhost:" + port2 + contextPath + servletMapping; urls[1] = "http://localhost:" + port2 + contextPath + servletMapping;
// Create the session on node1 // Create the session on node1
ContentExchange exchange1 = new ContentExchange(true); Future<ContentResponse> future = client.GET(urls[0] + "?action=init");
exchange1.setMethod(HttpMethods.GET); ContentResponse response1 = future.get();
exchange1.setURL(urls[0] + "?action=init");
client.send(exchange1); assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
exchange1.waitForDone(); String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Be sure the session is also present in node2 // Be sure the session is also present in node2
ContentExchange exchange2 = new ContentExchange(true);
exchange2.setMethod(HttpMethods.GET); Request request2 = client.newRequest(urls[1] + "?action=increment");
exchange2.setURL(urls[1] + "?action=increment"); request2.header("Cookie", sessionCookie);
exchange2.getRequestFields().add("Cookie", sessionCookie); future = request2.send();
client.send(exchange2); ContentResponse response2 = future.get();
exchange2.waitForDone(); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
// Invalidate on node1 // Invalidate on node1
exchange1 = new ContentExchange(true); Request request1 = client.newRequest(urls[0] + "?action=invalidate");
exchange1.setMethod(HttpMethods.GET); request1.header("Cookie", sessionCookie);
exchange1.setURL(urls[0] + "?action=invalidate"); future = request1.send();
exchange1.getRequestFields().add("Cookie", sessionCookie); assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
client.send(exchange1);
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus());
pause(); pause();
// Be sure on node2 we don't see the session anymore // Be sure on node2 we don't see the session anymore
exchange2 = new ContentExchange(true); request2 = client.newRequest(urls[1] + "?action=test");
exchange2.setMethod(HttpMethods.GET); request2.header("Cookie", sessionCookie);
exchange2.setURL(urls[1] + "?action=test"); future = request2.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); response2 = future.get();
client.send(exchange2); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
} }
finally finally
{ {

View File

@ -18,26 +18,36 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* AbstractLastAccessTimeTest * AbstractLastAccessTimeTest
*
* This test checks that a session can migrate from node A to node B, kept in use in node B
* past the time at which it would have expired due to inactivity on node A but is NOT
* scavenged by node A. In other words, it tests that a session that migrates from one node
* to another is not timed out on the original node.
*/ */
public abstract class AbstractLastAccessTimeTest public abstract class AbstractLastAccessTimeTest
{ {
@ -48,10 +58,15 @@ public abstract class AbstractLastAccessTimeTest
{ {
String contextPath = ""; String contextPath = "";
String servletMapping = "/server"; String servletMapping = "/server";
int maxInactivePeriod = 8; int maxInactivePeriod = 8; //session will timeout after 8 seconds
int scavengePeriod = 2; int scavengePeriod = 2; //scavenging occurs every 2 seconds
AbstractTestServer server1 = createServer(0, maxInactivePeriod, scavengePeriod); AbstractTestServer server1 = createServer(0, maxInactivePeriod, scavengePeriod);
server1.addContext(contextPath).addServlet(TestServlet.class, servletMapping); TestServlet servlet1 = new TestServlet();
ServletHolder holder1 = new ServletHolder(servlet1);
ServletContextHandler context = server1.addContext(contextPath);
TestSessionListener listener1 = new TestSessionListener();
context.addEventListener(listener1);
context.addServlet(holder1, servletMapping);
server1.start(); server1.start();
int port1=server1.getPort(); int port1=server1.getPort();
try try
@ -63,19 +78,15 @@ public abstract class AbstractLastAccessTimeTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
// Perform one request to server1 to create a session // Perform one request to server1 to create a session
ContentExchange exchange1 = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
exchange1.setMethod(HttpMethods.GET); ContentResponse response1 = future.get();
exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping + "?action=init"); assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
client.send(exchange1); assertEquals("test", response1.getContentAsString());
exchange1.waitForDone(); String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus());
assertEquals("test", exchange1.getResponseContent());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assertTrue( sessionCookie != null ); assertTrue( sessionCookie != null );
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -88,16 +99,14 @@ public abstract class AbstractLastAccessTimeTest
int requestInterval = 500; int requestInterval = 500;
for (int i = 0; i < maxInactivePeriod * (1000 / requestInterval); ++i) for (int i = 0; i < maxInactivePeriod * (1000 / requestInterval); ++i)
{ {
ContentExchange exchange2 = new ContentExchange(true); Request request = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping);
exchange2.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange2.setURL("http://localhost:" + port2 + contextPath + servletMapping); future = request.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); ContentResponse response2 = future.get();
client.send(exchange2); assertEquals(HttpServletResponse.SC_OK , response2.getStatus());
exchange2.waitForDone(); assertEquals("test", response2.getContentAsString());
assertEquals(HttpServletResponse.SC_OK , exchange2.getResponseStatus());
assertEquals("test", exchange2.getResponseContent());
String setCookie = exchange1.getResponseFields().getStringField("Set-Cookie"); String setCookie = response2.getHeaders().getStringField("Set-Cookie");
if (setCookie!=null) if (setCookie!=null)
sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -108,17 +117,8 @@ public abstract class AbstractLastAccessTimeTest
// Let's wait for the scavenger to run, waiting 2.5 times the scavenger period // Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
Thread.sleep(scavengePeriod * 2500L); Thread.sleep(scavengePeriod * 2500L);
// Access again server1, and ensure that we can still access the session //check that the session was not scavenged over on server1 by ensuring that the SessionListener destroy method wasn't called
exchange1 = new ContentExchange(true); assertTrue (listener1.destroyed == false);
exchange1.setMethod(HttpMethods.GET);
exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping);
exchange1.getRequestFields().add("Cookie", sessionCookie);
client.send(exchange1);
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus());
//test that the session was kept alive by server 2 and still contains what server1 put in it
assertEquals("test", exchange1.getResponseContent());
} }
finally finally
{ {
@ -136,8 +136,30 @@ public abstract class AbstractLastAccessTimeTest
} }
} }
public static class TestSessionListener implements HttpSessionListener
{
public boolean destroyed = false;
public boolean created = false;
@Override
public void sessionDestroyed(HttpSessionEvent se)
{
destroyed = true;
}
@Override
public void sessionCreated(HttpSessionEvent se)
{
created = true;
}
}
public static class TestServlet extends HttpServlet public static class TestServlet extends HttpServlet
{ {
@Override @Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException
{ {
@ -146,7 +168,6 @@ public abstract class AbstractLastAccessTimeTest
{ {
HttpSession session = request.getSession(true); HttpSession session = request.getSession(true);
session.setAttribute("test", "test"); session.setAttribute("test", "test");
sendResult(session, httpServletResponse.getWriter()); sendResult(session, httpServletResponse.getWriter());
} }
@ -161,8 +182,6 @@ public abstract class AbstractLastAccessTimeTest
{ {
session.setAttribute("test", "test"); session.setAttribute("test", "test");
} }
} }
} }

View File

@ -18,12 +18,16 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.Random; import java.util.Random;
import java.util.concurrent.CyclicBarrier; import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException; import javax.servlet.ServletException;
@ -32,12 +36,10 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
@ -70,7 +72,6 @@ public abstract class AbstractLightLoadTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType( HttpClient.CONNECTOR_SOCKET );
client.start(); client.start();
try try
{ {
@ -78,13 +79,10 @@ public abstract class AbstractLightLoadTest
urls[0] = "http://localhost:" + port1 + contextPath + servletMapping; urls[0] = "http://localhost:" + port1 + contextPath + servletMapping;
urls[1] = "http://localhost:" + port2 + contextPath + servletMapping; urls[1] = "http://localhost:" + port2 + contextPath + servletMapping;
ContentExchange exchange1 = new ContentExchange( true ); Future<ContentResponse> future = client.GET( urls[0] + "?action=init" );
exchange1.setMethod( HttpMethods.GET ); ContentResponse response1 = future.get();
exchange1.setURL( urls[0] + "?action=init" ); assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
client.send( exchange1 ); String sessionCookie = response1.getHeaders().getStringField( "Set-Cookie" );
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String sessionCookie = exchange1.getResponseFields().getStringField( "Set-Cookie" );
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -115,14 +113,12 @@ public abstract class AbstractLightLoadTest
executor.shutdownNow(); executor.shutdownNow();
// Perform one request to get the result // Perform one request to get the result
ContentExchange exchange2 = new ContentExchange( true ); Request request = client.newRequest( urls[0] + "?action=result" );
exchange2.setMethod( HttpMethods.GET ); request.header("Cookie", sessionCookie);
exchange2.setURL( urls[0] + "?action=result" ); future = request.send();
exchange2.getRequestFields().add( "Cookie", sessionCookie ); ContentResponse response2 = future.get();
client.send( exchange2 ); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
exchange2.waitForDone(); String response = response2.getContentAsString();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
String response = exchange2.getResponseContent();
System.out.println( "get = " + response ); System.out.println( "get = " + response );
assertEquals(response.trim(), String.valueOf( clientsCount * requestsCount ) ); assertEquals(response.trim(), String.valueOf( clientsCount * requestsCount ) );
} }
@ -155,11 +151,11 @@ public abstract class AbstractLightLoadTest
private final String sessionCookie; private final String sessionCookie;
private final String[] urls; private final String[] urls;
public Worker( CyclicBarrier barrier, int requestsCount, String sessionCookie, String[] urls ) public Worker( CyclicBarrier barrier, int requestsCount, String sessionCookie, String[] urls )
{ {
this.client = new HttpClient(); this.client = new HttpClient();
this.client.setConnectorType( HttpClient.CONNECTOR_SOCKET );
this.barrier = barrier; this.barrier = barrier;
this.requestsCount = requestsCount; this.requestsCount = requestsCount;
this.sessionCookie = sessionCookie; this.sessionCookie = sessionCookie;
@ -186,18 +182,15 @@ public abstract class AbstractLightLoadTest
barrier.await(); barrier.await();
Random random = new Random( System.nanoTime() ); Random random = new Random( System.nanoTime() );
for ( int i = 0; i < requestsCount; ++i ) for ( int i = 0; i < requestsCount; ++i )
{ {
int urlIndex = random.nextInt( urls.length ); int urlIndex = random.nextInt( urls.length );
Request request = client.newRequest(urls[urlIndex] + "?action=increment");
ContentExchange exchange = new ContentExchange( true ); request.header("Cookie", sessionCookie);
exchange.setMethod( HttpMethods.GET ); Future<ContentResponse> future = request.send();
exchange.setURL( urls[urlIndex] + "?action=increment" ); ContentResponse response = future.get();
exchange.getRequestFields().add( "Cookie", sessionCookie ); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
client.send( exchange );
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
} }
// Wait for all workers to be done // Wait for all workers to be done

View File

@ -18,8 +18,11 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -27,14 +30,11 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SessionManager; import org.eclipse.jetty.server.SessionManager;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* AbstractLocalSessionScavengingTest * AbstractLocalSessionScavengingTest
@ -75,7 +75,6 @@ public abstract class AbstractLocalSessionScavengingTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
@ -84,50 +83,43 @@ public abstract class AbstractLocalSessionScavengingTest
urls[1] = "http://localhost:" + port2 + contextPath + servletMapping; urls[1] = "http://localhost:" + port2 + contextPath + servletMapping;
// Create the session on node1 // Create the session on node1
ContentExchange exchange1 = new ContentExchange(true); Future<ContentResponse> future = client.GET(urls[0] + "?action=init");
exchange1.setMethod(HttpMethods.GET); ContentResponse response1 = future.get();
exchange1.setURL(urls[0] + "?action=init"); assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
client.send(exchange1); String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Be sure the session is also present in node2 // Be sure the session is also present in node2
ContentExchange exchange2 = new ContentExchange(true); org.eclipse.jetty.client.api.Request request = client.newRequest(urls[1] + "?action=test");
exchange2.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange2.setURL(urls[1] + "?action=test"); future = request.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); ContentResponse response2 = future.get();
client.send(exchange2); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
// Wait for the scavenger to run on node1, waiting 2.5 times the scavenger period // Wait for the scavenger to run on node1, waiting 2.5 times the scavenger period
pause(scavengePeriod); pause(scavengePeriod);
// Check that node1 does not have any local session cached // Check that node1 does not have any local session cached
exchange1 = new ContentExchange(true); request = client.newRequest(urls[0] + "?action=check");
exchange1.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange1.setURL(urls[0] + "?action=check"); future = request.send();
client.send(exchange1); response1 = future.get();
exchange1.waitForDone(); assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
// Wait for the scavenger to run on node2, waiting 2 times the scavenger period // Wait for the scavenger to run on node2, waiting 2 times the scavenger period
// This ensures that the scavenger on node2 runs at least once. // This ensures that the scavenger on node2 runs at least once.
pause(scavengePeriod); pause(scavengePeriod);
// Check that node2 does not have any local session cached // Check that node2 does not have any local session cached
exchange2 = new ContentExchange(true); request = client.newRequest(urls[1] + "?action=check");
exchange2.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange2.setURL(urls[1] + "?action=check"); future = request.send();
client.send(exchange2); response2 = future.get();
exchange2.waitForDone(); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
} }
finally finally
{ {

View File

@ -18,8 +18,11 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -27,13 +30,11 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* AbstractNewSessionTest * AbstractNewSessionTest
@ -68,17 +69,13 @@ public abstract class AbstractNewSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
ContentExchange exchange = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
exchange.setMethod(HttpMethods.GET); ContentResponse response = future.get();
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=create"); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
client.send(exchange); String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
String sessionCookie = exchange.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -88,13 +85,11 @@ public abstract class AbstractNewSessionTest
// The session is not there anymore, but we present an old cookie // The session is not there anymore, but we present an old cookie
// The server creates a new session, we must ensure we released all locks // The server creates a new session, we must ensure we released all locks
exchange = new ContentExchange(true); Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=old-create");
exchange.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=old-create"); future = request.send();
exchange.getRequestFields().add("Cookie", sessionCookie); response = future.get();
client.send(exchange); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
} }
finally finally
{ {

View File

@ -18,8 +18,11 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException; import javax.servlet.ServletException;
@ -28,12 +31,10 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* AbstractOrphanedSessionTest * AbstractOrphanedSessionTest
@ -68,18 +69,14 @@ public abstract class AbstractOrphanedSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
// Connect to server1 to create a session and get its session cookie // Connect to server1 to create a session and get its session cookie
ContentExchange exchange1 = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
exchange1.setMethod(HttpMethods.GET); ContentResponse response1 = future.get();
exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping + "?action=init"); assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
client.send(exchange1); String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -90,13 +87,11 @@ public abstract class AbstractOrphanedSessionTest
Thread.sleep(TimeUnit.SECONDS.toMillis(inactivePeriod + 2L * scavengePeriod)); Thread.sleep(TimeUnit.SECONDS.toMillis(inactivePeriod + 2L * scavengePeriod));
// Perform one request to server2 to be sure that the session has been expired // Perform one request to server2 to be sure that the session has been expired
ContentExchange exchange2 = new ContentExchange(true); Request request = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=check");
exchange2.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange2.setURL("http://localhost:" + port2 + contextPath + servletMapping + "?action=check"); future = request.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); ContentResponse response2 = future.get();
client.send(exchange2); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
} }
finally finally
{ {

View File

@ -18,8 +18,11 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -27,12 +30,9 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
@ -54,16 +54,12 @@ public abstract class AbstractReentrantRequestSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
ContentExchange exchange = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=reenter&port=" + port + "&path=" + contextPath + servletMapping);
exchange.setMethod(HttpMethods.GET); ContentResponse response = future.get();
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=reenter&port=" + port + "&path=" + contextPath + servletMapping); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
client.send(exchange);
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
} }
finally finally
{ {
@ -103,16 +99,12 @@ public abstract class AbstractReentrantRequestSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
ContentExchange exchange = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port + path + ";jsessionid="+session.getId()+"?action=none");
exchange.setMethod(HttpMethods.GET); ContentResponse resp = future.get();
exchange.setURL("http://localhost:" + port + path + ";jsessionid="+session.getId()+"?action=none"); assertEquals(HttpServletResponse.SC_OK,resp.getStatus());
client.send(exchange);
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
assertEquals("true",session.getAttribute("reentrant")); assertEquals("true",session.getAttribute("reentrant"));
} }
finally finally

View File

@ -18,23 +18,27 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.EventListener; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.Test; import org.junit.Test;
@ -59,44 +63,36 @@ public abstract class AbstractRemoveSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
ContentExchange exchange = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
exchange.setMethod(HttpMethods.GET); ContentResponse response = future.get();
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=create"); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
client.send(exchange); String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
String sessionCookie = exchange.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
//ensure sessionCreated listener is called //ensure sessionCreated listener is called
assertTrue (testListener.isCreated()); assertTrue (testListener.isCreated());
//now delete the session //now delete the session
exchange = new ContentExchange(true); Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=delete");
exchange.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=delete"); future = request.send();
exchange.getRequestFields().add("Cookie", sessionCookie); response = future.get();
client.send(exchange); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
//ensure sessionDestroyed listener is called //ensure sessionDestroyed listener is called
assertTrue(testListener.isDestroyed()); assertTrue(testListener.isDestroyed());
// The session is not there anymore, but we present an old cookie // The session is not there anymore, but we present an old cookie
// The server creates a new session, we must ensure we released all locks // The server creates a new session, we must ensure we released all locks
exchange = new ContentExchange(true); request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=check");
exchange.setMethod(HttpMethods.GET); request.header("Cookie", sessionCookie);
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=check"); future = request.send();
exchange.getRequestFields().add("Cookie", sessionCookie); response = future.get();
client.send(exchange); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
} }
finally finally
{ {

View File

@ -18,9 +18,12 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.RequestDispatcher; import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
@ -30,13 +33,10 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* AbstractServerCrossContextSessionTest * AbstractServerCrossContextSessionTest
@ -62,17 +62,13 @@ public abstract class AbstractServerCrossContextSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
// Perform a request, on server side a cross context dispatch will be done // Perform a request, on server side a cross context dispatch will be done
ContentExchange exchange = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port + contextA + servletMapping);
exchange.setMethod(HttpMethods.GET); ContentResponse response = future.get();
exchange.setURL("http://localhost:" + port + contextA + servletMapping); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
client.send(exchange);
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
} }
finally finally
{ {

View File

@ -20,6 +20,7 @@ package org.eclipse.jetty.server.session;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.Random;
import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -29,14 +30,13 @@ import javax.servlet.http.HttpSession;
import junit.framework.Assert; import junit.framework.Assert;
import org.eclipse.jetty.client.Address;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpDestination; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpCookie; import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.http.HttpMethods;
import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.log.Log;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -76,43 +76,33 @@ public abstract class AbstractSessionCookieTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
ContentExchange exchange = new ContentExchange(true);
exchange.setMethod(HttpMethods.GET); Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=create"); ContentResponse response = future.get();
client.send(exchange); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus()); String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
String sessionCookie = exchange.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
//sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); //sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Let's wait for the scavenger to run, waiting 2.5 times the scavenger period // Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
//pause(scavengePeriod); //pause(scavengePeriod);
Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=check-cookie");
exchange = new ContentExchange(true); request.header("Cookie", sessionCookie);
exchange.setMethod(HttpMethods.GET); future = request.send();
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=check-cookie"); response = future.get();
exchange.getRequestFields().add("Cookie", sessionCookie);
client.send(exchange);
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
exchange = new ContentExchange(true); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
exchange.setMethod(HttpMethods.GET);
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=null-cookie");
//exchange.getRequestFields().add("Cookie", "null");
HttpDestination dest = client.getDestination(new Address("localhost",port),false);
dest.addCookie(new HttpCookie("Cookie",null)); request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=null-cookie");
request.header("Cookie", sessionCookie);
client.send(exchange); future = request.send();
exchange.waitForDone(); response = future.get();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus()); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
} }
finally finally
{ {

View File

@ -18,7 +18,11 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -26,16 +30,11 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.Request; import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.server.session.AbstractTestServer;
import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ -78,18 +77,14 @@ public abstract class AbstractSessionExpiryTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
String url = "http://localhost:" + port1 + contextPath + servletMapping; String url = "http://localhost:" + port1 + contextPath + servletMapping;
//make a request to set up a session on the server //make a request to set up a session on the server
ContentExchange exchange1 = new ContentExchange(true); Future<ContentResponse> future = client.GET(url + "?action=init");
exchange1.setMethod(HttpMethods.GET); ContentResponse response = future.get();
exchange1.setURL(url + "?action=init"); assertEquals(HttpServletResponse.SC_OK,response.getStatus());
client.send(exchange1); String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -102,14 +97,12 @@ public abstract class AbstractSessionExpiryTest
port1 = server1.getPort(); port1 = server1.getPort();
url = "http://localhost:" + port1 + contextPath + servletMapping; url = "http://localhost:" + port1 + contextPath + servletMapping;
//make another request, the session should not have expired //make another request, the session should not have expired
ContentExchange exchange2 = new ContentExchange(true); Request request = client.newRequest(url + "?action=notexpired");
exchange2.setMethod(HttpMethods.GET); request.getHeaders().add("Cookie", sessionCookie);
exchange2.setURL(url + "?action=notexpired"); future = request.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); ContentResponse response2 = future.get();
client.send(exchange2); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
} }
finally finally
@ -135,18 +128,14 @@ public abstract class AbstractSessionExpiryTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
String url = "http://localhost:" + port1 + contextPath + servletMapping; String url = "http://localhost:" + port1 + contextPath + servletMapping;
//make a request to set up a session on the server //make a request to set up a session on the server
ContentExchange exchange1 = new ContentExchange(true); Future<ContentResponse> future = client.GET(url + "?action=init");
exchange1.setMethod(HttpMethods.GET); ContentResponse response1 = future.get();
exchange1.setURL(url + "?action=init"); assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
client.send(exchange1); String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -163,13 +152,11 @@ public abstract class AbstractSessionExpiryTest
url = "http://localhost:" + port1 + contextPath + servletMapping; url = "http://localhost:" + port1 + contextPath + servletMapping;
//make another request, the session should have expired //make another request, the session should have expired
ContentExchange exchange2 = new ContentExchange(true); Request request = client.newRequest(url + "?action=test");
exchange2.setMethod(HttpMethods.GET); request.getHeaders().add("Cookie", sessionCookie);
exchange2.setURL(url + "?action=test"); future = request.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); ContentResponse response2 = future.get();
client.send(exchange2); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
} }
finally finally
{ {

View File

@ -18,10 +18,13 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -33,16 +36,12 @@ import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.Request; import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* AbstractSessionInvalidateAndCreateTest * AbstractSessionInvalidateAndCreateTest
@ -107,7 +106,6 @@ public abstract class AbstractSessionInvalidateAndCreateTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
@ -115,26 +113,21 @@ public abstract class AbstractSessionInvalidateAndCreateTest
// Create the session // Create the session
ContentExchange exchange1 = new ContentExchange(true); Future<ContentResponse> future = client.GET(url + "?action=init");
exchange1.setMethod(HttpMethods.GET); ContentResponse response1 = future.get();
exchange1.setURL(url + "?action=init"); assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
client.send(exchange1); String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Make a request which will invalidate the existing session and create a new one // Make a request which will invalidate the existing session and create a new one
ContentExchange exchange2 = new ContentExchange(true); Request request2 = client.newRequest(url + "?action=test");
exchange2.setMethod(HttpMethods.GET); request2.header("Cookie", sessionCookie);
exchange2.setURL(url + "?action=test"); future = request2.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); ContentResponse response2 = future.get();
client.send(exchange2); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
// Wait for the scavenger to run, waiting 2.5 times the scavenger period // Wait for the scavenger to run, waiting 2.5 times the scavenger period
pause(scavengePeriod); pause(scavengePeriod);

View File

@ -20,7 +20,8 @@ package org.eclipse.jetty.server.session;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -28,9 +29,12 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpCookie;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -60,33 +64,28 @@ public abstract class AbstractSessionMigrationTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
// Perform one request to server1 to create a session // Perform one request to server1 to create a session
int value = 1; int value = 1;
ContentExchange exchange1 = new ContentExchange(true); Request request1 = client.POST("http://localhost:" + port1 + contextPath + servletMapping + "?action=set&value=" + value);
exchange1.setMethod(HttpMethods.POST); Future<ContentResponse> future = request1.send();
exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping + "?action=set&value=" + value); ContentResponse response1 = future.get();
client.send(exchange1); assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
exchange1.waitForDone(); String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertEquals(HttpServletResponse.SC_OK,exchange1.getResponseStatus());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Perform a request to server2 using the session cookie from the previous request // Perform a request to server2 using the session cookie from the previous request
// This should migrate the session from server1 to server2. // This should migrate the session from server1 to server2.
ContentExchange exchange2 = new ContentExchange(true); Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=get");
exchange2.setMethod(HttpMethods.GET); request2.header("Cookie", sessionCookie);
exchange2.setURL("http://localhost:" + port2 + contextPath + servletMapping + "?action=get"); future = request2.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); ContentResponse response2 = future.get();
client.send(exchange2); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
exchange2.waitForDone(); String response = response2.getContentAsString();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus());
String response = exchange2.getResponseContent();
assertEquals(response.trim(),String.valueOf(value)); } assertEquals(response.trim(),String.valueOf(value)); }
finally finally
{ {

View File

@ -0,0 +1,134 @@
//
// ========================================================================
// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.session;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletContextHandler;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public abstract class AbstractSessionRenewTest
{
public abstract AbstractTestServer createServer(int port, int max, int scavenge);
public void testSessionRenewal() throws Exception
{
String contextPath = "";
String servletMapping = "/server";
int scavengePeriod = 3;
AbstractTestServer server = createServer(0, 1, scavengePeriod);
ServletContextHandler context = server.addContext(contextPath);
context.addServlet(TestServlet.class, servletMapping);
server.start();
int port=server.getPort();
HttpClient client = new HttpClient();
try
{
client.start();
//make a request to create a session
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
ContentResponse response = future.get();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
//make a request to change the sessionid
Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=renew");
request.header("Cookie", sessionCookie);
future = request.send();
ContentResponse renewResponse = future.get();
assertEquals(HttpServletResponse.SC_OK,renewResponse.getStatus());
String renewSessionCookie = renewResponse.getHeaders().getStringField("Set-Cookie");
assertNotNull(renewSessionCookie);
assertNotSame(sessionCookie, renewSessionCookie);
}
finally
{
client.stop();
}
}
public static class TestServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String action = request.getParameter("action");
if ("create".equals(action))
{
HttpSession session = request.getSession(true);
assertTrue(session.isNew());
}
else if ("renew".equals(action))
{
HttpSession beforeSession = request.getSession(false);
String beforeSessionId = beforeSession.getId();
assertTrue(beforeSession != null);
((AbstractSession)beforeSession).renewId(request);
HttpSession afterSession = request.getSession(false);
String afterSessionId = afterSession.getId();
assertTrue(afterSession != null);
assertTrue(beforeSession==afterSession);
assertTrue(beforeSessionId != afterSessionId);
AbstractSessionManager sessionManager = (AbstractSessionManager)((AbstractSession)afterSession).getSessionManager();
AbstractSessionIdManager sessionIdManager = (AbstractSessionIdManager)sessionManager.getSessionIdManager();
assertTrue(sessionIdManager.idInUse(afterSessionId));
assertFalse(sessionIdManager.idInUse(beforeSessionId));
HttpSession session = sessionManager.getSession(afterSessionId);
assertNotNull(session);
session = sessionManager.getSession(beforeSessionId);
assertNull(session);
if (((AbstractSession)afterSession).isIdChanged())
{
((org.eclipse.jetty.server.Response)response).addCookie(sessionManager.getSessionCookie(afterSession, request.getContextPath(), request.isSecure()));
}
}
}
}
}

View File

@ -18,9 +18,12 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -28,12 +31,10 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
@ -58,26 +59,21 @@ public abstract class AbstractSessionValueSavingTest
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
long sessionTestValue = 0; long sessionTestValue = 0;
// Perform one request to server1 to create a session // Perform one request to server1 to create a session
ContentExchange exchange1 = new ContentExchange(true); Future<ContentResponse> future = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
exchange1.setMethod(HttpMethods.GET); ContentResponse response1 = future.get();
exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
client.send(exchange1);
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus());
System.out.println("Checking: " + sessionTestValue + " vs " + exchange1.getResponseContent()); assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
assertTrue(sessionTestValue < Long.parseLong(exchange1.getResponseContent())); assertTrue(sessionTestValue < Long.parseLong(response1.getContentAsString()));
sessionTestValue = Long.parseLong(exchange1.getResponseContent()); sessionTestValue = Long.parseLong(response1.getContentAsString());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie"); String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue( sessionCookie != null ); assertTrue( sessionCookie != null );
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -92,20 +88,16 @@ public abstract class AbstractSessionValueSavingTest
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
{ {
ContentExchange exchange2 = new ContentExchange(true); Request request2 = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping);
exchange2.setMethod(HttpMethods.GET); request2.header("Cookie", sessionCookie);
exchange2.setURL("http://localhost:" + port1 + contextPath + servletMapping); future = request2.send();
exchange2.getRequestFields().add("Cookie", sessionCookie); ContentResponse response2 = future.get();
client.send(exchange2);
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK , exchange2.getResponseStatus());
System.out.println("Checking: " + sessionTestValue + " vs " + exchange2.getResponseContent()); assertEquals(HttpServletResponse.SC_OK , response2.getStatus());
assertTrue(sessionTestValue < Long.parseLong(exchange2.getResponseContent())); assertTrue(sessionTestValue < Long.parseLong(response2.getContentAsString()));
sessionTestValue = Long.parseLong(response2.getContentAsString());
sessionTestValue = Long.parseLong(exchange2.getResponseContent()); String setCookie = response1.getHeaders().getStringField("Set-Cookie");
String setCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
if (setCookie!=null) if (setCookie!=null)
sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.SessionIdManager; import org.eclipse.jetty.server.SessionIdManager;
import org.eclipse.jetty.server.SessionManager; import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.ContextHandlerCollection;
@ -77,7 +78,7 @@ public abstract class AbstractTestServer
public int getPort() public int getPort()
{ {
return _server.getConnectors()[0].getLocalPort(); return ((NetworkConnector)getServer().getConnectors()[0]).getLocalPort();
} }
public ServletContextHandler addContext(String contextPath) public ServletContextHandler addContext(String contextPath)

View File

@ -18,22 +18,24 @@
package org.eclipse.jetty.server.session; package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileWriter; import java.io.FileWriter;
import java.util.Random; import java.util.concurrent.Future;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpMethods; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.resource.Resource;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* AbstractWebAppObjectInSessionTest * AbstractWebAppObjectInSessionTest
* *
@ -106,31 +108,29 @@ public abstract class AbstractWebAppObjectInSessionTest
try try
{ {
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start(); client.start();
try try
{ {
// Perform one request to server1 to create a session // Perform one request to server1 to create a session
ContentExchange exchange1 = new ContentExchange(true); Request request = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping + "?action=set");
exchange1.setMethod(HttpMethods.GET); request.method(HttpMethod.GET);
exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping + "?action=set");
client.send(exchange1); Future<ContentResponse> future = request.send();
exchange1.waitForDone(); ContentResponse response = future.get();
assertEquals( HttpServletResponse.SC_OK, exchange1.getResponseStatus()); assertEquals( HttpServletResponse.SC_OK, response.getStatus());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie"); String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null); assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc. // Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Perform a request to server2 using the session cookie from the previous request // Perform a request to server2 using the session cookie from the previous request
ContentExchange exchange2 = new ContentExchange(true); Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=get");
exchange2.setMethod(HttpMethods.GET); request2.method(HttpMethod.GET);
exchange2.setURL("http://localhost:" + port2 + contextPath + servletMapping + "?action=get"); request2.header("Cookie", sessionCookie);
exchange2.getRequestFields().add("Cookie", sessionCookie); future = request2.send();
client.send(exchange2); ContentResponse response2 = future.get();
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange2.getResponseStatus()); assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
} }
finally finally
{ {