List of usage examples for org.apache.shiro.session Session getStartTimestamp
Date getStartTimestamp();
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 www. j a va2 s.co 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.github.richardwilly98.esdms.shiro.EsSessionDAO.java
License:Open Source License
@Override protected Serializable doCreate(Session session) { try {/*from w ww . j a v a2 s . c om*/ 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 w w w .j av a 2 s . com*/ 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 www . j a v a2s.com*/ 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);//from w ww. ja v a2 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.parallax.server.blocklyprop.security.BlocklyPropSessionDao.java
/** * Convert a Session object into a SessionRecord object * * @param session/*from w ww . j a va2 s . com*/ * 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; }
From source file:net.eggcanfly.spring.shiro.support.RedisSessionDao.java
License:Apache License
protected void seriablizeSession(Session session, Serializable sessionId) { BoundHashOperations<String, String, Object> hashOperations = redisTemplate .boundHashOps(SESSION_KEY + sessionId); Collection<Object> attributeKeys = session.getAttributeKeys(); for (Iterator<Object> iterator = attributeKeys.iterator(); iterator.hasNext();) { Object key = iterator.next(); hashOperations.put((String) key, session.getAttribute(key)); }/*from w ww .j a v a2s. c om*/ hashOperations.put("host", session.getHost()); hashOperations.put("lastAccessTime", session.getLastAccessTime()); hashOperations.put("startTimestamp", session.getStartTimestamp()); hashOperations.put("stopTimestamp", ((SimpleSession) session).getStopTimestamp()); hashOperations.put("timeout", session.getTimeout()); }
From source file:org.graylog2.security.MongoDbSessionDAO.java
License:Open Source License
@Override protected Serializable doCreate(Session session) { final Serializable id = generateSessionId(session); assignSessionId(session, id);/*from ww w. j a va 2 s . co m*/ Map<String, Object> fields = Maps.newHashMap(); fields.put("session_id", id); fields.put("host", session.getHost()); fields.put("start_timestamp", session.getStartTimestamp()); fields.put("last_access_time", session.getLastAccessTime()); fields.put("timeout", session.getTimeout()); Map<String, Object> attributes = Maps.newHashMap(); for (Object key : session.getAttributeKeys()) { attributes.put(key.toString(), session.getAttribute(key)); } fields.put("attributes", attributes); final MongoDbSession dbSession = new MongoDbSession(fields); LOG.debug("Created session {}", id); final String objectId = mongoDBSessionService.saveWithoutValidation(dbSession); return id; }
From source file:org.graylog2.security.MongoDbSessionDAO.java
License:Open Source License
@Override protected void doUpdate(Session session) { final MongoDbSession dbSession = mongoDBSessionService.load(session.getId().toString()); if (null == dbSession) { throw new RuntimeException("Couldn't load session <" + session.getId() + ">"); }// w w w . j a v a 2 s. c om LOG.debug("Updating session {}", session); dbSession.setHost(session.getHost()); dbSession.setTimeout(session.getTimeout()); dbSession.setStartTimestamp(session.getStartTimestamp()); dbSession.setLastAccessTime(session.getLastAccessTime()); if (session instanceof SimpleSession) { final SimpleSession simpleSession = (SimpleSession) session; dbSession.setAttributes(simpleSession.getAttributes()); dbSession.setExpired(simpleSession.isExpired()); } else { throw new RuntimeException("Unsupported session type: " + session.getClass().getCanonicalName()); } mongoDBSessionService.saveWithoutValidation(dbSession); }