Search in sources :

Example 1 with SessionData

use of org.eclipse.jetty.server.session.SessionData in project jetty.project by eclipse.

the class MongoSessionDataStore method load.

/** 
     * @see org.eclipse.jetty.server.session.SessionDataStore#load(String)
     */
@Override
public SessionData load(String id) throws Exception {
    final AtomicReference<SessionData> reference = new AtomicReference<SessionData>();
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();
    Runnable r = new Runnable() {

        public void run() {
            try {
                DBObject sessionDocument = _dbSessions.findOne(new BasicDBObject(__ID, id));
                if (LOG.isDebugEnabled())
                    LOG.debug("id={} loaded={}", id, sessionDocument);
                if (sessionDocument == null)
                    return;
                Boolean valid = (Boolean) sessionDocument.get(__VALID);
                if (LOG.isDebugEnabled())
                    LOG.debug("id={} valid={}", id, valid);
                if (valid == null || !valid)
                    return;
                Object version = getNestedValue(sessionDocument, getContextSubfield(__VERSION));
                Long lastSaved = (Long) getNestedValue(sessionDocument, getContextSubfield(__LASTSAVED));
                String lastNode = (String) getNestedValue(sessionDocument, getContextSubfield(__LASTNODE));
                Long created = (Long) sessionDocument.get(__CREATED);
                Long accessed = (Long) sessionDocument.get(__ACCESSED);
                Long maxInactive = (Long) sessionDocument.get(__MAX_IDLE);
                Long expiry = (Long) sessionDocument.get(__EXPIRY);
                NoSqlSessionData data = null;
                // get the session for the context
                DBObject sessionSubDocumentForContext = (DBObject) getNestedValue(sessionDocument, getContextField());
                if (LOG.isDebugEnabled())
                    LOG.debug("attrs {}", sessionSubDocumentForContext);
                if (sessionSubDocumentForContext != null) {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Session {} present for context {}", id, _context);
                    //only load a session if it exists for this context
                    data = (NoSqlSessionData) newSessionData(id, created, accessed, accessed, maxInactive);
                    data.setVersion(version);
                    data.setExpiry(expiry);
                    data.setContextPath(_context.getCanonicalContextPath());
                    data.setVhost(_context.getVhost());
                    data.setLastSaved(lastSaved);
                    data.setLastNode(lastNode);
                    HashMap<String, Object> attributes = new HashMap<>();
                    for (String name : sessionSubDocumentForContext.keySet()) {
                        //skip special metadata attribute which is not one of the actual session attributes
                        if (__METADATA.equals(name))
                            continue;
                        String attr = decodeName(name);
                        Object value = decodeValue(sessionSubDocumentForContext.get(name));
                        attributes.put(attr, value);
                    }
                    data.putAllAttributes(attributes);
                } else {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Session  {} not present for context {}", id, _context);
                }
                reference.set(data);
            } catch (Exception e) {
                exception.set(e);
            }
        }
    };
    _context.run(r);
    if (exception.get() != null)
        throw exception.get();
    return reference.get();
}
Also used : HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) SessionData(org.eclipse.jetty.server.session.SessionData) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) MongoException(com.mongodb.MongoException) IOException(java.io.IOException) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject)

Example 2 with SessionData

use of org.eclipse.jetty.server.session.SessionData in project jetty.project by eclipse.

the class InfinispanSessionDataStore method exists.

/** 
     * @see org.eclipse.jetty.server.session.SessionDataStore#exists(java.lang.String)
     */
@Override
public boolean exists(String id) throws Exception {
    // TODO find a better way to do this that does not pull into memory the
    // whole session object
    final AtomicReference<Boolean> reference = new AtomicReference<Boolean>();
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();
    Runnable load = new Runnable() {

        public void run() {
            try {
                SessionData sd = load(id);
                if (sd == null) {
                    reference.set(Boolean.FALSE);
                    return;
                }
                if (sd.getExpiry() <= 0)
                    //never expires
                    reference.set(Boolean.TRUE);
                else
                    //not expired yet
                    reference.set(Boolean.valueOf(sd.getExpiry() > System.currentTimeMillis()));
            } catch (Exception e) {
                exception.set(e);
            }
        }
    };
    //ensure the load runs in the context classloader scope
    _context.run(load);
    if (exception.get() != null)
        throw exception.get();
    return reference.get();
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) SessionData(org.eclipse.jetty.server.session.SessionData)

Example 3 with SessionData

use of org.eclipse.jetty.server.session.SessionData in project jetty.project by eclipse.

the class InfinispanSessionDataStore method doGetExpired.

/** 
     * @see org.eclipse.jetty.server.session.SessionDataStore#getExpired(Set)
     */
@Override
public Set<String> doGetExpired(Set<String> candidates) {
    if (candidates == null || candidates.isEmpty())
        return candidates;
    long now = System.currentTimeMillis();
    Set<String> expired = new HashSet<String>();
    for (String candidate : candidates) {
        if (LOG.isDebugEnabled())
            LOG.debug("Checking expiry for candidate {}", candidate);
        try {
            SessionData sd = load(candidate);
            //if the session no longer exists
            if (sd == null) {
                expired.add(candidate);
                if (LOG.isDebugEnabled())
                    LOG.debug("Session {} does not exist in infinispan", candidate);
            } else {
                if (_context.getWorkerName().equals(sd.getLastNode())) {
                    //we are its manager, add it to the expired set if it is expired now
                    if ((sd.getExpiry() > 0) && sd.getExpiry() <= now) {
                        expired.add(candidate);
                        if (LOG.isDebugEnabled())
                            LOG.debug("Session {} managed by {} is expired", candidate, _context.getWorkerName());
                    }
                } else {
                    //the session expired at least one graceperiod ago
                    if (_lastExpiryCheckTime <= 0) {
                        if ((sd.getExpiry() > 0) && sd.getExpiry() < (now - (1000L * (3 * _gracePeriodSec))))
                            expired.add(candidate);
                    } else {
                        if ((sd.getExpiry() > 0) && sd.getExpiry() < (now - (1000L * _gracePeriodSec)))
                            expired.add(candidate);
                    }
                }
            }
        } catch (Exception e) {
            LOG.warn("Error checking if candidate {} is expired", candidate, e);
        }
    }
    return expired;
}
Also used : SessionData(org.eclipse.jetty.server.session.SessionData) HashSet(java.util.HashSet)

Example 4 with SessionData

use of org.eclipse.jetty.server.session.SessionData in project jetty.project by eclipse.

the class InfinispanSessionDataStore method load.

/** 
     * @see org.eclipse.jetty.server.session.SessionDataStore#load(String)
     */
@Override
public SessionData load(String id) throws Exception {
    final AtomicReference<SessionData> reference = new AtomicReference<SessionData>();
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();
    Runnable load = new Runnable() {

        public void run() {
            try {
                if (LOG.isDebugEnabled())
                    LOG.debug("Loading session {} from infinispan", id);
                SessionData sd = (SessionData) _cache.get(getCacheKey(id));
                reference.set(sd);
            } catch (Exception e) {
                exception.set(e);
            }
        }
    };
    //ensure the load runs in the context classloader scope
    _context.run(load);
    if (exception.get() != null)
        throw exception.get();
    return reference.get();
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) SessionData(org.eclipse.jetty.server.session.SessionData)

Example 5 with SessionData

use of org.eclipse.jetty.server.session.SessionData in project jetty.project by eclipse.

the class CachingSessionDataStoreTest method testSessionCRUD.

@Test
public void testSessionCRUD() throws Exception {
    String servletMapping = "/server";
    int scavengePeriod = -1;
    int maxInactivePeriod = -1;
    DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory();
    SessionDataStoreFactory storeFactory = MemcachedTestHelper.newSessionDataStoreFactory();
    //Make sure sessions are evicted on request exit so they will need to be reloaded via cache/persistent store
    TestServer server = new TestServer(0, maxInactivePeriod, scavengePeriod, cacheFactory, storeFactory);
    ServletContextHandler context = server.addContext("/");
    context.addServlet(TestServlet.class, servletMapping);
    String contextPath = "";
    try {
        server.start();
        int port = server.getPort();
        HttpClient client = new HttpClient();
        client.start();
        try {
            //
            //Create a session
            //
            ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            String sessionCookie = response.getHeaders().get("Set-Cookie");
            assertTrue(sessionCookie != null);
            // Mangle the cookie, replacing Path with $Path, etc.
            sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
            String id = TestServer.extractSessionId(sessionCookie);
            //check that the memcache contains the session, and the session data store contains the session
            CachingSessionDataStore ds = (CachingSessionDataStore) context.getSessionHandler().getSessionCache().getSessionDataStore();
            assertNotNull(ds);
            SessionDataStore persistentStore = ds.getSessionStore();
            SessionDataMap dataMap = ds.getSessionDataMap();
            //the backing persistent store contains the session
            assertNotNull(persistentStore.load(id));
            //the memcache cache contains the session
            assertNotNull(dataMap.load(id));
            //
            //Update a session and check that is is NOT loaded via the persistent store
            //
            ((MockDataStore) persistentStore).zeroLoadCount();
            Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=update");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            assertEquals(0, ((MockDataStore) persistentStore).getLoadCount());
            //check it was updated in the persistent store
            SessionData sd = persistentStore.load(id);
            assertNotNull(sd);
            assertEquals("bar", sd.getAttribute("foo"));
            //check it was updated in the cache
            sd = dataMap.load(id);
            assertNotNull(sd);
            assertEquals("bar", sd.getAttribute("foo"));
        } finally {
            client.stop();
        }
    } finally {
        server.stop();
    }
}
Also used : DefaultSessionCacheFactory(org.eclipse.jetty.server.session.DefaultSessionCacheFactory) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) CachingSessionDataStore(org.eclipse.jetty.server.session.CachingSessionDataStore) SessionDataStoreFactory(org.eclipse.jetty.server.session.SessionDataStoreFactory) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) SessionData(org.eclipse.jetty.server.session.SessionData) TestServer(org.eclipse.jetty.server.session.TestServer) CachingSessionDataStore(org.eclipse.jetty.server.session.CachingSessionDataStore) SessionDataStore(org.eclipse.jetty.server.session.SessionDataStore) SessionDataMap(org.eclipse.jetty.server.session.SessionDataMap) HttpClient(org.eclipse.jetty.client.HttpClient) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) MockDataStore(org.eclipse.jetty.memcached.sessions.MemcachedTestHelper.MockDataStore) Test(org.junit.Test)

Aggregations

SessionData (org.eclipse.jetty.server.session.SessionData)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Blob (com.google.cloud.datastore.Blob)1 DatastoreException (com.google.cloud.datastore.DatastoreException)1 BasicDBObject (com.mongodb.BasicDBObject)1 DBObject (com.mongodb.DBObject)1 MongoException (com.mongodb.MongoException)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpClient (org.eclipse.jetty.client.HttpClient)1 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)1 Request (org.eclipse.jetty.client.api.Request)1 MockDataStore (org.eclipse.jetty.memcached.sessions.MemcachedTestHelper.MockDataStore)1 CachingSessionDataStore (org.eclipse.jetty.server.session.CachingSessionDataStore)1 DefaultSessionCacheFactory (org.eclipse.jetty.server.session.DefaultSessionCacheFactory)1 SessionDataMap (org.eclipse.jetty.server.session.SessionDataMap)1 SessionDataStore (org.eclipse.jetty.server.session.SessionDataStore)1 SessionDataStoreFactory (org.eclipse.jetty.server.session.SessionDataStoreFactory)1