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

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

Introduction

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

Prototype

public void setId(Serializable id) 

Source Link

Usage

From source file:com.fengduo.spark.commons.shiro.session.SessionManager.java

License:Open Source License

@Override
public Session start(SessionContext context) {
    try {//from www  . j  a va 2 s  . co m
        return super.start(context);
    } catch (NullPointerException e) {
        SimpleSession session = new SimpleSession();
        session.setId(0);
        return session;
    }
}

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

License:Apache License

/**
 * ??// w  w w  . ja  v a2 s .c  o 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 {// www  .  j a  v  a  2s  . co  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

/**
 * Inserts a new Session record into the underling EIS (a relational database in this
 * implementation).//from   w  w  w. ja  v a 2 s  . c o m
 *
 * @param session
 * the Session object to create in the EIS.
 *
 * @return
 * the EIS id (e.g. primary key) of the created Session object.
 *
 * @implNote
 * After this method is invoked, the Session.getId() method executed on the argument
 * must return a valid session identifier. That is, the following should always be
 * true:
 *
 *    Serializable id = create( session );
 *    id.equals( session.getId() ) == true
 *
 * Implementations are free to throw any exceptions that might occur due to integrity
 * violation constraints or other EIS related errors.
 */
@Override
public Serializable create(Session session) {
    LOG.trace("Create BlocklyProp session");

    // Set session timeout for 8 hours
    session.setTimeout(28800000);

    SimpleSession simpleSession = (SimpleSession) session;

    // Create a unique string and save into the session object
    String uuid = UUID.randomUUID().toString();
    simpleSession.setId(uuid);

    // Get a reference to the static session service and create
    // a session record from the session object and store it in the
    // sessionDao backing store
    SessionServiceImpl.getSessionService().create(convert(simpleSession));
    LOG.info("Creating session: {}", simpleSession.getId());

    // Return a unique session identifier
    return uuid;
}

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

/**
 * Concert a SessionRecord object to a Session object
 *
 * @param sessionRecord//from  w  w  w .  j  a  v  a  2s .  com
 * 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  ww  .j  a  va  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.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);
    }//from  w w  w  .  ja  va2s.  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.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());
    ss.setLastAccessTime(session.getLastAccessTime());
    ss.setStartTimestamp(session.getStartTimestamp());
    return ss;/* www. j a va2 s  . c o  m*/
}

From source file:uk.ac.ox.it.ords.security.services.impl.hibernate.SessionStorageServiceImplTest.java

License:Apache License

@Test
public void sessionLifecycleTest() throws Exception {

    SimpleSession session = new SimpleSession();
    session.setAttribute("test", "test");
    session.setId("1");

    SessionStorageService.Factory.getInstance().createSession("1", session);

    SimpleSession result = (SimpleSession) SessionStorageService.Factory.getInstance().readSession("1");
    assertEquals("test", result.getAttribute("test"));
    SessionStorageService.Factory.getInstance().deleteSession("1");
    assertNull(SessionStorageService.Factory.getInstance().readSession("1"));

}

From source file:uk.ac.ox.it.ords.security.services.impl.hibernate.SessionStorageServiceImplTest.java

License:Apache License

@Test
public void sessionLifecycleUpdateTest() throws Exception {

    SimpleSession session = new SimpleSession();
    session.setAttribute("test", "test");
    session.setId("1");

    SessionStorageService.Factory.getInstance().createSession("1", session);

    session.setAttribute("new", "newvalue");
    session.setAttribute("test", "newvalue");
    SessionStorageService.Factory.getInstance().updateSession("1", session);

    SimpleSession result = (SimpleSession) SessionStorageService.Factory.getInstance().readSession("1");
    assertEquals("newvalue", result.getAttribute("new"));
    assertEquals("newvalue", result.getAttribute("test"));

    SessionStorageService.Factory.getInstance().deleteSession("1");
    assertNull(SessionStorageService.Factory.getInstance().readSession("1"));
}