Adapt to Spring Session's merging of ExpiringSession into Session

This commit is contained in:
Greg Turnquist
2017-06-18 22:35:07 -05:00
parent 279b03f1dc
commit ab898a8b05
14 changed files with 192 additions and 145 deletions

View File

@@ -41,6 +41,7 @@ import com.mongodb.DBObject;
* bean.
*
* @author Jakub Kubrynski
* @author Greg Turnquist
* @since 1.2
*/
public abstract class AbstractMongoSessionConverter implements GenericConverter {
@@ -89,14 +90,16 @@ public abstract class AbstractMongoSessionConverter implements GenericConverter
if (resolvedPrincipal != null) {
return resolvedPrincipal;
} else {
return expiringSession.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
return expiringSession.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)
.map(Object::toString)
.orElse("");
}
}
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(
new ConvertiblePair(DBObject.class, MongoExpiringSession.class));
new ConvertiblePair(DBObject.class, MongoSession.class));
}
@SuppressWarnings("unchecked")
@@ -113,11 +116,11 @@ public abstract class AbstractMongoSessionConverter implements GenericConverter
return convert((Document) source);
}
else {
return convert((MongoExpiringSession) source);
return convert((MongoSession) source);
}
}
protected abstract DBObject convert(MongoExpiringSession session);
protected abstract DBObject convert(MongoSession session);
protected abstract MongoExpiringSession convert(Document sessionWrapper);
protected abstract MongoSession convert(Document sessionWrapper);
}

View File

@@ -15,6 +15,8 @@
*/
package org.springframework.session.data.mongo;
import java.util.Optional;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
@@ -22,6 +24,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
* Utility class to extract principal name from {@code Authentication} object.
*
* @author Jakub Kubrynski
* @author Greg Turnquist
*/
final class AuthenticationParser {
@@ -35,13 +38,14 @@ final class AuthenticationParser {
* @param authentication Authentication object
* @return principal name
*/
static String extractName(Object authentication) {
static String extractName(Optional<Object> authentication) {
if (authentication != null) {
Expression expression = PARSER.parseExpression(NAME_EXPRESSION);
return expression.getValue(authentication, String.class);
}
return null;
return authentication
.map(auth -> {
Expression expression = PARSER.parseExpression(NAME_EXPRESSION);
return expression.getValue(auth, String.class);
})
.orElse(null);
}
private AuthenticationParser() {}

View File

@@ -40,6 +40,7 @@ import com.mongodb.util.JSON;
* {@code AbstractMongoSessionConverter} implementation using Jackson.
*
* @author Jakub Kubrynski
* @author Greg Turnquist
* @since 1.2
*/
public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter {
@@ -67,7 +68,7 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter
return Query.query(Criteria.where(PRINCIPAL_FIELD_NAME).is(indexValue));
}
return Query.query(Criteria.where(ATTRS_FIELD_NAME +
MongoExpiringSession.coverDot(indexName)).is(indexValue));
MongoSession.coverDot(indexName)).is(indexValue));
}
private ObjectMapper buildObjectMapper() {
@@ -87,7 +88,7 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter
}
@Override
protected DBObject convert(MongoExpiringSession source) {
protected DBObject convert(MongoSession source) {
try {
DBObject dbSession = (DBObject) JSON.parse(this.objectMapper.writeValueAsString(source));
@@ -100,12 +101,12 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter
}
@Override
protected MongoExpiringSession convert(Document source) {
protected MongoSession convert(Document source) {
String json = JSON.serialize(source);
try {
return this.objectMapper.readValue(json, MongoExpiringSession.class);
return this.objectMapper.readValue(json, MongoSession.class);
}
catch (IOException e) {
LOG.error("Error during Mongo Session deserialization", e);

View File

@@ -16,6 +16,8 @@
package org.springframework.session.data.mongo;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@@ -40,6 +42,7 @@ import com.mongodb.DBObject;
*
* @author Jakub Kubrynski
* @author Rob Winch
* @author Greg Turnquist
* @since 1.2
*/
public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
@@ -78,13 +81,13 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
}
@Override
protected DBObject convert(MongoExpiringSession session) {
protected DBObject convert(MongoSession session) {
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put(ID, session.getId());
basicDBObject.put(CREATION_TIME, session.getCreationTime());
basicDBObject.put(LAST_ACCESSED_TIME, session.getLastAccessedTime());
basicDBObject.put(MAX_INTERVAL, session.getMaxInactiveIntervalInSeconds());
basicDBObject.put(MAX_INTERVAL, session.getMaxInactiveInterval());
basicDBObject.put(PRINCIPAL_FIELD_NAME, extractPrincipal(session));
basicDBObject.put(EXPIRE_AT_FIELD_NAME, session.getExpireAt());
basicDBObject.put(ATTRIBUTES, serializeAttributes(session));
@@ -92,14 +95,33 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
}
@Override
protected MongoExpiringSession convert(Document sessionWrapper) {
protected MongoSession convert(Document sessionWrapper) {
MongoExpiringSession session = new MongoExpiringSession(
sessionWrapper.getString(ID), sessionWrapper.getInteger(MAX_INTERVAL));
Object maxInterval = sessionWrapper.get(MAX_INTERVAL);
Duration maxIntervalDuration = (maxInterval instanceof Duration)
? (Duration) maxInterval
: Duration.parse(maxInterval.toString());
MongoSession session = new MongoSession(
sessionWrapper.getString(ID), maxIntervalDuration.getSeconds());
Object creationTime = sessionWrapper.get(CREATION_TIME);
if (creationTime instanceof Instant) {
session.setCreationTime(((Instant) creationTime).toEpochMilli());
} else if (creationTime instanceof Date) {
session.setCreationTime(((Date) creationTime).getTime());
}
Object lastAccessedTime = sessionWrapper.get(LAST_ACCESSED_TIME);
if (lastAccessedTime instanceof Instant) {
session.setLastAccessedTime((Instant) lastAccessedTime);
} else if (lastAccessedTime instanceof Date) {
session.setLastAccessedTime(Instant.ofEpochMilli(((Date) lastAccessedTime).getTime()));
}
session.setCreationTime(sessionWrapper.getLong(CREATION_TIME));
session.setLastAccessedTime(sessionWrapper.getLong(LAST_ACCESSED_TIME));
session.setExpireAt((Date) sessionWrapper.get(EXPIRE_AT_FIELD_NAME));
deserializeAttributes(sessionWrapper, session);
return session;
@@ -110,7 +132,7 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
Map<String, Object> attributes = new HashMap<>();
for (String attrName : session.getAttributeNames()) {
attributes.put(attrName, session.getAttribute(attrName));
attributes.put(attrName, session.getAttribute(attrName).get());
}
return this.serializer.convert(attributes);

View File

@@ -16,6 +16,7 @@
package org.springframework.session.data.mongo;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -42,10 +43,11 @@ import com.mongodb.DBObject;
* done every minute.
*
* @author Jakub Kubrynski
* @author Greg Turnquist
* @since 1.2
*/
public class MongoOperationsSessionRepository
implements FindByIndexNameSessionRepository<MongoExpiringSession> {
implements FindByIndexNameSessionRepository<MongoSession> {
/**
* The default time period in seconds in which a session will expire.
@@ -69,24 +71,24 @@ public class MongoOperationsSessionRepository
this.mongoOperations = mongoOperations;
}
public MongoExpiringSession createSession() {
public MongoSession createSession() {
MongoExpiringSession session = new MongoExpiringSession();
MongoSession session = new MongoSession();
if (this.maxInactiveIntervalInSeconds != null) {
session.setMaxInactiveIntervalInSeconds(this.maxInactiveIntervalInSeconds);
session.setMaxInactiveInterval(Duration.ofSeconds(this.maxInactiveIntervalInSeconds));
}
return session;
}
public void save(MongoExpiringSession session) {
public void save(MongoSession session) {
DBObject sessionDbObject = convertToDBObject(session);
this.mongoOperations.save(sessionDbObject, this.collectionName);
}
public MongoExpiringSession getSession(String id) {
public MongoSession getSession(String id) {
Document sessionWrapper = findSession(id);
@@ -94,7 +96,7 @@ public class MongoOperationsSessionRepository
return null;
}
MongoExpiringSession session = convertToSession(sessionWrapper);
MongoSession session = convertToSession(sessionWrapper);
if (session.isExpired()) {
delete(id);
@@ -113,9 +115,9 @@ public class MongoOperationsSessionRepository
* @param indexValue the value of the index to search for.
* @return sessions map
*/
public Map<String, MongoExpiringSession> findByIndexNameAndIndexValue(String indexName, String indexValue) {
public Map<String, MongoSession> findByIndexNameAndIndexValue(String indexName, String indexValue) {
HashMap<String, MongoExpiringSession> result = new HashMap<String, MongoExpiringSession>();
HashMap<String, MongoSession> result = new HashMap<String, MongoSession>();
Query query = this.mongoSessionConverter.getQueryForIndex(indexName, indexValue);
@@ -126,7 +128,7 @@ public class MongoOperationsSessionRepository
List<Document> mapSessions = this.mongoOperations.find(query, Document.class, this.collectionName);
for (Document dbSession : mapSessions) {
MongoExpiringSession mapSession = convertToSession(dbSession);
MongoSession mapSession = convertToSession(dbSession);
result.put(mapSession.getId(), mapSession);
}
@@ -148,17 +150,17 @@ public class MongoOperationsSessionRepository
return this.mongoOperations.findById(id, Document.class, this.collectionName);
}
MongoExpiringSession convertToSession(Document session) {
MongoSession convertToSession(Document session) {
return (MongoExpiringSession) this.mongoSessionConverter.convert(session,
return (MongoSession) this.mongoSessionConverter.convert(session,
TypeDescriptor.valueOf(Document.class),
TypeDescriptor.valueOf(MongoExpiringSession.class));
TypeDescriptor.valueOf(MongoSession.class));
}
DBObject convertToDBObject(MongoExpiringSession session) {
DBObject convertToDBObject(MongoSession session) {
return (DBObject) this.mongoSessionConverter.convert(session,
TypeDescriptor.valueOf(MongoExpiringSession.class),
TypeDescriptor.valueOf(MongoSession.class),
TypeDescriptor.valueOf(DBObject.class));
}

View File

@@ -15,23 +15,26 @@
*/
package org.springframework.session.data.mongo;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.springframework.session.ExpiringSession;
import org.springframework.session.Session;
/**
* Session object providing additional information about the datetime of expiration.
*
* @author Jakub Kubrynski
* @author Greg Turnquist
* @since 1.2
*/
public class MongoExpiringSession implements ExpiringSession {
public class MongoSession implements Session {
/**
* Mongo doesn't support {@literal dot} in field names. We replace it with a very rarely used character
@@ -39,25 +42,25 @@ public class MongoExpiringSession implements ExpiringSession {
private static final char DOT_COVER_CHAR = '\uF607';
private final String id;
private long created = System.currentTimeMillis();
private long accessed;
private int interval;
private long createdMillis = System.currentTimeMillis();
private long accessedMillis;
private long intervalSeconds;
private Date expireAt;
private Map<String, Object> attrs = new HashMap<String, Object>();
public MongoExpiringSession() {
public MongoSession() {
this(MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL);
}
public MongoExpiringSession(int maxInactiveIntervalInSeconds) {
public MongoSession(long maxInactiveIntervalInSeconds) {
this(UUID.randomUUID().toString(), maxInactiveIntervalInSeconds);
}
public MongoExpiringSession(String id, int maxInactiveIntervalInSeconds) {
public MongoSession(String id, long maxInactiveIntervalInSeconds) {
this.id = id;
this.interval = maxInactiveIntervalInSeconds;
setLastAccessedTime(this.created);
this.intervalSeconds = maxInactiveIntervalInSeconds;
setLastAccessedTime(Instant.ofEpochMilli(this.createdMillis));
}
public String getId() {
@@ -65,8 +68,8 @@ public class MongoExpiringSession implements ExpiringSession {
}
@SuppressWarnings("unchecked")
public <T> T getAttribute(String attributeName) {
return (T) this.attrs.get(coverDot(attributeName));
public <T> Optional<T> getAttribute(String attributeName) {
return Optional.ofNullable((T) this.attrs.get(coverDot(attributeName)));
}
public Set<String> getAttributeNames() {
@@ -93,34 +96,34 @@ public class MongoExpiringSession implements ExpiringSession {
this.attrs.remove(coverDot(attributeName));
}
public long getCreationTime() {
return this.created;
public Instant getCreationTime() {
return Instant.ofEpochMilli(this.createdMillis);
}
public void setCreationTime(long created) {
this.created = created;
this.createdMillis = created;
}
public void setLastAccessedTime(long lastAccessedTime) {
public void setLastAccessedTime(Instant lastAccessedTime) {
this.accessed = lastAccessedTime;
this.expireAt = new Date(lastAccessedTime + TimeUnit.SECONDS.toMillis(this.interval));
this.accessedMillis = lastAccessedTime.toEpochMilli();
this.expireAt = Date.from(lastAccessedTime.plus(Duration.ofSeconds(this.intervalSeconds)));
}
public long getLastAccessedTime() {
return this.accessed;
public Instant getLastAccessedTime() {
return Instant.ofEpochMilli(this.accessedMillis);
}
public void setMaxInactiveIntervalInSeconds(int interval) {
this.interval = interval;
public void setMaxInactiveInterval(Duration interval) {
this.intervalSeconds = interval.getSeconds();
}
public int getMaxInactiveIntervalInSeconds() {
return this.interval;
public Duration getMaxInactiveInterval() {
return Duration.ofSeconds(this.intervalSeconds);
}
public boolean isExpired() {
return this.interval >= 0 && new Date().after(this.expireAt);
return this.intervalSeconds >= 0 && new Date().after(this.expireAt);
}
public Date getExpireAt() {
@@ -149,7 +152,7 @@ public class MongoExpiringSession implements ExpiringSession {
return false;
}
MongoExpiringSession that = (MongoExpiringSession) o;
MongoSession that = (MongoSession) o;
return this.id.equals(that.id);
}

View File

@@ -17,6 +17,8 @@ package org.springframework.session.data.mongo;
import static org.assertj.core.api.Assertions.*;
import java.util.Optional;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -24,6 +26,7 @@ import org.springframework.security.core.context.SecurityContextImpl;
/**
* @author Jakub Kubrynski
* @author Greg Turnquist
*/
public class AuthenticationParserTest {
@@ -36,7 +39,7 @@ public class AuthenticationParserTest {
context.setAuthentication(new UsernamePasswordAuthenticationToken(principalName, null));
// when
String extractedName = AuthenticationParser.extractName(context);
String extractedName = AuthenticationParser.extractName(Optional.ofNullable(context));
// then
assertThat(extractedName).isEqualTo(principalName);

View File

@@ -25,6 +25,7 @@ import com.mongodb.DBObject;
/**
* @author Jakub Kubrynski
* @author Greg Turnquist
*/
public class JacksonMongoSessionConverterTest {
@@ -34,7 +35,7 @@ public class JacksonMongoSessionConverterTest {
public void shouldSaveIdField() throws Exception {
//given
MongoExpiringSession session = new MongoExpiringSession();
MongoSession session = new MongoSession();
//when
DBObject convert = this.sut.convert(session);

View File

@@ -24,7 +24,6 @@ import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import com.mongodb.DBObject;
@@ -32,6 +31,7 @@ import com.mongodb.DBObject;
/**
* @author Jakub Kubrynski
* @author Rob Winch
* @author Greg Turnquist
*/
public class JdkMongoSessionConverterTest {
@@ -51,12 +51,12 @@ public class JdkMongoSessionConverterTest {
public void verifyRoundTripSerialization() throws Exception {
// given
MongoExpiringSession toSerialize = new MongoExpiringSession();
MongoSession toSerialize = new MongoSession();
toSerialize.setAttribute("username", "john_the_springer");
// when
DBObject dbObject = convertToDBObject(toSerialize);
ExpiringSession deserialized = convertToSession(dbObject);
MongoSession deserialized = convertToSession(dbObject);
// then
assertThat(deserialized).isEqualToComparingFieldByField(toSerialize);
@@ -66,7 +66,7 @@ public class JdkMongoSessionConverterTest {
public void shouldExtractPrincipalNameFromAttributes() throws Exception {
// given
MongoExpiringSession toSerialize = new MongoExpiringSession();
MongoSession toSerialize = new MongoSession();
String principalName = "john_the_springer";
toSerialize.setAttribute(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
@@ -83,7 +83,7 @@ public class JdkMongoSessionConverterTest {
public void shouldExtractPrincipalNameFromAuthentication() throws Exception {
// given
MongoExpiringSession toSerialize = new MongoExpiringSession();
MongoSession toSerialize = new MongoSession();
String principalName = "john_the_springer";
SecurityContextImpl context = new SecurityContextImpl();
context.setAuthentication(
@@ -97,15 +97,15 @@ public class JdkMongoSessionConverterTest {
assertThat(dbObject.get("principal")).isEqualTo(principalName);
}
MongoExpiringSession convertToSession(DBObject session) {
return (MongoExpiringSession) this.sut.convert(session,
MongoSession convertToSession(DBObject session) {
return (MongoSession) this.sut.convert(session,
TypeDescriptor.valueOf(DBObject.class),
TypeDescriptor.valueOf(MongoExpiringSession.class));
TypeDescriptor.valueOf(MongoSession.class));
}
DBObject convertToDBObject(MongoExpiringSession session) {
DBObject convertToDBObject(MongoSession session) {
return (DBObject) this.sut.convert(session,
TypeDescriptor.valueOf(MongoExpiringSession.class),
TypeDescriptor.valueOf(MongoSession.class),
TypeDescriptor.valueOf(DBObject.class));
}
}

View File

@@ -38,7 +38,6 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import com.mongodb.BasicDBObject;
@@ -49,6 +48,7 @@ import com.mongodb.DBObject;
*
* @author Jakub Kubrynski
* @author Vedran Pavic
* @author Greg Turnquist
*/
@RunWith(MockitoJUnitRunner.class)
public class MongoOperationsSessionRepositoryTest {
@@ -70,11 +70,11 @@ public class MongoOperationsSessionRepositoryTest {
@Test
public void shouldCreateSession() throws Exception {
// when
ExpiringSession session = this.repository.createSession();
MongoSession session = this.repository.createSession();
// then
assertThat(session.getId()).isNotEmpty();
assertThat(session.getMaxInactiveIntervalInSeconds())
assertThat(session.getMaxInactiveInterval().getSeconds())
.isEqualTo(MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL);
}
@@ -82,22 +82,22 @@ public class MongoOperationsSessionRepositoryTest {
public void shouldCreateSessionWhenMaxInactiveIntervalNotDefined() throws Exception {
// when
this.repository.setMaxInactiveIntervalInSeconds(null);
ExpiringSession session = this.repository.createSession();
MongoSession session = this.repository.createSession();
// then
assertThat(session.getId()).isNotEmpty();
assertThat(session.getMaxInactiveIntervalInSeconds())
assertThat(session.getMaxInactiveInterval().getSeconds())
.isEqualTo(MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL);
}
@Test
public void shouldSaveSession() throws Exception {
// given
MongoExpiringSession session = new MongoExpiringSession();
MongoSession session = new MongoSession();
BasicDBObject dbSession = new BasicDBObject();
given(this.converter.convert(session,
TypeDescriptor.valueOf(MongoExpiringSession.class),
TypeDescriptor.valueOf(MongoSession.class),
TypeDescriptor.valueOf(DBObject.class))).willReturn(dbSession);
// when
this.repository.save(session);
@@ -115,13 +115,13 @@ public class MongoOperationsSessionRepositoryTest {
given(this.mongoOperations.findById(sessionId, Document.class,
MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(sessionDocument);
MongoExpiringSession session = new MongoExpiringSession();
MongoSession session = new MongoSession();
given(this.converter.convert(sessionDocument, TypeDescriptor.valueOf(Document.class),
TypeDescriptor.valueOf(MongoExpiringSession.class))).willReturn(session);
TypeDescriptor.valueOf(MongoSession.class))).willReturn(session);
// when
ExpiringSession retrievedSession = this.repository.getSession(sessionId);
MongoSession retrievedSession = this.repository.getSession(sessionId);
// then
assertThat(retrievedSession).isEqualTo(session);
@@ -136,11 +136,11 @@ public class MongoOperationsSessionRepositoryTest {
given(this.mongoOperations.findById(sessionId, Document.class,
MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(sessionDocument);
MongoExpiringSession session = mock(MongoExpiringSession.class);
MongoSession session = mock(MongoSession.class);
given(session.isExpired()).willReturn(true);
given(this.converter.convert(sessionDocument, TypeDescriptor.valueOf(Document.class),
TypeDescriptor.valueOf(MongoExpiringSession.class))).willReturn(session);
TypeDescriptor.valueOf(MongoSession.class))).willReturn(session);
// when
this.repository.getSession(sessionId);
@@ -182,13 +182,13 @@ public class MongoOperationsSessionRepositoryTest {
String sessionId = UUID.randomUUID().toString();
MongoExpiringSession session = new MongoExpiringSession(sessionId, 1800);
MongoSession session = new MongoSession(sessionId, 1800);
given(this.converter.convert(document, TypeDescriptor.valueOf(Document.class),
TypeDescriptor.valueOf(MongoExpiringSession.class))).willReturn(session);
TypeDescriptor.valueOf(MongoSession.class))).willReturn(session);
// when
Map<String, MongoExpiringSession> sessionsMap =
Map<String, MongoSession> sessionsMap =
this.repository.findByIndexNameAndIndexValue(principalNameIndexName, "john");
// then
@@ -202,7 +202,7 @@ public class MongoOperationsSessionRepositoryTest {
String index = "some_not_supported_index_name";
// when
Map<String, MongoExpiringSession> sessionsMap = this.repository
Map<String, MongoSession> sessionsMap = this.repository
.findByIndexNameAndIndexValue(index, "some_value");
// then

View File

@@ -16,20 +16,24 @@
package org.springframework.session.data.mongo;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.time.Instant;
import org.junit.Test;
/**
* @author Rob Winch
* @author Greg Turnquist
*/
public class MongoExpiringSessionTest {
public class MongoSessionTest {
@Test
public void isExpiredWhenIntervalNegativeThenFalse() {
MongoExpiringSession session = new MongoExpiringSession();
session.setMaxInactiveIntervalInSeconds(-1);
session.setLastAccessedTime(0L);
MongoSession session = new MongoSession();
session.setMaxInactiveInterval(Duration.ofSeconds(-1));
session.setLastAccessedTime(Instant.ofEpochMilli(0L));
assertThat(session.isExpired()).isFalse();
}

View File

@@ -19,9 +19,11 @@ import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.net.UnknownHostException;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import de.flapdoodle.embed.mongo.MongodExecutable;
import org.junit.Test;
@@ -38,8 +40,8 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.data.mongo.MongoExpiringSession;
import org.springframework.session.data.mongo.MongoOperationsSessionRepository;
import org.springframework.session.data.mongo.MongoSession;
import org.springframework.util.SocketUtils;
import com.mongodb.MongoClient;
@@ -49,6 +51,7 @@ import com.mongodb.MongoClient;
*
* @author Jakub Kubrynski
* @author Vedran Pavic
* @author Greg Turnquist
*/
abstract public class AbstractMongoRepositoryITest extends AbstractITest {
@@ -63,7 +66,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
public void saves() throws InterruptedException {
String username = "saves-" + System.currentTimeMillis();
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
String expectedAttributeName = "a";
String expectedAttributeValue = "b";
toSave.setAttribute(expectedAttributeName, expectedAttributeValue);
@@ -92,7 +95,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
@Test
public void putAllOnSingleAttrDoesNotRemoveOld() {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute("a", "b");
this.repository.save(toSave);
@@ -105,8 +108,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
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());
}
@@ -115,12 +118,12 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
public void findByPrincipalName() throws Exception {
String principalName = "findByPrincipalName" + UUID.randomUUID();
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, principalName);
assertThat(findByPrincipalName).hasSize(1);
@@ -140,7 +143,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
String principalName = "findByPrincipalNameNoPrincipalNameChange"
+ UUID.randomUUID();
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
this.repository.save(toSave);
@@ -148,7 +151,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
toSave.setAttribute("other", "value");
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, principalName);
assertThat(findByPrincipalName).hasSize(1);
@@ -160,7 +163,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
String principalName = "findByPrincipalNameNoPrincipalNameChangeReload"
+ UUID.randomUUID();
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
this.repository.save(toSave);
@@ -170,7 +173,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
toSave.setAttribute("other", "value");
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, principalName);
assertThat(findByPrincipalName).hasSize(1);
@@ -181,7 +184,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
public void findByDeletedPrincipalName() throws Exception {
String principalName = "findByDeletedPrincipalName" + UUID.randomUUID();
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
this.repository.save(toSave);
@@ -189,7 +192,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
toSave.setAttribute(INDEX_NAME, null);
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, principalName);
assertThat(findByPrincipalName).isEmpty();
@@ -200,7 +203,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
String principalName = "findByChangedPrincipalName" + UUID.randomUUID();
String principalNameChanged = "findByChangedPrincipalName" + UUID.randomUUID();
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
this.repository.save(toSave);
@@ -208,7 +211,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
toSave.setAttribute(INDEX_NAME, principalNameChanged);
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, principalName);
assertThat(findByPrincipalName).isEmpty();
@@ -223,16 +226,16 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
public void findByDeletedPrincipalNameReload() throws Exception {
String principalName = "findByDeletedPrincipalName" + UUID.randomUUID();
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
this.repository.save(toSave);
MongoExpiringSession getSession = this.repository.getSession(toSave.getId());
MongoSession getSession = this.repository.getSession(toSave.getId());
getSession.setAttribute(INDEX_NAME, null);
this.repository.save(getSession);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, principalName);
assertThat(findByPrincipalName).isEmpty();
@@ -243,17 +246,17 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
String principalName = "findByChangedPrincipalName" + UUID.randomUUID();
String principalNameChanged = "findByChangedPrincipalName" + UUID.randomUUID();
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
this.repository.save(toSave);
MongoExpiringSession getSession = this.repository.getSession(toSave.getId());
MongoSession getSession = this.repository.getSession(toSave.getId());
getSession.setAttribute(INDEX_NAME, principalNameChanged);
this.repository.save(getSession);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, principalName);
assertThat(findByPrincipalName).isEmpty();
@@ -267,12 +270,12 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
@Test
public void findBySecurityPrincipalName() throws Exception {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName());
assertThat(findByPrincipalName).hasSize(1);
@@ -290,7 +293,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
@Test
public void findByPrincipalNameNoSecurityPrincipalNameChange() throws Exception {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
this.repository.save(toSave);
@@ -298,7 +301,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
toSave.setAttribute("other", "value");
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName());
assertThat(findByPrincipalName).hasSize(1);
@@ -308,7 +311,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
@Test
public void findByDeletedSecurityPrincipalName() throws Exception {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
this.repository.save(toSave);
@@ -316,7 +319,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
toSave.setAttribute(SPRING_SECURITY_CONTEXT, null);
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName());
assertThat(findByPrincipalName).isEmpty();
@@ -325,7 +328,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
@Test
public void findByChangedSecurityPrincipalName() throws Exception {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
this.repository.save(toSave);
@@ -333,7 +336,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.changedContext);
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName());
assertThat(findByPrincipalName).isEmpty();
@@ -347,17 +350,17 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
@Test
public void findByChangedSecurityPrincipalNameReload() throws Exception {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
this.repository.save(toSave);
MongoExpiringSession getSession = this.repository.getSession(toSave.getId());
MongoSession getSession = this.repository.getSession(toSave.getId());
getSession.setAttribute(SPRING_SECURITY_CONTEXT, this.changedContext);
this.repository.save(getSession);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName());
assertThat(findByPrincipalName).isEmpty();
@@ -372,14 +375,13 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
public void loadExpiredSession() throws Exception {
// given
MongoExpiringSession expiredSession = this.repository.createSession();
long thirtyOneMinutesAgo = System.currentTimeMillis()
- TimeUnit.MINUTES.toMillis(31);
MongoSession expiredSession = this.repository.createSession();
Instant thirtyOneMinutesAgo = Instant.ofEpochMilli(System.currentTimeMillis()).minus(Duration.ofMinutes(31));
expiredSession.setLastAccessedTime(thirtyOneMinutesAgo);
this.repository.save(expiredSession);
// then
MongoExpiringSession expiredSessionFromDb = this.repository
MongoSession expiredSessionFromDb = this.repository
.getSession(expiredSession.getId());
assertThat(expiredSessionFromDb).isNull();
}

View File

@@ -28,7 +28,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.data.geo.GeoModule;
import org.springframework.session.data.mongo.AbstractMongoSessionConverter;
import org.springframework.session.data.mongo.JacksonMongoSessionConverter;
import org.springframework.session.data.mongo.MongoExpiringSession;
import org.springframework.session.data.mongo.MongoSession;
import org.springframework.session.data.mongo.config.annotation.web.http.EnableMongoHttpSession;
import org.springframework.test.context.ContextConfiguration;
@@ -40,6 +40,7 @@ import com.fasterxml.jackson.databind.Module;
*
* @author Jakub Kubrynski
* @author Vedran Pavic
* @author Greg Turnquist
*/
@ContextConfiguration
public class MongoRepositoryJacksonITest extends AbstractMongoRepositoryITest {
@@ -47,13 +48,13 @@ public class MongoRepositoryJacksonITest extends AbstractMongoRepositoryITest {
@Test
public void findByCustomIndex() throws Exception {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
String cartId = "cart-" + UUID.randomUUID();
toSave.setAttribute("cartId", cartId);
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByCartId = this.repository
Map<String, MongoSession> findByCartId = this.repository
.findByIndexNameAndIndexValue("cartId", cartId);
assertThat(findByCartId).hasSize(1);

View File

@@ -25,7 +25,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.mongo.AbstractMongoSessionConverter;
import org.springframework.session.data.mongo.JdkMongoSessionConverter;
import org.springframework.session.data.mongo.MongoExpiringSession;
import org.springframework.session.data.mongo.MongoSession;
import org.springframework.session.data.mongo.config.annotation.web.http.EnableMongoHttpSession;
import org.springframework.test.context.ContextConfiguration;
@@ -35,6 +35,7 @@ import org.springframework.test.context.ContextConfiguration;
*
* @author Jakub Kubrynski
* @author Vedran Pavic
* @author Greg Turnquist
*/
@ContextConfiguration
public class MongoRepositoryJdkSerializationITest extends AbstractMongoRepositoryITest {
@@ -42,16 +43,16 @@ public class MongoRepositoryJdkSerializationITest extends AbstractMongoRepositor
@Test
public void findByDeletedSecurityPrincipalNameReload() throws Exception {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
this.repository.save(toSave);
MongoExpiringSession getSession = this.repository.getSession(toSave.getId());
MongoSession getSession = this.repository.getSession(toSave.getId());
getSession.setAttribute(INDEX_NAME, null);
this.repository.save(getSession);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName());
assertThat(findByPrincipalName).isEmpty();
@@ -60,7 +61,7 @@ public class MongoRepositoryJdkSerializationITest extends AbstractMongoRepositor
@Test
public void findByPrincipalNameNoSecurityPrincipalNameChangeReload() throws Exception {
MongoExpiringSession toSave = this.repository.createSession();
MongoSession toSave = this.repository.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
this.repository.save(toSave);
@@ -70,7 +71,7 @@ public class MongoRepositoryJdkSerializationITest extends AbstractMongoRepositor
toSave.setAttribute("other", "value");
this.repository.save(toSave);
Map<String, MongoExpiringSession> findByPrincipalName = this.repository
Map<String, MongoSession> findByPrincipalName = this.repository
.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName());
assertThat(findByPrincipalName).hasSize(1);