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

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

Introduction

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

Prototype

public Serializable getId() 

Source Link

Usage

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

License:Apache License

/**
 * ??//from   w  w w . j  a v a  2s  .c om
 *
 * @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.leshazlewood.samples.shiro.cassandra.CassandraSessionDAO.java

License:Apache License

protected void save(SimpleSession ss) {

    //Cassandra TTL values are in seconds, so we need to convert from Shiro's millis:
    int timeoutInSeconds = (int) (ss.getTimeout() / 1000);

    PreparedStatement ps = prepareSaveStatement();
    BoundStatement bs = new BoundStatement(ps);

    byte[] serialized = serializer.serialize(ss);

    ByteBuffer bytes = ByteBuffer.wrap(serialized);

    bs.bind(timeoutInSeconds, ss.getStartTimestamp(),
            ss.getStopTimestamp() != null ? ss.getStartTimestamp() : null, ss.getLastAccessTime(),
            ss.getTimeout(), ss.isExpired(), ss.getHost(), bytes, ss.getId());

    cassandraSession.execute(bs);/*from  ww w  .j a  va 2s .  c om*/
}

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).//  w w w .j av  a2s.  co  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.wms.studio.controller.admin.UserAdminManagerController.java

License:Apache License

@RequestMapping("admin/userManager/userOnlineStore")
public void getOnlineUsers(Model model) {
    Iterator<Session> sessions = sessionDao.getActiveSessions().iterator();
    ArrayList<OnlineUser> ous = new ArrayList<OnlineUser>();
    while (sessions.hasNext()) {
        OnlineUser ou = new OnlineUser();
        SimpleSession session = (SimpleSession) sessions.next();
        ou.setHost(session.getHost());//from  w w w. j av  a2 s. c  o m
        ou.setId(session.getId().toString());
        ou.setLastAccessTime(session.getLastAccessTime());
        ou.setStartTime(session.getStartTimestamp());
        PrincipalCollection principal = (PrincipalCollection) session
                .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (principal != null) {
            ShiroUser su = (ShiroUser) principal.getPrimaryPrincipal();
            ou.setUserid(su.loginName);
            ou.setUsername(su.name);
            ou.setLogin(true);
        }
        ous.add(ou);
    }
    model.addAttribute("users", ous);
    model.addAttribute("total", ous.size());
}

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

License:Apache License

@Test(groups = "slow")
public void testCRUD() throws Exception {
    // Note! We are testing the do* methods here to bypass the caching layer
    final JDBCSessionDao jdbcSessionDao = new JDBCSessionDao(dbi);

    // Retrieve/*from   w w w. jav a 2 s. c  o  m*/
    final SimpleSession session = createSession();
    Assert.assertNull(jdbcSessionDao.doReadSession(session.getId()));

    // Create
    final Serializable sessionId = jdbcSessionDao.doCreate(session);
    final Session retrievedSession = jdbcSessionDao.doReadSession(sessionId);
    Assert.assertEquals(retrievedSession, session);

    // Update
    final String newHost = UUID.randomUUID().toString();
    Assert.assertNotEquals(retrievedSession.getHost(), newHost);
    session.setHost(newHost);
    jdbcSessionDao.doUpdate(session);
    Assert.assertEquals(jdbcSessionDao.doReadSession(sessionId).getHost(), newHost);

    // Delete
    jdbcSessionDao.doDelete(session);
    Assert.assertNull(jdbcSessionDao.doReadSession(session.getId()));
}

From source file:uk.q3c.krail.core.shiro.VaadinSessionManager.java

License:Apache License

@Override
public Session start(SessionContext context) {
    log.debug("starting VaadinSessionManager");
    // Retrieve the VaadinSession for the current user.
    VaadinSession vaadinSession = sessionProvider.get();

    // Create a new security session using the session factory.
    SimpleSession shiroSession = (SimpleSession) sessionFactory.createSession(context);

    // Assign a unique ID to the session now because this session manager
    // doesn't use a SessionDAO for persistence as it delegates to any
    // VaadinSession configured persistence.
    shiroSession.setId(UUID.randomUUID().toString());

    // Put the security session in the VaadinSession. We use the session's ID as
    // part of the key just to be safe so we can double check that the security
    // session matches when it is requested in getSession.
    vaadinSession.setAttribute(SESSION_ATTRIBUTE_PREFIX + shiroSession.getId(), shiroSession);

    return shiroSession;
}