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

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

Introduction

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

Prototype

long getTimeout() throws InvalidSessionException;

Source Link

Document

Returns the time in milliseconds that the session session may remain idle before expiring.

Usage

From source file:cn.com.xl.system.controller.LoginController.java

License:Apache License

/**
 * /*from w w w . j  a  v  a 2  s. co  m*/
 */
@Json
@Before(LoginValidator.class)
@PostMapping("/login")
public AjaxResult login(HttpServletRequest request, HttpServletResponse response) {
    String account = getParameter("account");
    String password = getParameter("password");
    String imgCode = getParameter("imgCode");
    if (!validateCaptcha(response, imgCode)) {
        return error("??");
    }
    Subject currentUser = ShiroKit.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(account, password.toCharArray());
    token.setRememberMe(true);
    try {
        currentUser.login(token);
        Session session = ShiroKit.getSession();
        LogKit.println("\nsessionID   : {} ", session.getId());
        LogKit.println("sessionHost   : {}", session.getHost());
        LogKit.println("sessionTimeOut   : {}", session.getTimeout());
    } catch (UnknownAccountException e) {
        LOGGER.error("??!", e);
        return error("??");
    } catch (DisabledAccountException e) {
        LOGGER.error("??!", e);
        return error("??");
    } catch (IncorrectCredentialsException e) {
        LOGGER.error("?!", e);
        return error("?");
    } catch (RuntimeException e) {
        LOGGER.error(",??!", e);
        return error(",??");
    }
    doLog(ShiroKit.getSession(), "");
    return success("?");
}

From source file:cn.com.xl.system.controller.LoginController.java

License:Apache License

public void doLog(Session session, String type) {
    if (!BladeLogManager.isDoLog()) {
        return;//from   w  ww.ja  v  a  2s .  c  o  m
    }
    try {
        LoginLog log = new LoginLog();
        String msg = Func.format("[sessionID]: {} [sessionHost]: {} [sessionHost]: {}", session.getId(),
                session.getHost(), session.getTimeout());
        log.setLogname(type);
        log.setMethod(msg);
        log.setCreatetime(new Date());
        log.setSucceed("1");
        log.setUserid(Func.toStr(ShiroKit.getUser().getId()));
        Blade.create(LoginLog.class).save(log);
    } catch (Exception ex) {
        LogKit.logNothing(ex);
    }
}

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())/*from   w ww.  j ava  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.biu.system.controller.LoginController.java

License:Apache License

/**
 * //  www  .j a  v a2 s.com
 */
@Before(LoginValidator.class)
@ResponseBody
@PostMapping("/login")
public AjaxResult login(HttpServletRequest request, HttpServletResponse response) {
    String account = getParameter("account");
    String password = getParameter("password");
    String imgCode = getParameter("imgCode");
    if (!validateCaptcha(response, imgCode)) {
        return error("??");
    }
    Subject currentUser = ShiroKit.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(account, password.toCharArray());
    token.setRememberMe(true);
    try {
        currentUser.login(token);
        Session session = ShiroKit.getSession();
        LogKit.println("\nsessionID   : {} ", session.getId());
        LogKit.println("sessionHost   : {}", session.getHost());
        LogKit.println("sessionTimeOut   : {}", session.getTimeout());
    } catch (UnknownAccountException e) {
        LOGGER.error("??!", e);
        return error("??");
    } catch (DisabledAccountException e) {
        LOGGER.error("??!", e);
        return error("??");
    } catch (IncorrectCredentialsException e) {
        LOGGER.error("?!", e);
        return error("?");
    } catch (RuntimeException e) {
        LOGGER.error(",??!", e);
        return error(",??");
    }
    return success("?");
}

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  www . jav a 2s. 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 {/*from  www  .j a v  a  2 s.  com*/
        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.glaf.shiro.redis.RedisShiroSessionDao.java

License:Apache License

@Override
public void update(Session session) throws UnknownSessionException {
    try {// w ww .  ja va  2s. c om
        cacheable.update(session.getId().toString().getBytes(), SerializerUtils.serialize(session),
                session.getTimeout() / 1000);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:com.hesine.manager.sercurity.SystemAuthorizingRealm.java

License:Open Source License

/**
 * ?ShiroSession,/*from   w  ww  .  ja va2 s. com*/
 *
 */
private void setSession(Object key, Object value) {
    Subject currentUser = SecurityUtils.getSubject();
    if (null != currentUser) {
        Session session = currentUser.getSession();
        System.out.println("Session[" + session.getTimeout() + "]");
        if (null != session) {
            session.setAttribute(key, value);
        }
    }
}

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

License:Apache License

protected JsonNode serialize(Object session) {
    ObjectNode sessionOb = null;//from ww w  . j av a 2  s  . c  o  m
    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 ava  2  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);

}