Improve Session API to use Java 8

This commit is contained in:
Vedran Pavic
2017-05-04 23:03:26 +02:00
committed by Rob Winch
parent 4cf26d9c36
commit f7e07b7f6b
33 changed files with 370 additions and 310 deletions

View File

@@ -16,6 +16,9 @@
package docs;
import java.time.Duration;
import java.util.Optional;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
@@ -70,8 +73,8 @@ public class IndexDocTests {
S session = this.repository.getSession(toSave.getId()); // <5>
// <6>
User user = session.getAttribute(ATTR_USER);
assertThat(user).isEqualTo(rwinch);
Optional<User> user = session.getAttribute(ATTR_USER);
assertThat(user.orElse(null)).isEqualTo(rwinch);
}
// ... setter methods ...
@@ -93,7 +96,7 @@ public class IndexDocTests {
public void demo() {
S toSave = this.repository.createSession(); // <2>
// ...
toSave.setMaxInactiveIntervalInSeconds(30); // <3>
toSave.setMaxInactiveInterval(Duration.ofSeconds(30)); // <3>
this.repository.save(toSave); // <4>

View File

@@ -16,8 +16,8 @@
package docs.security;
import java.time.Duration;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.Cookie;
@@ -82,8 +82,8 @@ public class RememberMeSecurityConfigurationTests<T extends Session> {
assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE);
T session = this.sessions
.getSession(new String(Base64.getDecoder().decode(cookie.getValue())));
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo((int) TimeUnit.DAYS.toSeconds(30));
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofDays(30));
}
}

View File

@@ -16,8 +16,8 @@
package docs.security;
import java.time.Duration;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.Cookie;
@@ -82,8 +82,8 @@ public class RememberMeSecurityConfigurationXmlTests<T extends Session> {
assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE);
T session = this.sessions
.getSession(new String(Base64.getDecoder().decode(cookie.getValue())));
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo((int) TimeUnit.DAYS.toSeconds(30));
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofDays(30));
}
}

View File

@@ -7,6 +7,7 @@ dependencies {
compile "org.springframework.boot:spring-boot-starter-security"
compile "org.springframework.boot:spring-boot-devtools"
compile "nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect"
compile "org.thymeleaf.extras:thymeleaf-extras-java8time"
compile "org.webjars:bootstrap"
compile "org.webjars:html5shiv"
compile "org.webjars:webjars-locator"

View File

@@ -18,11 +18,11 @@
<th>Information</th>
<th>Terminate</th>
</tr>
<tr th:each="sessionElement : ${sessions}" th:with="details=${sessionElement.getAttribute('SESSION_DETAILS')}">
<tr th:each="sessionElement : ${sessions}" th:with="details=${sessionElement.getAttribute('SESSION_DETAILS').orElse(null)}">
<td th:text="${sessionElement.id.substring(30)}"></td>
<td th:text="${details?.location}"></td>
<td th:text="${#dates.format(new java.util.Date(sessionElement.creationTime),'dd/MMM/yyyy HH:mm:ss')}"></td>
<td th:text="${#dates.format(new java.util.Date(sessionElement.lastAccessedTime),'dd/MMM/yyyy HH:mm:ss')}"></td>
<td th:text="${#temporals.format(sessionElement.creationTime.atZone(T(java.time.ZoneId).systemDefault()),'dd/MMM/yyyy HH:mm:ss')}"></td>
<td th:text="${#temporals.format(sessionElement.lastAccessedTime.atZone(T(java.time.ZoneId).systemDefault()),'dd/MMM/yyyy HH:mm:ss')}"></td>
<td th:text="${details?.accessType}"></td>
<td>
<form th:action="@{'/sessions/' + ${sessionElement.id}}" th:method="delete">

View File

@@ -20,6 +20,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
@@ -66,15 +67,15 @@ public class UserAccountsFilter implements Filter {
continue;
}
String username = session.getAttribute("username");
if (username == null) {
Optional<String> username = session.getAttribute("username");
if (!username.isPresent()) {
unauthenticatedAlias = alias;
continue;
}
String logoutUrl = sessionManager.encodeURL("./logout", alias);
String switchAccountUrl = sessionManager.encodeURL("./", alias);
Account account = new Account(username, logoutUrl, switchAccountUrl);
Account account = new Account(username.get(), logoutUrl, switchAccountUrl);
if (currentSessionAlias.equals(alias)) {
currentAccount = account;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
package org.springframework.session.data.redis;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.junit.Test;
@@ -100,7 +101,8 @@ public class RedisOperationsSessionRepositoryITests extends AbstractITests {
.doesNotContain(toSave.getId());
assertThat(this.registry.getEvent(toSave.getId()).getSession()
.<String>getAttribute(expectedAttributeName)).isEqualTo(expectedAttributeValue);
.<String>getAttribute(expectedAttributeName))
.isEqualTo(Optional.of(expectedAttributeValue));
}
@Test
@@ -118,8 +120,8 @@ public class RedisOperationsSessionRepositoryITests extends AbstractITests {
Session session = this.repository.getSession(toSave.getId());
assertThat(session.getAttributeNames().size()).isEqualTo(2);
assertThat(session.<String>getAttribute("a")).isEqualTo("b");
assertThat(session.<String>getAttribute("1")).isEqualTo("2");
assertThat(session.<String>getAttribute("a")).isEqualTo(Optional.of("b"));
assertThat(session.<String>getAttribute("1")).isEqualTo(Optional.of("2"));
this.repository.delete(toSave.getId());
}

View File

@@ -71,7 +71,7 @@ public class EnableRedisHttpSessionExpireSessionDestroyedTests<S extends Session
this.repository.save(toSave);
synchronized (this.lock) {
this.lock.wait((toSave.getMaxInactiveIntervalInSeconds() * 1000) + 1);
this.lock.wait(toSave.getMaxInactiveInterval().plusMillis(1).toMillis());
}
if (!this.registry.receivedEvent()) {
// Redis makes no guarantees on when an expired event will be fired

View File

@@ -16,6 +16,9 @@
package org.springframework.session.hazelcast.config.annotation.web.http;
import java.time.Duration;
import java.time.Instant;
import com.hazelcast.core.HazelcastInstance;
import org.junit.Before;
import org.junit.Test;
@@ -111,8 +114,8 @@ public class EnableHazelcastHttpSessionEventsTests<S extends Session> {
.isInstanceOf(SessionCreatedEvent.class);
this.registry.clear();
assertThat(sessionToSave.getMaxInactiveIntervalInSeconds())
.isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
assertThat(sessionToSave.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionExpiredEvent>getEvent(sessionToSave.getId()))
@@ -150,16 +153,16 @@ public class EnableHazelcastHttpSessionEventsTests<S extends Session> {
this.repository.save(sessionToSave);
synchronized (lock) {
lock.wait((sessionToSave.getMaxInactiveIntervalInSeconds() * 1000) - 500);
lock.wait(sessionToSave.getMaxInactiveInterval().minusMillis(500).toMillis());
}
// Get and save the session like SessionRepositoryFilter would.
S sessionToUpdate = this.repository.getSession(sessionToSave.getId());
sessionToUpdate.setLastAccessedTime(System.currentTimeMillis());
sessionToUpdate.setLastAccessedTime(Instant.now());
this.repository.save(sessionToUpdate);
synchronized (lock) {
lock.wait((sessionToUpdate.getMaxInactiveIntervalInSeconds() * 1000) - 100);
lock.wait(sessionToUpdate.getMaxInactiveInterval().minusMillis(100).toMillis());
}
assertThat(this.repository.getSession(sessionToUpdate.getId())).isNotNull();

View File

@@ -16,6 +16,8 @@
package org.springframework.session.hazelcast.config.annotation.web.http;
import java.time.Duration;
import com.hazelcast.config.ClasspathXmlConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.NetworkConfig;
@@ -62,7 +64,8 @@ public class HazelcastHttpSessionConfigurationXmlTests<S extends Session> {
S session = this.repository.getSession(sessionToSave.getId());
assertThat(session.getId()).isEqualTo(sessionToSave.getId());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(1800);
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofMinutes(30));
}
@Configuration
@@ -99,7 +102,8 @@ public class HazelcastHttpSessionConfigurationXmlTests<S extends Session> {
S session = this.repository.getSession(sessionToSave.getId());
assertThat(session.getId()).isEqualTo(sessionToSave.getId());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(1200);
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofMinutes(20));
}
@Configuration

View File

@@ -16,9 +16,12 @@
package org.springframework.session.jdbc;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
@@ -136,8 +139,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests {
Session session = this.repository.getSession(toSave.getId());
assertThat(session.getAttributeNames().size()).isEqualTo(2);
assertThat(session.<String>getAttribute("a")).isEqualTo("b");
assertThat(session.<String>getAttribute("1")).isEqualTo("2");
assertThat(session.<String>getAttribute("a")).isEqualTo(Optional.of("b"));
assertThat(session.<String>getAttribute("1")).isEqualTo(Optional.of("2"));
this.repository.delete(toSave.getId());
}
@@ -146,12 +149,12 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests {
public void updateLastAccessedTime() {
JdbcOperationsSessionRepository.JdbcSession toSave = this.repository
.createSession();
toSave.setLastAccessedTime(System.currentTimeMillis()
- (MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS * 1000 + 1000));
toSave.setLastAccessedTime(Instant.now().minusSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));
this.repository.save(toSave);
long lastAccessedTime = System.currentTimeMillis();
Instant lastAccessedTime = Instant.now();
toSave.setLastAccessedTime(lastAccessedTime);
this.repository.save(toSave);
@@ -193,8 +196,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests {
JdbcOperationsSessionRepository.JdbcSession toSave = this.repository
.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
toSave.setLastAccessedTime(System.currentTimeMillis()
- (MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS * 1000 + 1000));
toSave.setLastAccessedTime(Instant.now().minusSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS+ 1));
this.repository.save(toSave);
this.repository.cleanUpExpiredSessions();
@@ -365,8 +368,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests {
JdbcOperationsSessionRepository.JdbcSession toSave = this.repository
.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
toSave.setLastAccessedTime(System.currentTimeMillis()
- (MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS * 1000 + 1000));
toSave.setLastAccessedTime(Instant.now().minusSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));
this.repository.save(toSave);
this.repository.cleanUpExpiredSessions();
@@ -513,15 +516,15 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests {
assertThat(this.repository.getSession(session.getId())).isNotNull();
long now = System.currentTimeMillis();
Instant now = Instant.now();
session.setLastAccessedTime(now - TimeUnit.MINUTES.toMillis(10));
session.setLastAccessedTime(now.minus(10, ChronoUnit.MINUTES));
this.repository.save(session);
this.repository.cleanUpExpiredSessions();
assertThat(this.repository.getSession(session.getId())).isNotNull();
session.setLastAccessedTime(now - TimeUnit.MINUTES.toMillis(30));
session.setLastAccessedTime(now.minus(30, ChronoUnit.MINUTES));
this.repository.save(session);
this.repository.cleanUpExpiredSessions();
@@ -533,7 +536,7 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests {
public void cleanupInactiveSessionsUsingSessionDefinedInterval() {
JdbcOperationsSessionRepository.JdbcSession session = this.repository
.createSession();
session.setMaxInactiveIntervalInSeconds((int) TimeUnit.MINUTES.toSeconds(45));
session.setMaxInactiveInterval(Duration.ofMinutes(45));
this.repository.save(session);
@@ -543,15 +546,15 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests {
assertThat(this.repository.getSession(session.getId())).isNotNull();
long now = System.currentTimeMillis();
Instant now = Instant.now();
session.setLastAccessedTime(now - TimeUnit.MINUTES.toMillis(40));
session.setLastAccessedTime(now.minus(40, ChronoUnit.MINUTES));
this.repository.save(session);
this.repository.cleanUpExpiredSessions();
assertThat(this.repository.getSession(session.getId())).isNotNull();
session.setLastAccessedTime(now - TimeUnit.MINUTES.toMillis(50));
session.setLastAccessedTime(now.minus(50, ChronoUnit.MINUTES));
this.repository.save(session);
this.repository.cleanUpExpiredSessions();

View File

@@ -17,11 +17,13 @@
package org.springframework.session;
import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* <p>
@@ -41,23 +43,24 @@ import java.util.concurrent.TimeUnit;
* </p>
*
* @author Rob Winch
* @author Vedran Pavic
* @since 1.0
*/
public final class MapSession implements Session, Serializable {
/**
* Default {@link #setMaxInactiveIntervalInSeconds(int)} (30 minutes).
* Default {@link #setMaxInactiveInterval(Duration)} (30 minutes).
*/
public static final int DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS = 1800;
private String id;
private Map<String, Object> sessionAttrs = new HashMap<>();
private long creationTime = System.currentTimeMillis();
private long lastAccessedTime = this.creationTime;
private Instant creationTime = Instant.now();
private Instant lastAccessedTime = this.creationTime;
/**
* Defaults to 30 minutes.
*/
private int maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS;
private Duration maxInactiveInterval = Duration.ofSeconds(DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
/**
* Creates a new instance with a secure randomly generated identifier.
@@ -91,19 +94,19 @@ public final class MapSession implements Session, Serializable {
this.sessionAttrs = new HashMap<>(
session.getAttributeNames().size());
for (String attrName : session.getAttributeNames()) {
Object attrValue = session.getAttribute(attrName);
this.sessionAttrs.put(attrName, attrValue);
session.getAttribute(attrName)
.ifPresent(attrValue -> this.sessionAttrs.put(attrName, attrValue));
}
this.lastAccessedTime = session.getLastAccessedTime();
this.creationTime = session.getCreationTime();
this.maxInactiveInterval = session.getMaxInactiveIntervalInSeconds();
this.maxInactiveInterval = session.getMaxInactiveInterval();
}
public void setLastAccessedTime(long lastAccessedTime) {
public void setLastAccessedTime(Instant lastAccessedTime) {
this.lastAccessedTime = lastAccessedTime;
}
public long getCreationTime() {
public Instant getCreationTime() {
return this.creationTime;
}
@@ -111,33 +114,32 @@ public final class MapSession implements Session, Serializable {
return this.id;
}
public long getLastAccessedTime() {
public Instant getLastAccessedTime() {
return this.lastAccessedTime;
}
public void setMaxInactiveIntervalInSeconds(int interval) {
public void setMaxInactiveInterval(Duration interval) {
this.maxInactiveInterval = interval;
}
public int getMaxInactiveIntervalInSeconds() {
public Duration getMaxInactiveInterval() {
return this.maxInactiveInterval;
}
public boolean isExpired() {
return isExpired(System.currentTimeMillis());
return isExpired(Instant.now());
}
boolean isExpired(long now) {
if (this.maxInactiveInterval < 0) {
boolean isExpired(Instant now) {
if (this.maxInactiveInterval.isNegative()) {
return false;
}
return now - TimeUnit.SECONDS
.toMillis(this.maxInactiveInterval) >= this.lastAccessedTime;
return now.minus(this.maxInactiveInterval).compareTo(this.lastAccessedTime) >= 0;
}
@SuppressWarnings("unchecked")
public <T> T getAttribute(String attributeName) {
return (T) this.sessionAttrs.get(attributeName);
public <T> Optional<T> getAttribute(String attributeName) {
return Optional.ofNullable((T) this.sessionAttrs.get(attributeName));
}
public Set<String> getAttributeNames() {
@@ -158,12 +160,11 @@ public final class MapSession implements Session, Serializable {
}
/**
* Sets the time that this {@link Session} was created in milliseconds since midnight
* of 1/1/1970 GMT. The default is when the {@link Session} was instantiated.
* @param creationTime the time that this {@link Session} was created in milliseconds
* since midnight of 1/1/1970 GMT.
* Sets the time that this {@link Session} was created. The default is when the
* {@link Session} was instantiated.
* @param creationTime the time that this {@link Session} was created.
*/
public void setCreationTime(long creationTime) {
public void setCreationTime(Instant creationTime) {
this.creationTime = creationTime;
}

View File

@@ -16,6 +16,7 @@
package org.springframework.session;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -39,7 +40,7 @@ import org.springframework.session.events.SessionExpiredEvent;
public class MapSessionRepository implements SessionRepository<Session> {
/**
* If non-null, this value is used to override
* {@link Session#setMaxInactiveIntervalInSeconds(int)}.
* {@link Session#setMaxInactiveInterval(Duration)}.
*/
private Integer defaultMaxInactiveInterval;
@@ -67,7 +68,7 @@ public class MapSessionRepository implements SessionRepository<Session> {
/**
* If non-null, this value is used to override
* {@link Session#setMaxInactiveIntervalInSeconds(int)}.
* {@link Session#setMaxInactiveInterval(Duration)}.
* @param defaultMaxInactiveInterval the number of seconds that the {@link Session}
* should be kept alive between client requests.
*/
@@ -98,7 +99,8 @@ public class MapSessionRepository implements SessionRepository<Session> {
public Session createSession() {
Session result = new MapSession();
if (this.defaultMaxInactiveInterval != null) {
result.setMaxInactiveIntervalInSeconds(this.defaultMaxInactiveInterval);
result.setMaxInactiveInterval(
Duration.ofSeconds(this.defaultMaxInactiveInterval));
}
return result;
}

View File

@@ -16,6 +16,9 @@
package org.springframework.session;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
/**
@@ -23,6 +26,7 @@ import java.util.Set;
* used by an HttpSession, WebSocket Session, or even non web related sessions.
*
* @author Rob Winch
* @author Vedran Pavic
* @since 1.0
*/
public interface Session {
@@ -43,7 +47,7 @@ public interface Session {
* associated to that name
* @param <T> The return type of the attribute
*/
<T> T getAttribute(String attributeName);
<T> Optional<T> getAttribute(String attributeName);
/**
* Gets the attribute names that have a value associated with it. Each value can be
@@ -73,49 +77,43 @@ public interface Session {
void removeAttribute(String attributeName);
/**
* Gets the time when this session was created in milliseconds since midnight of
* 1/1/1970 GMT.
* Gets the time when this session was created.
*
* @return the time when this session was created in milliseconds since midnight of
* 1/1/1970 GMT.
* @return the time when this session was created.
*/
long getCreationTime();
Instant getCreationTime();
/**
* Sets the last accessed time in milliseconds since midnight of 1/1/1970 GMT.
* Sets the last accessed time.
*
* @param lastAccessedTime the last accessed time in milliseconds since midnight of
* 1/1/1970 GMT
* @param lastAccessedTime the last accessed time
*/
void setLastAccessedTime(long lastAccessedTime);
void setLastAccessedTime(Instant lastAccessedTime);
/**
* Gets the last time this {@link Session} was accessed expressed in milliseconds
* since midnight of 1/1/1970 GMT.
* Gets the last time this {@link Session} was accessed.
*
* @return the last time the client sent a request associated with the session
* expressed in milliseconds since midnight of 1/1/1970 GMT
*/
long getLastAccessedTime();
Instant getLastAccessedTime();
/**
* Sets the maximum inactive interval in seconds between requests before this session
* will be invalidated. A negative time indicates that the session will never timeout.
* Sets the maximum inactive interval between requests before this session will be
* invalidated. A negative time indicates that the session will never timeout.
*
* @param interval the number of seconds that the {@link Session} should be kept alive
* @param interval the amount of time that the {@link Session} should be kept alive
* between client requests.
*/
void setMaxInactiveIntervalInSeconds(int interval);
void setMaxInactiveInterval(Duration interval);
/**
* Gets the maximum inactive interval in seconds between requests before this session
* will be invalidated. A negative time indicates that the session will never timeout.
* Gets the maximum inactive interval between requests before this session will be
* invalidated. A negative time indicates that the session will never timeout.
*
* @return the maximum inactive interval in seconds between requests before this
* session will be invalidated. A negative time indicates that the session will never
* timeout.
* @return the maximum inactive interval between requests before this session will be
* invalidated. A negative time indicates that the session will never timeout.
*/
int getMaxInactiveIntervalInSeconds();
Duration getMaxInactiveInterval();
/**
* Returns true if the session is expired.

View File

@@ -16,11 +16,13 @@
package org.springframework.session.data.redis;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -151,7 +153,7 @@ import org.springframework.util.Assert;
* <p>
* An expiration is associated to each session using the
* <a href="http://redis.io/commands/expire">EXPIRE command</a> based upon the
* {@link org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession#getMaxInactiveIntervalInSeconds()}
* {@link org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession#getMaxInactiveInterval()}
* . For example:
* </p>
*
@@ -239,6 +241,7 @@ import org.springframework.util.Assert;
* </p>
*
* @author Rob Winch
* @author Vedran Pavic
* @since 1.0
*/
public class RedisOperationsSessionRepository implements
@@ -264,7 +267,7 @@ public class RedisOperationsSessionRepository implements
/**
* The key in the Hash representing
* {@link org.springframework.session.Session#getMaxInactiveIntervalInSeconds()}
* {@link org.springframework.session.Session#getMaxInactiveInterval()}
* .
*/
static final String MAX_INACTIVE_ATTR = "maxInactiveInterval";
@@ -302,7 +305,7 @@ public class RedisOperationsSessionRepository implements
/**
* If non-null, this value is used to override the default value for
* {@link RedisSession#setMaxInactiveIntervalInSeconds(int)}.
* {@link RedisSession#setMaxInactiveInterval(Duration)}.
*/
private Integer defaultMaxInactiveInterval;
@@ -446,13 +449,13 @@ public class RedisOperationsSessionRepository implements
for (Map.Entry<Object, Object> entry : entries.entrySet()) {
String key = (String) entry.getKey();
if (CREATION_TIME_ATTR.equals(key)) {
loaded.setCreationTime((Long) entry.getValue());
loaded.setCreationTime(Instant.ofEpochMilli((long) entry.getValue()));
}
else if (MAX_INACTIVE_ATTR.equals(key)) {
loaded.setMaxInactiveIntervalInSeconds((Integer) entry.getValue());
loaded.setMaxInactiveInterval(Duration.ofSeconds((int) entry.getValue()));
}
else if (LAST_ACCESSED_ATTR.equals(key)) {
loaded.setLastAccessedTime((Long) entry.getValue());
loaded.setLastAccessedTime(Instant.ofEpochMilli((long) entry.getValue()));
}
else if (key.startsWith(SESSION_ATTR_PREFIX)) {
loaded.setAttribute(key.substring(SESSION_ATTR_PREFIX.length()),
@@ -474,14 +477,15 @@ public class RedisOperationsSessionRepository implements
String expireKey = getExpiredKey(session.getId());
this.sessionRedisOperations.delete(expireKey);
session.setMaxInactiveIntervalInSeconds(0);
session.setMaxInactiveInterval(Duration.ZERO);
save(session);
}
public RedisSession createSession() {
RedisSession redisSession = new RedisSession();
if (this.defaultMaxInactiveInterval != null) {
redisSession.setMaxInactiveIntervalInSeconds(this.defaultMaxInactiveInterval);
redisSession.setMaxInactiveInterval(
Duration.ofSeconds(this.defaultMaxInactiveInterval));
}
return redisSession;
}
@@ -668,7 +672,7 @@ public class RedisOperationsSessionRepository implements
*/
final class RedisSession implements Session {
private final MapSession cached;
private Long originalLastAccessTime;
private Instant originalLastAccessTime;
private Map<String, Object> delta = new HashMap<>();
private boolean isNew;
private String originalPrincipalName;
@@ -679,9 +683,9 @@ public class RedisOperationsSessionRepository implements
*/
RedisSession() {
this(new MapSession());
this.delta.put(CREATION_TIME_ATTR, getCreationTime());
this.delta.put(MAX_INACTIVE_ATTR, getMaxInactiveIntervalInSeconds());
this.delta.put(LAST_ACCESSED_ATTR, getLastAccessedTime());
this.delta.put(CREATION_TIME_ATTR, getCreationTime().toEpochMilli());
this.delta.put(MAX_INACTIVE_ATTR, (int) getMaxInactiveInterval().getSeconds());
this.delta.put(LAST_ACCESSED_ATTR, getLastAccessedTime().toEpochMilli());
this.isNew = true;
this.flushImmediateIfNecessary();
}
@@ -702,9 +706,9 @@ public class RedisOperationsSessionRepository implements
this.isNew = isNew;
}
public void setLastAccessedTime(long lastAccessedTime) {
public void setLastAccessedTime(Instant lastAccessedTime) {
this.cached.setLastAccessedTime(lastAccessedTime);
this.putAndFlush(LAST_ACCESSED_ATTR, getLastAccessedTime());
this.putAndFlush(LAST_ACCESSED_ATTR, getLastAccessedTime().toEpochMilli());
}
public boolean isExpired() {
@@ -715,7 +719,7 @@ public class RedisOperationsSessionRepository implements
return this.isNew;
}
public long getCreationTime() {
public Instant getCreationTime() {
return this.cached.getCreationTime();
}
@@ -723,20 +727,20 @@ public class RedisOperationsSessionRepository implements
return this.cached.getId();
}
public long getLastAccessedTime() {
public Instant getLastAccessedTime() {
return this.cached.getLastAccessedTime();
}
public void setMaxInactiveIntervalInSeconds(int interval) {
this.cached.setMaxInactiveIntervalInSeconds(interval);
this.putAndFlush(MAX_INACTIVE_ATTR, getMaxInactiveIntervalInSeconds());
public void setMaxInactiveInterval(Duration interval) {
this.cached.setMaxInactiveInterval(interval);
this.putAndFlush(MAX_INACTIVE_ATTR, (int) getMaxInactiveInterval().getSeconds());
}
public int getMaxInactiveIntervalInSeconds() {
return this.cached.getMaxInactiveIntervalInSeconds();
public Duration getMaxInactiveInterval() {
return this.cached.getMaxInactiveInterval();
}
public <T> T getAttribute(String attributeName) {
public <T> Optional<T> getAttribute(String attributeName) {
return this.cached.getAttribute(attributeName);
}
@@ -799,8 +803,7 @@ public class RedisOperationsSessionRepository implements
this.delta = new HashMap<>(this.delta.size());
Long originalExpiration = this.originalLastAccessTime == null ? null
: this.originalLastAccessTime + TimeUnit.SECONDS
.toMillis(getMaxInactiveIntervalInSeconds());
: this.originalLastAccessTime.plus(getMaxInactiveInterval()).toEpochMilli();
RedisOperationsSessionRepository.this.expirationPolicy
.onExpirationUpdated(originalExpiration, this);
}
@@ -813,15 +816,15 @@ public class RedisOperationsSessionRepository implements
private SpelExpressionParser parser = new SpelExpressionParser();
public String resolvePrincipal(Session session) {
String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
return principalName;
Optional<String> principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);
if (principalName.isPresent()) {
return principalName.get();
}
Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication != null) {
Optional<Object> authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication.isPresent()) {
Expression expression = this.parser
.parseExpression("authentication?.name");
return expression.getValue(authentication, String.class);
return expression.getValue(authentication.get(), String.class);
}
return null;
}

View File

@@ -79,7 +79,7 @@ final class RedisSessionExpirationPolicy {
}
}
long sessionExpireInSeconds = session.getMaxInactiveIntervalInSeconds();
long sessionExpireInSeconds = session.getMaxInactiveInterval().getSeconds();
String sessionKey = getSessionKey(keyToExpire);
if (sessionExpireInSeconds < 0) {
@@ -147,8 +147,8 @@ final class RedisSessionExpirationPolicy {
}
static long expiresInMillis(Session session) {
int maxInactiveInSeconds = session.getMaxInactiveIntervalInSeconds();
long lastAccessedTimeInMillis = session.getLastAccessedTime();
int maxInactiveInSeconds = (int) session.getMaxInactiveInterval().getSeconds();
long lastAccessedTimeInMillis = session.getLastAccessedTime().toEpochMilli();
return lastAccessedTimeInMillis + TimeUnit.SECONDS.toMillis(maxInactiveInSeconds);
}

View File

@@ -16,10 +16,13 @@
package org.springframework.session.hazelcast;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@@ -134,7 +137,7 @@ public class HazelcastSessionRepository implements
/**
* If non-null, this value is used to override
* {@link MapSession#setMaxInactiveIntervalInSeconds(int)}.
* {@link MapSession#setMaxInactiveInterval(Duration)}.
*/
private Integer defaultMaxInactiveInterval;
@@ -193,7 +196,8 @@ public class HazelcastSessionRepository implements
public HazelcastSession createSession() {
HazelcastSession result = new HazelcastSession();
if (this.defaultMaxInactiveInterval != null) {
result.setMaxInactiveIntervalInSeconds(this.defaultMaxInactiveInterval);
result.setMaxInactiveInterval(
Duration.ofSeconds(this.defaultMaxInactiveInterval));
}
return result;
}
@@ -201,7 +205,7 @@ public class HazelcastSessionRepository implements
public void save(HazelcastSession session) {
if (session.isChanged()) {
this.sessions.put(session.getId(), session.getDelegate(),
session.getMaxInactiveIntervalInSeconds(), TimeUnit.SECONDS);
session.getMaxInactiveInterval().getSeconds(), TimeUnit.SECONDS);
session.markUnchanged();
}
}
@@ -291,7 +295,7 @@ public class HazelcastSessionRepository implements
this.delegate = cached;
}
public void setLastAccessedTime(long lastAccessedTime) {
public void setLastAccessedTime(Instant lastAccessedTime) {
this.delegate.setLastAccessedTime(lastAccessedTime);
this.changed = true;
flushImmediateIfNecessary();
@@ -301,7 +305,7 @@ public class HazelcastSessionRepository implements
return this.delegate.isExpired();
}
public long getCreationTime() {
public Instant getCreationTime() {
return this.delegate.getCreationTime();
}
@@ -309,21 +313,21 @@ public class HazelcastSessionRepository implements
return this.delegate.getId();
}
public long getLastAccessedTime() {
public Instant getLastAccessedTime() {
return this.delegate.getLastAccessedTime();
}
public void setMaxInactiveIntervalInSeconds(int interval) {
this.delegate.setMaxInactiveIntervalInSeconds(interval);
public void setMaxInactiveInterval(Duration interval) {
this.delegate.setMaxInactiveInterval(interval);
this.changed = true;
flushImmediateIfNecessary();
}
public int getMaxInactiveIntervalInSeconds() {
return this.delegate.getMaxInactiveIntervalInSeconds();
public Duration getMaxInactiveInterval() {
return this.delegate.getMaxInactiveInterval();
}
public <T> T getAttribute(String attributeName) {
public <T> Optional<T> getAttribute(String attributeName) {
return this.delegate.getAttribute(attributeName);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.session.hazelcast;
import java.util.Optional;
import com.hazelcast.query.extractor.ValueCollector;
import com.hazelcast.query.extractor.ValueExtractor;
@@ -56,16 +58,16 @@ public class PrincipalNameExtractor extends ValueExtractor<MapSession, String> {
private SpelExpressionParser parser = new SpelExpressionParser();
public String resolvePrincipal(Session session) {
String principalName = session.getAttribute(
Optional<String> principalName = session.getAttribute(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
return principalName;
if (principalName.isPresent()) {
return principalName.get();
}
Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication != null) {
Optional<Object> authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication.isPresent()) {
Expression expression = this.parser
.parseExpression("authentication?.name");
return expression.getValue(authentication, String.class);
return expression.getValue(authentication.get(), String.class);
}
return null;
}

View File

@@ -19,11 +19,14 @@ package org.springframework.session.jdbc;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.sql.DataSource;
@@ -211,7 +214,7 @@ public class JdbcOperationsSessionRepository implements
/**
* If non-null, this value is used to override the default value for
* {@link JdbcSession#setMaxInactiveIntervalInSeconds(int)}.
* {@link JdbcSession#setMaxInactiveInterval(Duration)}.
*/
private Integer defaultMaxInactiveInterval;
@@ -363,7 +366,7 @@ public class JdbcOperationsSessionRepository implements
public JdbcSession createSession() {
JdbcSession session = new JdbcSession();
if (this.defaultMaxInactiveInterval != null) {
session.setMaxInactiveIntervalInSeconds(this.defaultMaxInactiveInterval);
session.setMaxInactiveInterval(Duration.ofSeconds(this.defaultMaxInactiveInterval));
}
return session;
}
@@ -377,9 +380,9 @@ public class JdbcOperationsSessionRepository implements
JdbcOperationsSessionRepository.this.createSessionQuery,
ps -> {
ps.setString(1, session.getId());
ps.setLong(2, session.getCreationTime());
ps.setLong(3, session.getLastAccessedTime());
ps.setInt(4, session.getMaxInactiveIntervalInSeconds());
ps.setLong(2, session.getCreationTime().toEpochMilli());
ps.setLong(3, session.getLastAccessedTime().toEpochMilli());
ps.setInt(4, (int) session.getMaxInactiveInterval().getSeconds());
ps.setString(5, session.getPrincipalName());
});
if (!session.getAttributeNames().isEmpty()) {
@@ -392,7 +395,7 @@ public class JdbcOperationsSessionRepository implements
String attributeName = attributeNames.get(i);
ps.setString(1, session.getId());
ps.setString(2, attributeName);
serialize(ps, 3, session.getAttribute(attributeName));
serialize(ps, 3, session.getAttribute(attributeName).orElse(null));
}
public int getBatchSize() {
@@ -413,8 +416,8 @@ public class JdbcOperationsSessionRepository implements
JdbcOperationsSessionRepository.this.jdbcOperations.update(
JdbcOperationsSessionRepository.this.updateSessionQuery,
ps -> {
ps.setLong(1, session.getLastAccessedTime());
ps.setInt(2, session.getMaxInactiveIntervalInSeconds());
ps.setLong(1, session.getLastAccessedTime().toEpochMilli());
ps.setInt(2, (int) session.getMaxInactiveInterval().getSeconds());
ps.setString(3, session.getPrincipalName());
ps.setString(4, session.getId());
});
@@ -636,7 +639,7 @@ public class JdbcOperationsSessionRepository implements
return this.delegate.getId();
}
public <T> T getAttribute(String attributeName) {
public <T> Optional<T> getAttribute(String attributeName) {
return this.delegate.getAttribute(attributeName);
}
@@ -658,26 +661,26 @@ public class JdbcOperationsSessionRepository implements
this.delta.put(attributeName, null);
}
public long getCreationTime() {
public Instant getCreationTime() {
return this.delegate.getCreationTime();
}
public void setLastAccessedTime(long lastAccessedTime) {
public void setLastAccessedTime(Instant lastAccessedTime) {
this.delegate.setLastAccessedTime(lastAccessedTime);
this.changed = true;
}
public long getLastAccessedTime() {
public Instant getLastAccessedTime() {
return this.delegate.getLastAccessedTime();
}
public void setMaxInactiveIntervalInSeconds(int interval) {
this.delegate.setMaxInactiveIntervalInSeconds(interval);
public void setMaxInactiveInterval(Duration interval) {
this.delegate.setMaxInactiveInterval(interval);
this.changed = true;
}
public int getMaxInactiveIntervalInSeconds() {
return this.delegate.getMaxInactiveIntervalInSeconds();
public Duration getMaxInactiveInterval() {
return this.delegate.getMaxInactiveInterval();
}
public boolean isExpired() {
@@ -696,15 +699,15 @@ public class JdbcOperationsSessionRepository implements
private SpelExpressionParser parser = new SpelExpressionParser();
public String resolvePrincipal(Session session) {
String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
return principalName;
Optional<String> principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);
if (principalName.isPresent()) {
return principalName.get();
}
Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication != null) {
Optional<Object> authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication.isPresent()) {
Expression expression = this.parser
.parseExpression("authentication?.name");
return expression.getValue(authentication, String.class);
return expression.getValue(authentication.get(), String.class);
}
return null;
}
@@ -723,9 +726,9 @@ public class JdbcOperationsSessionRepository implements
}
else {
session = new MapSession(id);
session.setCreationTime(rs.getLong("CREATION_TIME"));
session.setLastAccessedTime(rs.getLong("LAST_ACCESS_TIME"));
session.setMaxInactiveIntervalInSeconds(rs.getInt("MAX_INACTIVE_INTERVAL"));
session.setCreationTime(Instant.ofEpochMilli(rs.getLong("CREATION_TIME")));
session.setLastAccessedTime(Instant.ofEpochMilli(rs.getLong("LAST_ACCESS_TIME")));
session.setMaxInactiveInterval(Duration.ofSeconds(rs.getInt("MAX_INACTIVE_INTERVAL")));
}
String attributeName = rs.getString("ATTRIBUTE_NAME");
if (attributeName != null) {

View File

@@ -17,6 +17,7 @@
package org.springframework.session.security;
import java.util.Date;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -52,11 +53,13 @@ class SpringSessionBackedSessionInformation<S extends Session>
SpringSessionBackedSessionInformation(S session,
SessionRepository<S> sessionRepository) {
super(resolvePrincipal(session), session.getId(),
new Date(session.getLastAccessedTime()));
Date.from(session.getLastAccessedTime()));
this.sessionRepository = sessionRepository;
if (Boolean.TRUE.equals(session.getAttribute(EXPIRED_ATTR))) {
super.expireNow();
}
session.getAttribute(EXPIRED_ATTR).ifPresent(expired -> {
if (Boolean.TRUE.equals(expired)) {
super.expireNow();
}
});
}
/**
@@ -66,14 +69,16 @@ class SpringSessionBackedSessionInformation<S extends Session>
* @return the principal's name, or empty String if it couldn't be determined
*/
private static String resolvePrincipal(Session session) {
String principalName = session
Optional<String> principalName = session
.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
return principalName;
if (principalName.isPresent()) {
return principalName.get();
}
SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (securityContext != null && securityContext.getAuthentication() != null) {
return securityContext.getAuthentication().getName();
Optional<SecurityContext> securityContext = session
.getAttribute(SPRING_SECURITY_CONTEXT);
if (securityContext.isPresent()
&& securityContext.get().getAuthentication() != null) {
return securityContext.get().getAuthentication().getName();
}
return "";
}

View File

@@ -69,7 +69,7 @@ public class SpringSessionBackedSessionRegistry<S extends Session>
List<SessionInformation> infos = new ArrayList<>();
for (S session : sessions) {
if (includeExpiredSessions || !Boolean.TRUE.equals(session
.getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))) {
.getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR).orElse(false))) {
infos.add(new SpringSessionBackedSessionInformation<>(session,
this.sessionRepository));
}

View File

@@ -16,6 +16,7 @@
package org.springframework.session.web.http;
import java.time.Duration;
import java.util.Collections;
import java.util.Enumeration;
import java.util.NoSuchElementException;
@@ -56,7 +57,7 @@ class HttpSessionAdapter<S extends Session> implements HttpSession {
public long getCreationTime() {
checkState();
return this.session.getCreationTime();
return this.session.getCreationTime().toEpochMilli();
}
public String getId() {
@@ -65,7 +66,7 @@ class HttpSessionAdapter<S extends Session> implements HttpSession {
public long getLastAccessedTime() {
checkState();
return this.session.getLastAccessedTime();
return this.session.getLastAccessedTime().toEpochMilli();
}
public ServletContext getServletContext() {
@@ -73,11 +74,11 @@ class HttpSessionAdapter<S extends Session> implements HttpSession {
}
public void setMaxInactiveInterval(int interval) {
this.session.setMaxInactiveIntervalInSeconds(interval);
this.session.setMaxInactiveInterval(Duration.ofSeconds(interval));
}
public int getMaxInactiveInterval() {
return this.session.getMaxInactiveIntervalInSeconds();
return (int) this.session.getMaxInactiveInterval().getSeconds();
}
public HttpSessionContext getSessionContext() {
@@ -86,7 +87,7 @@ class HttpSessionAdapter<S extends Session> implements HttpSession {
public Object getAttribute(String name) {
checkState();
return this.session.getAttribute(name);
return this.session.getAttribute(name).orElse(null);
}
public Object getValue(String name) {

View File

@@ -17,6 +17,7 @@
package org.springframework.session.web.http;
import java.io.IOException;
import java.time.Instant;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
@@ -327,7 +328,7 @@ public class SessionRepositoryFilter<S extends Session>
if (session == null) {
return null;
}
session.setLastAccessedTime(System.currentTimeMillis());
session.setLastAccessedTime(Instant.now());
return session;
}
@@ -369,7 +370,7 @@ public class SessionRepositoryFilter<S extends Session>
"For debugging purposes only (not an error)"));
}
S session = SessionRepositoryFilter.this.sessionRepository.createSession();
session.setLastAccessedTime(System.currentTimeMillis());
session.setLastAccessedTime(Instant.now());
currentSession = new HttpSessionWrapper(session, getServletContext());
setCurrentSession(currentSession);
return currentSession;

View File

@@ -16,6 +16,7 @@
package org.springframework.session.web.socket.server;
import java.time.Instant;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
@@ -123,7 +124,7 @@ public final class SessionRepositoryMessageInterceptor<S extends Session>
S session = this.sessionRepository.getSession(sessionId);
if (session != null) {
// update the last accessed time
session.setLastAccessedTime(System.currentTimeMillis());
session.setLastAccessedTime(Instant.now());
this.sessionRepository.save(session);
}
}

View File

@@ -16,7 +16,9 @@
package org.springframework.session;
import java.util.concurrent.TimeUnit;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.junit.Before;
import org.junit.Test;
@@ -36,9 +38,8 @@ public class MapSessionRepositoryTests {
@Test
public void getSessionExpired() {
this.session.setMaxInactiveIntervalInSeconds(1);
this.session.setLastAccessedTime(
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
this.session.setMaxInactiveInterval(Duration.ofSeconds(1));
this.session.setLastAccessedTime(Instant.now().minus(5, ChronoUnit.MINUTES));
this.repository.save(this.session);
assertThat(this.repository.getSession(this.session.getId())).isNull();
@@ -49,19 +50,20 @@ public class MapSessionRepositoryTests {
Session session = this.repository.createSession();
assertThat(session).isInstanceOf(MapSession.class);
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
assertThat(session.getMaxInactiveInterval())
.isEqualTo(new MapSession().getMaxInactiveInterval());
}
@Test
public void createSessionCustomDefaultExpiration() {
final int expectedMaxInterval = new MapSession().getMaxInactiveIntervalInSeconds()
+ 10;
this.repository.setDefaultMaxInactiveInterval(expectedMaxInterval);
final Duration expectedMaxInterval = new MapSession().getMaxInactiveInterval()
.plusSeconds(10);
this.repository.setDefaultMaxInactiveInterval(
(int) expectedMaxInterval.getSeconds());
Session session = this.repository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds())
assertThat(session.getMaxInactiveInterval())
.isEqualTo(expectedMaxInterval);
}
}

View File

@@ -16,6 +16,9 @@
package org.springframework.session;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
import org.junit.Before;
@@ -30,7 +33,7 @@ public class MapSessionTests {
@Before
public void setup() {
this.session = new MapSession();
this.session.setLastAccessedTime(1413258262962L);
this.session.setLastAccessedTime(Instant.ofEpochMilli(1413258262962L));
}
@Test(expected = IllegalArgumentException.class)
@@ -69,50 +72,50 @@ public class MapSessionTests {
@Test
public void isExpiredExact() {
long now = 1413260062962L;
Instant now = Instant.ofEpochMilli(1413260062962L);
assertThat(this.session.isExpired(now)).isTrue();
}
@Test
public void isExpiredOneMsTooSoon() {
long now = 1413260062961L;
Instant now = Instant.ofEpochMilli(1413260062961L);
assertThat(this.session.isExpired(now)).isFalse();
}
@Test
public void isExpiredOneMsAfter() {
long now = 1413260062963L;
Instant now = Instant.ofEpochMilli(1413260062963L);
assertThat(this.session.isExpired(now)).isTrue();
}
static class CustomSession implements Session {
public long getCreationTime() {
return 0;
public Instant getCreationTime() {
return Instant.EPOCH;
}
public String getId() {
return "id";
}
public void setLastAccessedTime(long lastAccessedTime) {
public void setLastAccessedTime(Instant lastAccessedTime) {
throw new UnsupportedOperationException();
}
public long getLastAccessedTime() {
return 0;
public Instant getLastAccessedTime() {
return Instant.EPOCH;
}
public void setMaxInactiveIntervalInSeconds(int interval) {
public void setMaxInactiveInterval(Duration interval) {
}
public int getMaxInactiveIntervalInSeconds() {
return 0;
public Duration getMaxInactiveInterval() {
return Duration.ZERO;
}
public <T> T getAttribute(String attributeName) {
return null;
public <T> Optional<T> getAttribute(String attributeName) {
return Optional.empty();
}
public Set<String> getAttributeNames() {

View File

@@ -16,6 +16,9 @@
package org.springframework.session.data.redis;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -103,8 +106,8 @@ public class RedisOperationsSessionRepositoryTests {
this.cached = new MapSession();
this.cached.setId("session-id");
this.cached.setCreationTime(1404360000000L);
this.cached.setLastAccessedTime(1404360000000L);
this.cached.setCreationTime(Instant.ofEpochMilli(1404360000000L));
this.cached.setLastAccessedTime(Instant.ofEpochMilli(1404360000000L));
}
@Test(expected = IllegalArgumentException.class)
@@ -131,8 +134,8 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void createSessionDefaultMaxInactiveInterval() throws Exception {
Session session = this.redisRepository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
assertThat(session.getMaxInactiveInterval())
.isEqualTo(new MapSession().getMaxInactiveInterval());
}
@Test
@@ -140,7 +143,8 @@ public class RedisOperationsSessionRepositoryTests {
int interval = 1;
this.redisRepository.setDefaultMaxInactiveInterval(interval);
Session session = this.redisRepository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(interval);
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(interval));
}
@Test
@@ -159,11 +163,11 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta
.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR);
assertThat(creationTime).isEqualTo(session.getCreationTime());
assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli());
assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR))
.isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR))
.isEqualTo(session.getCreationTime());
.isEqualTo(session.getCreationTime().toEpochMilli());
}
// gh-467
@@ -199,8 +203,8 @@ public class RedisOperationsSessionRepositoryTests {
// can be accessed in expiration events
// if the session is retrieved and expired it will not be returned since
// getSession checks if it is expired
long fiveMinutesAfterExpires = session.getMaxInactiveIntervalInSeconds()
+ TimeUnit.MINUTES.toSeconds(5);
long fiveMinutesAfterExpires = session.getMaxInactiveInterval().plusMinutes(5)
.getSeconds();
verify(this.boundHashOperations).expire(fiveMinutesAfterExpires,
TimeUnit.SECONDS);
verify(this.boundSetOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS);
@@ -230,7 +234,7 @@ public class RedisOperationsSessionRepositoryTests {
// if the session is retrieved and expired it will not be returned since
// getSession checks if it is expired
verify(this.boundHashOperations).expire(
session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5),
session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
TimeUnit.SECONDS);
}
@@ -238,7 +242,7 @@ public class RedisOperationsSessionRepositoryTests {
public void saveLastAccessChanged() {
RedisSession session = this.redisRepository.new RedisSession(
new MapSession(this.cached));
session.setLastAccessedTime(12345678L);
session.setLastAccessedTime(Instant.ofEpochMilli(12345678L));
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
@@ -250,7 +254,7 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(getDelta())
.isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
session.getLastAccessedTime()));
session.getLastAccessedTime().toEpochMilli()));
}
@Test
@@ -269,7 +273,7 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(getDelta()).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
session.getAttribute(attrName).orElse(null)));
}
@Test
@@ -293,7 +297,7 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void saveExpired() {
RedisSession session = this.redisRepository.new RedisSession(new MapSession());
session.setMaxInactiveIntervalInSeconds(0);
session.setMaxInactiveInterval(Duration.ZERO);
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
@@ -321,20 +325,20 @@ public class RedisOperationsSessionRepositoryTests {
public void delete() {
String attrName = "attrName";
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setLastAccessedTime(Instant.now().minusSeconds(60));
expected.setAttribute(attrName, "attrValue");
given(this.redisOperations.boundHashOps(anyString()))
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
expected.getAttribute(attrName),
expected.getAttribute(attrName).orElse(null),
RedisOperationsSessionRepository.CREATION_TIME_ATTR,
expected.getCreationTime(),
expected.getCreationTime().toEpochMilli(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR,
expected.getMaxInactiveIntervalInSeconds(),
(int) expected.getMaxInactiveInterval().getSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
expected.getLastAccessedTime());
expected.getLastAccessedTime().toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
@@ -373,18 +377,18 @@ public class RedisOperationsSessionRepositoryTests {
public void getSessionFound() {
String attrName = "attrName";
MapSession expected = new MapSession();
expected.setLastAccessedTime(System.currentTimeMillis() - 60000);
expected.setLastAccessedTime(Instant.now().minusSeconds(60));
expected.setAttribute(attrName, "attrValue");
given(this.redisOperations.boundHashOps(getKey(expected.getId())))
.willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
expected.getAttribute(attrName),
expected.getAttribute(attrName).orElse(null),
RedisOperationsSessionRepository.CREATION_TIME_ATTR,
expected.getCreationTime(),
expected.getCreationTime().toEpochMilli(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR,
expected.getMaxInactiveIntervalInSeconds(),
(int) expected.getMaxInactiveInterval().getSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
expected.getLastAccessedTime());
expected.getLastAccessedTime().toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
RedisSession session = this.redisRepository.getSession(expected.getId());
@@ -393,8 +397,8 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(session.<String>getAttribute(attrName))
.isEqualTo(expected.getAttribute(attrName));
assertThat(session.getCreationTime()).isEqualTo(expected.getCreationTime());
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(expected.getMaxInactiveIntervalInSeconds());
assertThat(session.getMaxInactiveInterval())
.isEqualTo(expected.getMaxInactiveInterval());
assertThat(session.getLastAccessedTime())
.isEqualTo(expected.getLastAccessedTime());
@@ -407,7 +411,7 @@ public class RedisOperationsSessionRepositoryTests {
.willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
assertThat(this.redisRepository.getSession(expiredId)).isNull();
@@ -424,7 +428,7 @@ public class RedisOperationsSessionRepositoryTests {
.willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
assertThat(this.redisRepository.findByIndexNameAndIndexValue(
@@ -434,9 +438,9 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void findByPrincipalName() {
long lastAccessed = System.currentTimeMillis() - 10;
long createdTime = lastAccessed - 10;
int maxInactive = 3600;
Instant lastAccessed = Instant.now().minusMillis(10);
Instant createdTime = lastAccessed.minusMillis(10);
Duration maxInactive = Duration.ofHours(1);
String sessionId = "some-id";
given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations);
@@ -444,9 +448,9 @@ public class RedisOperationsSessionRepositoryTests {
.willReturn(Collections.<Object>singleton(sessionId));
given(this.redisOperations.boundHashOps(getKey(sessionId)))
.willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.CREATION_TIME_ATTR, createdTime,
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, maxInactive,
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, lastAccessed);
Map map = map(RedisOperationsSessionRepository.CREATION_TIME_ATTR, createdTime.toEpochMilli(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, (int) maxInactive.getSeconds(),
RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, lastAccessed.toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
Map<String, RedisSession> sessionIdToSessions = this.redisRepository
@@ -459,7 +463,7 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(session).isNotNull();
assertThat(session.getId()).isEqualTo(sessionId);
assertThat(session.getLastAccessedTime()).isEqualTo(lastAccessed);
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(maxInactive);
assertThat(session.getMaxInactiveInterval()).isEqualTo(maxInactive);
assertThat(session.getCreationTime()).isEqualTo(createdTime);
}
@@ -572,7 +576,7 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void flushModeOnSaveSetLastAccessedTime() {
RedisSession session = this.redisRepository.createSession();
session.setLastAccessedTime(1L);
session.setLastAccessedTime(Instant.ofEpochMilli(1L));
verifyZeroInteractions(this.boundHashOperations);
}
@@ -580,7 +584,7 @@ public class RedisOperationsSessionRepositoryTests {
@Test
public void flushModeOnSaveSetMaxInactiveIntervalInSeconds() {
RedisSession session = this.redisRepository.createSession();
session.setMaxInactiveIntervalInSeconds(1);
session.setMaxInactiveInterval(Duration.ofSeconds(1));
verifyZeroInteractions(this.boundHashOperations);
}
@@ -601,11 +605,11 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(delta.size()).isEqualTo(3);
Object creationTime = delta
.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR);
assertThat(creationTime).isEqualTo(session.getCreationTime());
assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli());
assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR))
.isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR))
.isEqualTo(session.getCreationTime());
.isEqualTo(session.getCreationTime().toEpochMilli());
}
@Test
@@ -626,7 +630,7 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
session.getAttribute(attrName).orElse(null)));
}
@Test
@@ -647,7 +651,7 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName)));
session.getAttribute(attrName).orElse(null)));
}
@Test
@@ -664,7 +668,7 @@ public class RedisOperationsSessionRepositoryTests {
reset(this.boundHashOperations);
session.setMaxInactiveIntervalInSeconds(1);
session.setMaxInactiveInterval(Duration.ofSeconds(1));
verify(this.boundHashOperations).expire(anyLong(), any(TimeUnit.class));
}
@@ -681,14 +685,13 @@ public class RedisOperationsSessionRepositoryTests {
this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE);
RedisSession session = this.redisRepository.createSession();
long now = System.currentTimeMillis();
session.setLastAccessedTime(now);
session.setLastAccessedTime(Instant.now());
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta)
.isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR,
session.getLastAccessedTime()));
session.getLastAccessedTime().toEpochMilli()));
}
@Test(expected = IllegalArgumentException.class)

View File

@@ -16,6 +16,8 @@
package org.springframework.session.data.redis;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
@@ -66,7 +68,7 @@ public class RedisSessionExpirationPolicyTests {
this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations,
repository);
this.session = new MapSession();
this.session.setLastAccessedTime(1429116694675L);
this.session.setLastAccessedTime(Instant.ofEpochMilli(1429116694675L));
this.session.setId("12345");
given(this.sessionRedisOperations.boundSetOps(anyString()))
@@ -123,8 +125,9 @@ public class RedisSessionExpirationPolicyTests {
verify(this.sessionRedisOperations).boundSetOps(expectedExpireKey);
verify(this.setOperations).add("expires:" + this.session.getId());
verify(this.setOperations).expire(this.session.getMaxInactiveIntervalInSeconds()
+ TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
verify(this.setOperations).expire(
this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
TimeUnit.SECONDS);
}
@Test
@@ -134,8 +137,9 @@ public class RedisSessionExpirationPolicyTests {
this.policy.onExpirationUpdated(null, this.session);
verify(this.sessionRedisOperations).boundHashOps(sessionKey);
verify(this.hashOperations).expire(this.session.getMaxInactiveIntervalInSeconds()
+ TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
verify(this.hashOperations).expire(
this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
TimeUnit.SECONDS);
}
@Test
@@ -144,7 +148,7 @@ public class RedisSessionExpirationPolicyTests {
long originalExpirationTimeInMs = ONE_MINUTE_AGO;
this.session.setMaxInactiveIntervalInSeconds(0);
this.session.setMaxInactiveInterval(Duration.ZERO);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);
@@ -152,15 +156,16 @@ public class RedisSessionExpirationPolicyTests {
verify(this.setOperations).remove("expires:" + this.session.getId());
verify(this.setOperations).add("expires:" + this.session.getId());
verify(this.sessionRedisOperations).delete(sessionKey);
verify(this.setOperations).expire(this.session.getMaxInactiveIntervalInSeconds()
+ TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS);
verify(this.setOperations).expire(
this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(),
TimeUnit.SECONDS);
}
@Test
public void onExpirationUpdatedPersistOnNegativeExpiration() throws Exception {
long originalExpirationTimeInMs = ONE_MINUTE_AGO;
this.session.setMaxInactiveIntervalInSeconds(-1);
this.session.setMaxInactiveInterval(Duration.ofSeconds(-1));
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);

View File

@@ -16,6 +16,8 @@
package org.springframework.session.hazelcast;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -82,8 +84,8 @@ public class HazelcastSessionRepositoryTests {
public void createSessionDefaultMaxInactiveInterval() throws Exception {
HazelcastSession session = this.repository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
assertThat(session.getMaxInactiveInterval())
.isEqualTo(new MapSession().getMaxInactiveInterval());
verifyZeroInteractions(this.sessions);
}
@@ -94,7 +96,8 @@ public class HazelcastSessionRepositoryTests {
HazelcastSession session = this.repository.createSession();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(interval);
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(interval));
verifyZeroInteractions(this.sessions);
}
@@ -168,7 +171,7 @@ public class HazelcastSessionRepositoryTests {
@Test
public void saveUpdatedLastAccessedTimeFlushModeOnSave() {
HazelcastSession session = this.repository.createSession();
session.setLastAccessedTime(System.currentTimeMillis());
session.setLastAccessedTime(Instant.now());
verifyZeroInteractions(this.sessions);
this.repository.save(session);
@@ -181,7 +184,7 @@ public class HazelcastSessionRepositoryTests {
this.repository.setHazelcastFlushMode(HazelcastFlushMode.IMMEDIATE);
HazelcastSession session = this.repository.createSession();
session.setLastAccessedTime(System.currentTimeMillis());
session.setLastAccessedTime(Instant.now());
verify(this.sessions, times(2)).put(eq(session.getId()), eq(session.getDelegate()),
isA(Long.class), eq(TimeUnit.SECONDS));
@@ -192,7 +195,7 @@ public class HazelcastSessionRepositoryTests {
@Test
public void saveUpdatedMaxInactiveIntervalInSecondsFlushModeOnSave() {
HazelcastSession session = this.repository.createSession();
session.setMaxInactiveIntervalInSeconds(1);
session.setMaxInactiveInterval(Duration.ofSeconds(1));
verifyZeroInteractions(this.sessions);
this.repository.save(session);
@@ -205,7 +208,7 @@ public class HazelcastSessionRepositoryTests {
this.repository.setHazelcastFlushMode(HazelcastFlushMode.IMMEDIATE);
HazelcastSession session = this.repository.createSession();
session.setMaxInactiveIntervalInSeconds(1);
session.setMaxInactiveInterval(Duration.ofSeconds(1));
verify(this.sessions, times(2)).put(eq(session.getId()), eq(session.getDelegate()),
isA(Long.class), eq(TimeUnit.SECONDS));
@@ -249,8 +252,8 @@ public class HazelcastSessionRepositoryTests {
@Test
public void getSessionExpired() {
MapSession expired = new MapSession();
expired.setLastAccessedTime(System.currentTimeMillis() -
(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS * 1000 + 1000));
expired.setLastAccessedTime(Instant.now().minusSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));
given(this.sessions.get(eq(expired.getId()))).willReturn(expired);
HazelcastSession session = this.repository.getSession(expired.getId());
@@ -269,7 +272,7 @@ public class HazelcastSessionRepositoryTests {
HazelcastSession session = this.repository.getSession(saved.getId());
assertThat(session.getId()).isEqualTo(saved.getId());
assertThat(session.<String>getAttribute("savedName")).isEqualTo("savedValue");
assertThat(session.<String>getAttribute("savedName").orElse(null)).isEqualTo("savedValue");
verify(this.sessions, times(1)).get(eq(saved.getId()));
}

View File

@@ -15,6 +15,8 @@
*/
package org.springframework.session.jdbc;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -304,8 +306,8 @@ public class JdbcOperationsSessionRepositoryTests {
.createSession();
assertThat(session.isNew()).isTrue();
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds());
assertThat(session.getMaxInactiveInterval())
.isEqualTo(new MapSession().getMaxInactiveInterval());
verifyZeroInteractions(this.jdbcOperations);
}
@@ -318,7 +320,7 @@ public class JdbcOperationsSessionRepositoryTests {
.createSession();
assertThat(session.isNew()).isTrue();
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(interval);
assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(interval));
verifyZeroInteractions(this.jdbcOperations);
}
@@ -372,7 +374,7 @@ public class JdbcOperationsSessionRepositoryTests {
public void saveUpdatedLastAccessedTime() {
JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession(
new MapSession());
session.setLastAccessedTime(System.currentTimeMillis());
session.setLastAccessedTime(Instant.now());
this.repository.save(session);
@@ -413,8 +415,8 @@ public class JdbcOperationsSessionRepositoryTests {
@Test
public void getSessionExpired() {
MapSession expired = new MapSession();
expired.setLastAccessedTime(System.currentTimeMillis() -
(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS * 1000 + 1000));
expired.setLastAccessedTime(Instant.now().minusSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));
given(this.jdbcOperations.query(isA(String.class),
isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)))
.willReturn(Collections.singletonList(expired));
@@ -443,7 +445,7 @@ public class JdbcOperationsSessionRepositoryTests {
assertThat(session.getId()).isEqualTo(saved.getId());
assertThat(session.isNew()).isFalse();
assertThat(session.<String>getAttribute("savedName")).isEqualTo("savedValue");
assertThat(session.<String>getAttribute("savedName").orElse(null)).isEqualTo("savedValue");
assertPropagationRequiresNew();
verify(this.jdbcOperations, times(1)).query(isA(String.class),
isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class));

View File

@@ -16,11 +16,12 @@
package org.springframework.session.security;
import java.time.Instant;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -57,7 +58,7 @@ public class SpringSessionBackedSessionRegistryTest {
private static final User PRINCIPAL = new User(USER_NAME, "password",
Collections.emptyList());
private static final Date NOW = new Date();
private static final Instant NOW = Instant.now();
@Mock
private FindByIndexNameSessionRepository<Session> sessionRepository;
@@ -67,21 +68,21 @@ public class SpringSessionBackedSessionRegistryTest {
@Test
public void sessionInformationForExistingSession() {
Session session = createSession(SESSION_ID, USER_NAME, NOW.getTime());
Session session = createSession(SESSION_ID, USER_NAME, NOW);
when(this.sessionRepository.getSession(SESSION_ID)).thenReturn(session);
SessionInformation sessionInfo = this.sessionRegistry
.getSessionInformation(SESSION_ID);
assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID);
assertThat(sessionInfo.getLastRequest()).isEqualTo(NOW);
assertThat(sessionInfo.getLastRequest().toInstant()).isEqualTo(NOW);
assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
assertThat(sessionInfo.isExpired()).isFalse();
}
@Test
public void sessionInformationForExpiredSession() {
Session session = createSession(SESSION_ID, USER_NAME, NOW.getTime());
Session session = createSession(SESSION_ID, USER_NAME, NOW);
session.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR,
Boolean.TRUE);
when(this.sessionRepository.getSession(SESSION_ID)).thenReturn(session);
@@ -90,7 +91,7 @@ public class SpringSessionBackedSessionRegistryTest {
.getSessionInformation(SESSION_ID);
assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID);
assertThat(sessionInfo.getLastRequest()).isEqualTo(NOW);
assertThat(sessionInfo.getLastRequest().toInstant()).isEqualTo(NOW);
assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
assertThat(sessionInfo.isExpired()).isTrue();
}
@@ -125,7 +126,7 @@ public class SpringSessionBackedSessionRegistryTest {
@Test
public void expireNow() {
Session session = createSession(SESSION_ID, USER_NAME, NOW.getTime());
Session session = createSession(SESSION_ID, USER_NAME, NOW);
when(this.sessionRepository.getSession(SESSION_ID)).thenReturn(session);
SessionInformation sessionInfo = this.sessionRegistry
@@ -139,10 +140,11 @@ public class SpringSessionBackedSessionRegistryTest {
verify(this.sessionRepository).save(captor.capture());
assertThat(captor.getValue().<Boolean>getAttribute(
SpringSessionBackedSessionInformation.EXPIRED_ATTR))
.isEqualTo(Boolean.TRUE);
.isEqualTo(Optional.of(Boolean.TRUE));
}
private Session createSession(String sessionId, String userName, Long lastAccessed) {
private Session createSession(String sessionId, String userName,
Instant lastAccessed) {
MapSession session = new MapSession(sessionId);
session.setLastAccessedTime(lastAccessed);
Authentication authentication = mock(Authentication.class);
@@ -154,10 +156,10 @@ public class SpringSessionBackedSessionRegistryTest {
}
private void setUpSessions() {
Session session1 = createSession(SESSION_ID, USER_NAME, NOW.getTime());
Session session1 = createSession(SESSION_ID, USER_NAME, NOW);
session1.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR,
Boolean.TRUE);
Session session2 = createSession(SESSION_ID2, USER_NAME, NOW.getTime());
Session session2 = createSession(SESSION_ID2, USER_NAME, NOW);
Map<String, Session> sessions = new LinkedHashMap<>();
sessions.put(session1.getId(), session1);
sessions.put(session2.getId(), session2);

View File

@@ -17,6 +17,7 @@
package org.springframework.session.web.http;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
@@ -125,7 +126,7 @@ public class SessionRepositoryFilterTests {
@Test
public void doFilterCreateSetsLastAccessedTime() throws Exception {
MapSession session = new MapSession();
session.setLastAccessedTime(0L);
session.setLastAccessedTime(Instant.EPOCH);
this.sessionRepository = spy(this.sessionRepository);
given(this.sessionRepository.createSession()).willReturn(session);
this.filter = new SessionRepositoryFilter<>(

View File

@@ -16,6 +16,7 @@
package org.springframework.session.web.socket.server;
import java.time.Instant;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
@@ -44,7 +45,7 @@ import org.springframework.session.SessionRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.longThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -157,7 +158,7 @@ public class SessionRepositoryMessageInterceptorTests {
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.session).setLastAccessedTime(argThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
}
@@ -168,7 +169,7 @@ public class SessionRepositoryMessageInterceptorTests {
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.session).setLastAccessedTime(argThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
}
@@ -179,19 +180,19 @@ public class SessionRepositoryMessageInterceptorTests {
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.session).setLastAccessedTime(argThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
}
@Test
public void preSendUnsubscribeUpdatesLastUpdateTime() {
setMessageType(SimpMessageType.UNSUBSCRIBE);
this.session.setLastAccessedTime(0L);
this.session.setLastAccessedTime(Instant.EPOCH);
assertThat(this.interceptor.preSend(createMessage(), this.channel))
.isSameAs(this.createMessage);
verify(this.session).setLastAccessedTime(longThat(isAlmostNow()));
verify(this.session).setLastAccessedTime(argThat(isAlmostNow()));
verify(this.sessionRepository).save(this.session);
}
@@ -285,11 +286,11 @@ public class SessionRepositoryMessageInterceptorTests {
return new AlmostNowMatcher();
}
static class AlmostNowMatcher implements ArgumentMatcher<Long> {
static class AlmostNowMatcher implements ArgumentMatcher<Instant> {
public boolean matches(Long argument) {
public boolean matches(Instant argument) {
long now = System.currentTimeMillis();
long delta = now - argument;
long delta = now - argument.toEpochMilli();
return delta >= 0 && delta < TimeUnit.SECONDS.toMillis(3);
}