Example usage for org.apache.shiro.session Session getLastAccessTime

List of usage examples for org.apache.shiro.session Session getLastAccessTime

Introduction

In this page you can find the example usage for org.apache.shiro.session Session getLastAccessTime.

Prototype

Date getLastAccessTime();

Source Link

Document

Returns the last time the application received a request or method invocation from the user associated with this session.

Usage

From source file:com.baguaz.module.user.BgzSessionListener.java

License:Apache License

private String buildLogStr(Session session) {
    StringBuilder sb = new StringBuilder();
    sb.append("\n#################################################").append("\nid          :")
            .append(session.getId())/*w  ww  . j a  v  a  2 s  .c o m*/
            .append("\nstart       :"
                    + DateFormatUtils.format(session.getStartTimestamp(), "yyyy-MM-dd HH:mm:ss"))
            .append("\nlast        :"
                    + DateFormatUtils.format(session.getLastAccessTime(), "yyyy-MM-dd HH:mm:ss"))
            .append("\ntimeout(min):" + session.getTimeout() / (1000 * 60))
            .append("\nhost        :" + session.getHost())
            .append("\nattr keys   :" + session.getAttributeKeys())
            .append("\n#################################################");
    return sb.toString();
}

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

License:Apache License

/**
 * ??/*from w  ww  .  j  a  v a2s  . c  o  m*/
 *
 * @param includeLeave  ??3?
 * @param principal     ???
 * @param filterSession ????
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
    // ?
    if (includeLeave && principal == null) {
        return getActiveSessions();
    }
    Set<Session> sessions = Sets.newHashSet();
    for (Session session : getActiveSessions()) {
        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);
        }
    }
    return sessions;
}

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

License:Apache License

@Override
public void update(Session session) throws UnknownSessionException {
    if (session == null || session.getId() == null) {
        return;/*from w  ww.ja  v  a2s. c o m*/
    }

    HttpServletRequest request = Servlets.getRequest();
    if (request != null) {
        String uri = request.getServletPath();
        // ???SESSION
        if (Servlets.isStaticFile(uri)) {
            return;
        }
        // ?SESSION
        if (StringUtils.startsWith(uri, Global.getConfig("web.view.prefix"))
                && StringUtils.endsWith(uri, Global.getConfig("web.view.suffix"))) {
            return;
        }
        // ?SESSION
        if (Global.NO.equals(request.getParameter("updateSession"))) {
            return;
        }
    }

    Jedis jedis = null;
    try {

        jedis = JedisUtils.getResource();

        // ??
        PrincipalCollection pc = (PrincipalCollection) session
                .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;

        jedis.hset(sessionKeyPrefix, session.getId().toString(),
                principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
        jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));

        // 
        int timeoutSeconds = (int) (session.getTimeout() / 1000);
        jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);

        logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
    } catch (Exception e) {
        logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e);
    } finally {
        JedisUtils.returnResource(jedis);
    }
}

From source file:com.github.richardwilly98.esdms.shiro.EsSessionDAO.java

License:Open Source License

@Override
protected Serializable doCreate(Session session) {
    try {//  w  w  w .  j av a2  s . c o  m
        session.setTimeout(sessionTimeout);
        if (log.isTraceEnabled()) {
            log.trace(String.format("*** doCreate - %s - timeout: %s", session, session.getTimeout()));
        }
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);

        SessionImpl s = new SessionImpl.Builder().id(sessionId.toString())
                .createTime(session.getStartTimestamp()).lastAccessTime(session.getLastAccessTime())
                .active(true).timeout(session.getTimeout()).build();
        s = authenticationService.create(s);
        EsSession esSession = new EsSession(s);
        return esSession.getId();
    } catch (ServiceException ex) {
        log.error("doCreate failed", ex);
    }
    return null;
}

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

License:Apache License

protected JsonNode serialize(Object session) {
    ObjectNode sessionOb = null;//from  www .j  a  v a  2  s.c om
    if (session instanceof Session) {
        Session s = (Session) session;
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        sessionOb = mapper.createObjectNode();
        sessionOb.put("_id", s.getId().toString());
        sessionOb.put("last_access_time", s.getLastAccessTime().getTime());
        sessionOb.put("start_time_stamp", s.getStartTimestamp().getTime());
        sessionOb.put("timeout", s.getTimeout());
        sessionOb.put("host", s.getHost());
        ObjectNode attributesOb = sessionOb.putObject("attributes");
        for (Iterator<Object> it = s.getAttributeKeys().iterator(); it.hasNext();) {
            Object key = it.next();
            Object value = s.getAttribute(key);
            if (value != null) {
                // base64 encode objects in session
                logger.debug("Storing session attribute:" + key + "=" + value);
                attributesOb.put(escapeMongoCharacters("" + key), SerializableUtils.serialize(value));
            }
        }
    }
    return sessionOb;
}

From source file:com.ikanow.aleph2.security.service.IkanowV2SecurityServiceTest.java

License:Apache License

@Test
public void testSessionDb() {
    SessionDb sessionDb = new SessionDb(_service_context);
    Session session1 = mock(Session.class);
    when(session1.getId()).thenReturn("123");
    when(session1.getHost()).thenReturn("localhost");
    Date now = new Date();
    when(session1.getLastAccessTime()).thenReturn(now);
    when(session1.getStartTimestamp()).thenReturn(now);
    when(session1.getTimeout()).thenReturn(1000L * 60L);
    when(session1.getAttributeKeys()).thenReturn(Arrays.asList("currentUser"));
    when(session1.getAttribute(any())).thenReturn("doesnotexist@ikanow.com");
    sessionDb.store(session1);/*from w  w  w.j av  a2  s .c  o m*/
    Session session2 = (Session) sessionDb.loadById("123");
    assertNotNull(session2);
    assertEquals(session1.getId(), session2.getId());
    assertEquals(session1.getHost(), session2.getHost());
    assertEquals(session1.getLastAccessTime(), session2.getLastAccessTime());
    assertEquals(session1.getStartTimestamp(), session2.getStartTimestamp());
    assertEquals(session1.getAttribute("currentUser"), session2.getAttribute("currentUser"));
    sessionDb.delete("123");
    Session session3 = (Session) sessionDb.loadById("123");
    assertNull(session3);

}

From source file:com.imos.sample.Quickstart.java

License:Apache License

public static void main(String[] args) {

    // The easiest way to create a Shiro SecurityManager with configured
    // realms, users, roles and permissions is to use the simple INI config.
    // We'll do that by using a factory that can ingest a .ini file and
    // return a SecurityManager instance:
    // Use the shiro.ini file at the root of the classpath
    // (file: and url: prefixes load from files and urls respectively):
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();

    // for this simple example quickstart, make the SecurityManager
    // accessible as a JVM singleton.  Most applications wouldn't do this
    // and instead rely on their container configuration or web.xml for
    // webapps.  That is outside the scope of this simple quickstart, so
    // we'll just do the bare minimum so you can continue to get a feel
    // for things.
    SecurityUtils.setSecurityManager(securityManager);

    // Now that a simple Shiro environment is set up, let's see what you can do:
    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();
    ///home/alok/Tools/netbean_dev_workspace/AllProjects/SampleShiro/src/main/java/com/imos/sample/Quickstart.java

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    Session session = currentUser.getSession();
    session.setAttribute("someKey", "aValue");

    session.setTimeout(12000);/*ww w .  j  a va  2  s. c o  m*/
    System.out.println("Id : " + session.getId());
    System.out.println("Host : " + session.getHost());
    System.out.println("StartTime : " + session.getStartTimestamp());
    System.out.println("Timeout : " + session.getTimeout());

    String value = (String) session.getAttribute("someKey");
    if (value.equals("aValue")) {
        log.info("Retrieved the correct value! [" + value + "]");
    }

    // let's login the current user so we can check against roles and permissions:
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        } // ... catch more exceptions here (maybe custom ones specific to your application?
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

    //test a role:
    if (currentUser.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");
    }

    //test a typed permission (not instance-level)
    if (currentUser.isPermitted("lightsaber:weild")) {
        log.info("You may use a lightsaber ring.  Use it wisely.");
    } else {
        log.info("Sorry, lightsaber rings are for schwartz masters only.");
    }

    //a (very powerful) Instance Level permission:
    if (currentUser.isPermitted("winnebago:drive:eagle5")) {
        log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    try {
        System.out.println("Delay for 10 sec");
        Thread.sleep(10000);
    } catch (InterruptedException ex) {
        log.error(ex.getMessage());
    }

    try {
        System.out.println("LastAccess : " + session.getLastAccessTime());

        //all done - log out!
        currentUser.logout();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    //        currentUser = SecurityUtils.getSubject();
    System.out.println("\nNew Session");
    session = currentUser.getSession();
    session.setAttribute("someKey", "aValue");

    System.out.println("Id : " + session.getId());
    System.out.println("Host : " + session.getHost());
    System.out.println("StartTime : " + session.getStartTimestamp());
    System.out.println("Timeout : " + session.getTimeout() / 1000);

    // let's login the current user so we can check against roles and permissions:
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            //                currentUser.login(token);
        } catch (UnknownAccountException uae) {
            log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        } // ... catch more exceptions here (maybe custom ones specific to your application?
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }

        try {
            System.out.println("Delay for 5 sec");
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            log.error(ex.getMessage());
        }

        try {
            System.out.println("Last Access : " + session.getLastAccessTime());

            //all done - log out!
            currentUser.logout();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    System.exit(0);
}

From source file:com.ineunet.knife.security.session.DefaultWebSessionManager.java

License:Apache License

/**
 * can be override by childClass//from ww w .  j a  va2 s .  c o  m
 */
protected void validate(Session session) {
    try {
        Date lastAccessTime = session.getLastAccessTime();
        if (System.currentTimeMillis() - lastAccessTime.getTime() > globalSessionTimeout) {
            Server.logout(session);
            sessionDAO.delete(session);
        }
    } catch (Exception e) {
        // program step here when session deprecated
        // log.error("validateSessions error.", e);
        sessionDAO.delete(session);
    }
}

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

/**
 * Convert a Session object into a SessionRecord object
 *
 * @param session/*from ww w. j a v  a  2  s.c o m*/
 * the session to convert into a SessionRecord
 *
 * @return
 * a SessionRecord object containing the details necessary to persist the object
 * into an EIS.
 */
private SessionRecord convert(Session session) {
    LOG.trace("Converting session {} to a SessionRecord object", session.getId());

    // Cast the Session parameter into a SimpleSession reference
    SimpleSession ssession = (SimpleSession) session;

    SessionRecord sessionRecord = new SessionRecord();
    sessionRecord.setIdsession(session.getId().toString());
    sessionRecord.setStarttimestamp(new Timestamp(session.getStartTimestamp().getTime()));
    sessionRecord.setLastaccesstime(new Timestamp(session.getLastAccessTime().getTime()));
    sessionRecord.setTimeout(session.getTimeout());
    sessionRecord.setHost(session.getHost());

    // Gather the session attributes into a HashMap that can be persisted into the
    // SessionRecord object
    if (ssession.getAttributes() != null) {
        HashMap<Object, Object> attributes = (HashMap<Object, Object>) ssession.getAttributes();

        // Logging attributes
        // LOG.debug("Session attributes:");
        // attributes.forEach( (k,v) -> LOG.debug("Key: {}, Value: {}", k, v));

        sessionRecord.setAttributes(SerializationUtils.serialize(attributes));
    }

    return sessionRecord;
}

From source file:com.sonicle.webtop.core.bol.model.SessionInfo.java

License:Open Source License

public SessionInfo(DateTime now, Session session, UserProfileId profileId, int pushSessionsCount) {
    this.sessionId = session.getId().toString();
    this.timeout = (session.getTimeout() < 0) ? -1 : (int) session.getTimeout() / 1000;
    this.creationTime = new DateTime(session.getStartTimestamp());
    this.lastAccessTime = new DateTime(session.getLastAccessTime());
    this.usedTime = Math.abs(Seconds.secondsBetween(creationTime, now).getSeconds());
    this.ttl = (timeout < 0) ? -1
            : timeout - Math.abs(Seconds.secondsBetween(lastAccessTime, now).getSeconds());
    this.profileId = profileId.toString();
    this.pushSessionsCount = pushSessionsCount;
}