Example usage for org.apache.shiro.session.mgt SimpleSession setLastAccessTime

List of usage examples for org.apache.shiro.session.mgt SimpleSession setLastAccessTime

Introduction

In this page you can find the example usage for org.apache.shiro.session.mgt SimpleSession setLastAccessTime.

Prototype

public void setLastAccessTime(Date lastAccessTime) 

Source Link

Usage

From source file:com.funtl.framework.apache.shiro.session.JedisSessionDAO.java

License:Apache License

/**
 * ??// w w w . ja va2 s  .co m
 *
 * @param includeLeave  ??3?
 * @param principal     ???
 * @param filterSession ????
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
    Set<Session> sessions = Sets.newHashSet();

    Jedis jedis = null;
    try {
        jedis = JedisUtils.getResource();
        Map<String, String> map = jedis.hgetAll(sessionKeyPrefix);
        for (Map.Entry<String, String> e : map.entrySet()) {
            if (StringUtils.isNotBlank(e.getKey()) && StringUtils.isNotBlank(e.getValue())) {

                String[] ss = StringUtils.split(e.getValue(), "|");
                if (ss != null && ss.length == 3) {// jedis.exists(sessionKeyPrefix + e.getKey())){
                    // Session session = (Session)JedisUtils.toObject(jedis.get(JedisUtils.getBytesKey(sessionKeyPrefix + e.getKey())));
                    SimpleSession session = new SimpleSession();
                    session.setId(e.getKey());
                    session.setAttribute("principalId", ss[0]);
                    session.setTimeout(Long.valueOf(ss[1]));
                    session.setLastAccessTime(new Date(Long.valueOf(ss[2])));
                    try {
                        // ?SESSION
                        session.validate();

                        boolean isActiveSession = false;
                        // ????3?
                        if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3) {
                            isActiveSession = true;
                        }
                        // ??
                        if (principal != null) {
                            PrincipalCollection pc = (PrincipalCollection) session
                                    .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                            if (principal.toString().equals(
                                    pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)) {
                                isActiveSession = true;
                            }
                        }
                        // SESSION
                        if (filterSession != null && filterSession.getId().equals(session.getId())) {
                            isActiveSession = false;
                        }
                        if (isActiveSession) {
                            sessions.add(session);
                        }

                    }
                    // SESSION?
                    catch (Exception e2) {
                        jedis.hdel(sessionKeyPrefix, e.getKey());
                    }
                }
                // SESSION??
                else {
                    jedis.hdel(sessionKeyPrefix, e.getKey());
                }
            }
            // SESSIONValue
            else if (StringUtils.isNotBlank(e.getKey())) {
                jedis.hdel(sessionKeyPrefix, e.getKey());
            }
        }
        logger.info("getActiveSessions size: {} ", sessions.size());
    } catch (Exception e) {
        logger.error("getActiveSessions", e);
    } finally {
        JedisUtils.returnResource(jedis);
    }
    return sessions;
}

From source file:com.ikanow.aleph2.security.db.SessionDb.java

License:Apache License

protected Object deserialize(JsonNode sessionOb) {
    SimpleSession s = null;
    try {/*w ww .  j av  a  2 s  . c  o m*/
        if (sessionOb != null) {
            s = new SimpleSession();
            s.setId(sessionOb.get("_id").asText());
            s.setLastAccessTime(new Date(sessionOb.get("last_access_time").asLong()));
            s.setStartTimestamp(new Date(sessionOb.get("start_time_stamp").asLong()));
            s.setTimeout(sessionOb.get("timeout").asLong());
            s.setHost(sessionOb.get("host").asText());
            JsonNode attributesOb = sessionOb.get("attributes");
            for (Iterator<Entry<String, JsonNode>> it = attributesOb.fields(); it.hasNext();) {
                Entry<String, JsonNode> e = it.next();
                s.setAttribute(deescapeMongoCharacters(e.getKey()),
                        SerializableUtils.deserialize(e.getValue().asText()));
            }
        }
    } catch (Exception e) {
        logger.error("Caught Exception deserializing :" + sessionOb, e);
    }
    return s;
}

From source file:com.parallax.server.blocklyprop.security.BlocklyPropSessionDao.java

/**
 * Concert a SessionRecord object to a Session object
 *
 * @param sessionRecord/* w  w w.  j  a v  a2 s .c  o m*/
 * the SessionRecord object to convert
 *
 * @return
 * a Session object. The session object attributes may be missing if the original
 * SessionRecord object contained non-string data.
 */
private Session convert(SessionRecord sessionRecord) {
    LOG.trace("Converting SessionRecord {} into a SimpleSession object", sessionRecord.getIdsession());

    SimpleSession ssession = new SimpleSession();
    ssession.setId(sessionRecord.getIdsession());
    ssession.setStartTimestamp(sessionRecord.getStarttimestamp());
    ssession.setLastAccessTime(sessionRecord.getLastaccesstime());
    ssession.setTimeout(sessionRecord.getTimeout());
    ssession.setHost(sessionRecord.getHost());

    // Gather the session attributes into a HashMap that can be persisted into the
    // Session object
    if (sessionRecord.getAttributes() != null) {
        // In case there is something in the session attributes that isn't a string value
        // We can trap the issue here and deal with it. The @SuppressWarnings tells the IDE
        // that we have thought about this and taken appropriate defensive measures.
        try {
            @SuppressWarnings("unchecked")
            HashMap<Object, Object> attributes = (HashMap<Object, Object>) SerializationUtils
                    .deserialize(sessionRecord.getAttributes());
            ssession.setAttributes(attributes);
        } catch (ClassCastException ex) {
            LOG.warn("Unable to convert SessionRecord attributes in session {}", sessionRecord.getIdsession());
        }
    }

    return ssession;
}

From source file:net.eggcanfly.spring.shiro.support.RedisSessionDao.java

License:Apache License

protected Session deserializeSession(Serializable sessionId) {

    BoundHashOperations<String, String, Object> hashOperations = redisTemplate
            .boundHashOps(SESSION_KEY + sessionId);

    SimpleSession session = new SimpleSession();

    try {/*from w  w  w  .ja v  a  2 s  . c o  m*/

        session.setHost((String) hashOperations.get("host"));
        session.setId(sessionId);
        session.setLastAccessTime(
                hashOperations.get("lastAccessTime") == null ? new Date(System.currentTimeMillis())
                        : (Date) hashOperations.get("lastAccessTime"));
        session.setStartTimestamp((Date) hashOperations.get("startTimestamp"));
        session.setStopTimestamp((Date) hashOperations.get("stopTimestamp"));
        session.setTimeout((long) hashOperations.get("timeout"));
        Set<String> hashKeys = hashOperations.keys();
        for (Iterator<String> iterator = hashKeys.iterator(); iterator.hasNext();) {
            String hashKey = iterator.next();
            session.setAttribute(hashKey, hashOperations.get(hashKey));
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);

    }

    logger.debug("read session " + sessionId + ", session is " + session);

    return session.isValid() ? session : null;
}

From source file:org.cast.go.message.web.WebSocketController.java

License:Apache License

/**
 * session?//w w  w .j a  v  a2s . c  o  m
 * @return
 */
@MessageMapping("/online")
public void online(User user) {
    Cache cache = ehCacheManager.getCache(Common.ACTIVE_SESSIONS_CACHE_NAME);
    Collection<SimpleSession> sessions = cache.values();
    for (SimpleSession s : sessions) {
        MyRealm.ShiroUser shiroUser = (MyRealm.ShiroUser) s.getAttribute("shiroUser");
        if (user.getUsername().equals(shiroUser.getUsername())) {
            s.setLastAccessTime(new Date());
        }
    }

}

From source file:org.graylog2.security.MongoDbSessionDAO.java

License:Open Source License

private SimpleSession getSimpleSession(Serializable sessionId, MongoDbSession dbSession) {
    final SimpleSession session = new SimpleSession();
    assignSessionId(session, sessionId);
    session.setHost(dbSession.getHost());
    session.setTimeout(dbSession.getTimeout());
    session.setStartTimestamp(dbSession.getStartTimestamp());
    session.setLastAccessTime(dbSession.getLastAccessTime());
    session.setExpired(dbSession.isExpired());
    session.setAttributes(dbSession.getAttributes());
    return session;
}

From source file:org.killbill.billing.util.security.shiro.dao.SessionModelDao.java

License:Apache License

public Session toSimpleSession() throws IOException {
    final SimpleSession simpleSession = new SimpleSession();
    if (id != null) {
        // Make sure to use a String here! It will be used as-is as the key in Ehcache.
        // When retrieving the session, the sessionId will be a String
        // See https://github.com/killbill/killbill/issues/299
        simpleSession.setId(id);/* w  ww  . jav a  2 s.c  o  m*/
    }
    simpleSession.setStartTimestamp(startTimestamp.toDate());
    simpleSession.setLastAccessTime(lastAccessTime.toDate());
    simpleSession.setTimeout(timeout);
    simpleSession.setHost(host);

    final Map attributes = serializer.deserialize(sessionData);
    //noinspection unchecked
    simpleSession.setAttributes(attributes);

    return simpleSession;
}

From source file:org.killbill.billing.util.security.shiro.dao.TestJDBCSessionDao.java

License:Apache License

private SimpleSession createSession() {
    final SimpleSession simpleSession = new SimpleSession();
    simpleSession.setStartTimestamp(new Date(System.currentTimeMillis() - 5000));
    simpleSession.setLastAccessTime(new Date(System.currentTimeMillis()));
    simpleSession.setTimeout(493934L);/*from   w w w.  j av a  2 s . c o  m*/
    simpleSession.setHost(UUID.randomUUID().toString());
    simpleSession.setAttribute(UUID.randomUUID().toString(), Short.MIN_VALUE);
    simpleSession.setAttribute(UUID.randomUUID().toString(), Integer.MIN_VALUE);
    simpleSession.setAttribute(UUID.randomUUID().toString(), Long.MIN_VALUE);
    simpleSession.setAttribute(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    // Test with Serializable objects
    simpleSession.setAttribute(UUID.randomUUID().toString(), UUID.randomUUID());
    simpleSession.setAttribute(UUID.randomUUID().toString(), new Date(1242));
    return simpleSession;
}

From source file:org.killbill.billing.util.security.shiro.dao.TestSessionModelDao.java

License:Apache License

@Test(groups = "fast")
public void testRoundTrip() throws Exception {
    final SimpleSession simpleSession = new SimpleSession();
    simpleSession.setStartTimestamp(new Date(System.currentTimeMillis() - 5000));
    simpleSession.setLastAccessTime(new Date(System.currentTimeMillis()));
    simpleSession.setTimeout(493934L);//from w ww  .ja  v a2s.co m
    simpleSession.setHost(UUID.randomUUID().toString());
    simpleSession.setAttribute(UUID.randomUUID(), Short.MIN_VALUE);
    simpleSession.setAttribute(UUID.randomUUID(), Integer.MIN_VALUE);
    simpleSession.setAttribute(UUID.randomUUID(), Long.MIN_VALUE);
    simpleSession.setAttribute(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    // Test with Serializable objects
    simpleSession.setAttribute(UUID.randomUUID().toString(), UUID.randomUUID());
    simpleSession.setAttribute(UUID.randomUUID().toString(), new Date(1242));

    final SessionModelDao sessionModelDao = new SessionModelDao(simpleSession);
    Assert.assertEquals(sessionModelDao.getTimeout(), simpleSession.getTimeout());
    Assert.assertEquals(sessionModelDao.getHost(), simpleSession.getHost());
    Assert.assertTrue(sessionModelDao.getSessionData().length > 0);

    final Session retrievedSession = sessionModelDao.toSimpleSession();
    Assert.assertEquals(retrievedSession, simpleSession);
}

From source file:org.maodian.flyingcat.im.entity.Session.java

License:Apache License

public static org.apache.shiro.session.Session to(Session session) {
    SimpleSession ss = new SimpleSession(session.getHost());
    ss.setId(session.getId());/* w  ww  .  j a v a  2  s.c om*/
    ss.setLastAccessTime(session.getLastAccessTime());
    ss.setStartTimestamp(session.getStartTimestamp());
    return ss;
}