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

@ -180,4 +180,18 @@ public class NoSqlSession extends AbstractSession
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;
}
/* ------------------------------------------------------------ */
@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);
@ -319,4 +347,7 @@ public abstract class NoSqlSessionManager extends AbstractSessionManager impleme
/* ------------------------------------------------------------ */
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.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
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_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;
protected Server _server;
@ -79,8 +83,8 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
private long _scavengeDelay = 30 * 60 * 1000; // every 30 minutes
private long _scavengePeriod = 10 * 6 * 1000; // wait at least 10 minutes
private long _scavengeDelay = __defaultScavengeDelay;
private long _scavengePeriod = __defaultScavengePeriod;
/**
@ -145,8 +149,8 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
*/
protected void scavenge()
{
__log.debug("SessionIdManager:scavenge:called with delay" + _scavengeDelay);
long now = System.currentTimeMillis();
__log.debug("SessionIdManager:scavenge:at " + now);
synchronized (_sessionsIds)
{
/*
@ -158,7 +162,8 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
*/
BasicDBObject query = new BasicDBObject();
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));
@ -301,14 +306,20 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
*/
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)
{
this._scavengePeriod = scavengePeriod;
if (scavengePeriod <= 0)
_scavengePeriod = __defaultScavengePeriod;
else
_scavengePeriod = TimeUnit.SECONDS.toMillis(scavengePeriod);
}
/* ------------------------------------------------------------ */
@ -540,4 +551,35 @@ public class MongoSessionIdManager extends AbstractSessionIdManager
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.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteResult;
@ManagedObject("Mongo Session Manager")
@ -88,8 +89,9 @@ public class MongoSessionManager extends NoSqlSessionManager
{
super.doStart();
String[] hosts = getContextHandler().getVirtualHosts();
if (hosts == null || hosts.length == 0)
hosts = getContextHandler().getConnectorNames();
//TODO: can this be replaced?
/*if (hosts == null || hosts.length == 0)
hosts = getContextHandler().getConnectorNames();*/
if (hosts == null || hosts.length == 0)
hosts = new String[]
{ "::" }; // 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)
{
@ -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.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
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.Context;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.session.AbstractSessionManager;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.server.session.AbstractSession;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -329,7 +328,7 @@ public abstract class SecurityHandler extends HandlerWrapper implements Authenti
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.IdentityService;
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.session.AbstractSessionManager;
import org.eclipse.jetty.server.session.AbstractSession;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -51,7 +52,7 @@ public abstract class LoginAuthenticator implements Authenticator
UserIdentity user = _loginService.login(username,password);
if (user!=null)
{
renewSession((HttpServletRequest)request, null);
renewSession((HttpServletRequest)request, (request instanceof Request? ((Request)request).getResponse() : null));
return user;
}
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
//(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);
LOG.debug("renew {}->{}",httpSession.getId(),newSession.getId());
httpSession=newSession;
if (httpSession instanceof AbstractSession)
{
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.UserIdentity;
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.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -107,7 +108,7 @@ public class SessionAuthentication implements Authentication.User, Serializable,
if (security!=null)
security.logout(this);
if (_session!=null)
_session.removeAttribute(AbstractSessionManager.SESSION_KNOWN_ONLY_TO_AUTHENTICATED);
_session.removeAttribute(AbstractSession.SESSION_KNOWN_ONLY_TO_AUTHENTICATED);
}
@Override

View File

@ -68,6 +68,7 @@ import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.handler.ContextHandler;
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.util.Attributes;
import org.eclipse.jetty.util.AttributesMap;
@ -1207,7 +1208,15 @@ public class Request implements HttpServletRequest
if (session == null)
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();
}

View File

@ -59,6 +59,8 @@ public interface SessionIdManager extends LifeCycle
*/
public String newSessionId(HttpServletRequest request,long created);
public String getWorkerName();
@ -78,4 +80,15 @@ public interface SessionIdManager extends LifeCycle
*/
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.
*/
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.HttpSessionEvent;
import org.eclipse.jetty.server.SessionManager;
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
{
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 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 boolean _idChanged;
private final long _created;
@ -272,6 +273,33 @@ public abstract class AbstractSession implements AbstractSessionManager.SessionI
}
}
/* ------------------------------------------------------------ */
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)
{

View File

@ -117,32 +117,46 @@ public abstract class AbstractSessionIdManager extends AbstractLifeCycle impleme
}
// 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()^(((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;
}
String id = newSessionId(request.hashCode());
request.setAttribute(__NEW_SESSION_ID,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
protected void doStart() throws Exception

View File

@ -75,7 +75,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
new HashSet<SessionTrackingMode>(
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;
@ -130,27 +130,6 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
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()
{

View File

@ -219,4 +219,39 @@ public class HashSessionIdManager extends AbstractSessionIdManager
}
}
/* ------------------------------------------------------------ */
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
{
final static Logger __log = SessionHandler.LOG;
final static Logger LOG = SessionHandler.LOG;
protected final ConcurrentMap<String,HashedSession> _sessions=new ConcurrentHashMap<String,HashedSession>();
private static int __id;
@ -152,10 +152,10 @@ public class HashSessionManager extends AbstractSessionManager
public int getSessions()
{
int sessions=super.getSessions();
if (__log.isDebugEnabled())
if (LOG.isDebugEnabled())
{
if (_sessions.size()!=sessions)
__log.warn("sessions: "+_sessions.size()+"!="+sessions);
LOG.warn("sessions: "+_sessions.size()+"!="+sessions);
}
return sessions;
}
@ -225,7 +225,7 @@ public class HashSessionManager extends AbstractSessionManager
}
catch (Exception e)
{
__log.warn(e);
LOG.warn(e);
}
}
};
@ -320,7 +320,7 @@ public class HashSessionManager extends AbstractSessionManager
}
catch (Throwable t)
{
__log.warn("Problem scavenging sessions", t);
LOG.warn("Problem scavenging sessions", t);
}
finally
{
@ -348,7 +348,7 @@ public class HashSessionManager extends AbstractSessionManager
}
catch(Exception e)
{
__log.warn(e);
LOG.warn(e);
}
}
@ -399,6 +399,37 @@ public class HashSessionManager extends AbstractSessionManager
}
}
/* ------------------------------------------------------------ */
/**
* @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
protected AbstractSession newSession(HttpServletRequest request)
@ -467,7 +498,7 @@ public class HashSessionManager extends AbstractSessionManager
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;
}
@ -503,11 +534,11 @@ public class HashSessionManager extends AbstractSessionManager
if (file.exists())
{
file.delete();
__log.warn("Deleting file for unrestorable session "+idInCuster, e);
LOG.warn("Deleting file for unrestorable session "+idInCuster, e);
}
}
else
__log.warn("Problem restoring session "+idInCuster, e);
LOG.warn("Problem restoring session "+idInCuster, e);
}
return null;
@ -523,12 +554,12 @@ public class HashSessionManager extends AbstractSessionManager
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;
}
for (HashedSession session : _sessions.values())
session.save(true);
session.save(reactivate);
}
/* ------------------------------------------------------------ */

View File

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

View File

@ -387,6 +387,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)
{
if (session == null)
@ -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.
*
@ -655,7 +706,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
" where "+_sessionTableRowId+" = ?";
_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+
" set lastNode = ? where "+_sessionTableRowId+" = ?";

View File

@ -84,7 +84,7 @@ public class JDBCSessionManager extends AbstractSessionManager
*/
public class SessionData
{
private final String _id;
private String _id;
private String _rowId;
private long _accessed;
private long _lastAccessed;
@ -121,6 +121,11 @@ public class JDBCSessionManager extends AbstractSessionManager
return _id;
}
public synchronized void setId (String id)
{
_id = id;
}
public synchronized long getCreated ()
{
return _created;
@ -311,8 +316,38 @@ public class JDBCSessionManager extends AbstractSessionManager
_dirty=true;
}
@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());
}
@ -639,6 +674,35 @@ public class JDBCSessionManager extends AbstractSessionManager
}
/**
*
* @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.
*
@ -971,11 +1035,12 @@ public class JDBCSessionManager extends AbstractSessionManager
long now = System.currentTimeMillis();
connection.setAutoCommit(true);
statement = connection.prepareStatement(_jdbcSessionIdMgr._updateSession);
statement.setString(1, getSessionIdManager().getWorkerName());//my node id
statement.setLong(2, data.getAccessed());//accessTime
statement.setLong(3, data.getLastAccessed()); //lastAccessTime
statement.setLong(4, now); //last saved time
statement.setLong(5, data.getExpiryTime());
statement.setString(1, data.getId());
statement.setString(2, getSessionIdManager().getWorkerName());//my node id
statement.setLong(3, data.getAccessed());//accessTime
statement.setLong(4, data.getLastAccessed()); //lastAccessTime
statement.setLong(5, now); //last saved time
statement.setLong(6, data.getExpiryTime());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
@ -983,8 +1048,8 @@ public class JDBCSessionManager extends AbstractSessionManager
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
statement.setBinaryStream(6, bais, bytes.length);//attribute map as blob
statement.setString(7, data.getRowId()); //rowId
statement.setBinaryStream(7, bais, bytes.length);//attribute map as blob
statement.setString(8, data.getRowId()); //rowId
statement.executeUpdate();
data.setLastSaved(now);

View File

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

View File

@ -410,6 +410,8 @@
<module>examples/embedded</module>
<module>examples/async-rest</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
<module>tests</module>
@ -421,7 +423,6 @@
<module>jetty-monitor</module>
<module>jetty-nested</module>
<module>jetty-overlay-deployer</module>
<module>jetty-nosql</module>
<module>jetty-http-spi</module>
<module>test-jetty-nested</module>
-->

View File

@ -32,6 +32,7 @@
<module>test-sessions-common</module>
<module>test-hash-sessions</module>
<module>test-jdbc-sessions</module>
<module>test-mongodb-sessions</module>
<!-- Requires mongodb server running -->
<!-- module>test-mongodb-sessions</module -->
</modules>
</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;
import org.eclipse.jetty.util.log.Log;
import org.junit.Test;
/**

View File

@ -25,17 +25,17 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.Future;
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.ContentExchange;
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.util.log.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -73,7 +73,6 @@ public class MaxInactiveMigrationTest
testServer1.start();
testServer2.start();
client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start();
}
@ -99,22 +98,19 @@ public class MaxInactiveMigrationTest
int port=server.getPort();
//Log.getLog().setDebugEnabled(true);
ContentExchange exchange1 = new ContentExchange(true);
exchange1.setMethod(HttpMethods.GET);
exchange1.setURL("http://localhost:" + port + "" + "/test");
Request request = client.newRequest("http://localhost:" + port + "" + "/test");
if (sessionCookie != null)
exchange1.getRequestFields().add("Cookie", sessionCookie);
client.send(exchange1);
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus());
request.header("Cookie", sessionCookie);
Future<ContentResponse> future = request.send();
ContentResponse response = future.get();
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue( sessionCookie != null );
// Mangle the cookie, replacing Path with $Path, etc.
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;
import org.eclipse.jetty.util.log.Log;
import org.junit.Test;
/**
@ -31,7 +30,7 @@ public class SessionValueSavingTest extends AbstractSessionValueSavingTest
return new JdbcTestServer(port,max,scavenge);
}
@Override
@Test
public void testSessionValueSaving() throws Exception
{
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.AbstractTestServer;
import org.junit.Ignore;
import org.junit.Test;
public class LastAccessTimeTest extends AbstractLastAccessTimeTest

View File

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

View File

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

View File

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

View File

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

View File

@ -18,26 +18,36 @@
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.PrintWriter;
import java.util.Random;
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 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.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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* 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
{
@ -48,10 +58,15 @@ public abstract class AbstractLastAccessTimeTest
{
String contextPath = "";
String servletMapping = "/server";
int maxInactivePeriod = 8;
int scavengePeriod = 2;
int maxInactivePeriod = 8; //session will timeout after 8 seconds
int scavengePeriod = 2; //scavenging occurs every 2 seconds
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();
int port1=server1.getPort();
try
@ -63,19 +78,15 @@ public abstract class AbstractLastAccessTimeTest
try
{
HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start();
try
{
// Perform one request to server1 to create a session
ContentExchange exchange1 = new ContentExchange(true);
exchange1.setMethod(HttpMethods.GET);
exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
client.send(exchange1);
exchange1.waitForDone();
assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus());
assertEquals("test", exchange1.getResponseContent());
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
Future<ContentResponse> future = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
ContentResponse response1 = future.get();
assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
assertEquals("test", response1.getContentAsString());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue( sessionCookie != null );
// Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -88,16 +99,14 @@ public abstract class AbstractLastAccessTimeTest
int requestInterval = 500;
for (int i = 0; i < maxInactivePeriod * (1000 / requestInterval); ++i)
{
ContentExchange exchange2 = new ContentExchange(true);
exchange2.setMethod(HttpMethods.GET);
exchange2.setURL("http://localhost:" + port2 + contextPath + servletMapping);
exchange2.getRequestFields().add("Cookie", sessionCookie);
client.send(exchange2);
exchange2.waitForDone();
assertEquals(HttpServletResponse.SC_OK , exchange2.getResponseStatus());
assertEquals("test", exchange2.getResponseContent());
Request request = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping);
request.header("Cookie", sessionCookie);
future = request.send();
ContentResponse response2 = future.get();
assertEquals(HttpServletResponse.SC_OK , response2.getStatus());
assertEquals("test", response2.getContentAsString());
String setCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
String setCookie = response2.getHeaders().getStringField("Set-Cookie");
if (setCookie!=null)
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
Thread.sleep(scavengePeriod * 2500L);
// Access again server1, and ensure that we can still access the session
exchange1 = new ContentExchange(true);
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());
//check that the session was not scavenged over on server1 by ensuring that the SessionListener destroy method wasn't called
assertTrue (listener1.destroyed == false);
}
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
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
@ -146,7 +168,6 @@ public abstract class AbstractLastAccessTimeTest
{
HttpSession session = request.getSession(true);
session.setAttribute("test", "test");
sendResult(session, httpServletResponse.getWriter());
}
@ -161,8 +182,6 @@ public abstract class AbstractLastAccessTimeTest
{
session.setAttribute("test", "test");
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,23 +18,27 @@
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.util.EventListener;
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 javax.servlet.http.HttpSessionActivationListener;
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.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.junit.Test;
@ -59,17 +63,13 @@ public abstract class AbstractRemoveSessionTest
try
{
HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start();
try
{
ContentExchange exchange = new ContentExchange(true);
exchange.setMethod(HttpMethods.GET);
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=create");
client.send(exchange);
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
String sessionCookie = exchange.getResponseFields().getStringField("Set-Cookie");
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);
// Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
@ -77,26 +77,22 @@ public abstract class AbstractRemoveSessionTest
assertTrue (testListener.isCreated());
//now delete the session
exchange = new ContentExchange(true);
exchange.setMethod(HttpMethods.GET);
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=delete");
exchange.getRequestFields().add("Cookie", sessionCookie);
client.send(exchange);
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=delete");
request.header("Cookie", sessionCookie);
future = request.send();
response = future.get();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
//ensure sessionDestroyed listener is called
assertTrue(testListener.isDestroyed());
// 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
exchange = new ContentExchange(true);
exchange.setMethod(HttpMethods.GET);
exchange.setURL("http://localhost:" + port + contextPath + servletMapping + "?action=check");
exchange.getRequestFields().add("Cookie", sessionCookie);
client.send(exchange);
exchange.waitForDone();
assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=check");
request.header("Cookie", sessionCookie);
future = request.send();
response = future.get();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
finally
{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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