From 2fdf499411e5b3a2396fa175d849af0572e46093 Mon Sep 17 00:00:00 2001 From: Greg Turnquist Date: Tue, 12 Mar 2019 10:31:59 -0500 Subject: [PATCH] Polishing. Apply the formatting plugin to the entire code base. From there, polish up specific sections of code for readability. --- .../mongo/AbstractMongoSessionConverter.java | 27 ++--- .../data/mongo/AuthenticationParser.java | 4 +- .../mongo/JacksonMongoSessionConverter.java | 35 +++--- .../data/mongo/JdkMongoSessionConverter.java | 31 +++--- .../MongoOperationsSessionRepository.java | 52 ++++----- .../session/data/mongo/MongoSession.java | 34 +++--- .../session/data/mongo/MongoSessionUtils.java | 11 +- ...ctiveMongoOperationsSessionRepository.java | 67 +++++------ .../web/http/EnableMongoHttpSession.java | 12 +- .../http/MongoHttpSessionConfiguration.java | 15 ++- .../ReactiveMongoWebSessionConfiguration.java | 23 ++-- .../AbstractMongoSessionConverterTest.java | 27 ++--- .../data/mongo/AuthenticationParserTest.java | 1 - .../JacksonMongoSessionConverterTest.java | 14 +-- .../MongoOperationsSessionRepositoryTest.java | 59 +++++----- .../session/data/mongo/MongoSessionTest.java | 1 + ...eMongoOperationsSessionRepositoryTest.java | 105 ++++++++---------- .../MongoHttpSessionConfigurationTest.java | 21 ++-- ...ctiveMongoWebSessionConfigurationTest.java | 49 ++++---- .../integration/AbstractClassLoaderTest.java | 34 +++--- .../data/mongo/integration/AbstractITest.java | 14 +-- .../AbstractMongoRepositoryITest.java | 94 +++++++--------- .../mongo/integration/MongoITestUtils.java | 12 +- .../MongoRepositoryJacksonITest.java | 3 +- .../MongoRepositoryJdkSerializationITest.java | 8 +- .../integration/SessionEventRegistry.java | 8 +- .../TraditionalConfigurationTest.java | 5 +- 27 files changed, 349 insertions(+), 417 deletions(-) diff --git a/src/main/java/org/springframework/session/data/mongo/AbstractMongoSessionConverter.java b/src/main/java/org/springframework/session/data/mongo/AbstractMongoSessionConverter.java index 40d29d3..5ebf40e 100644 --- a/src/main/java/org/springframework/session/data/mongo/AbstractMongoSessionConverter.java +++ b/src/main/java/org/springframework/session/data/mongo/AbstractMongoSessionConverter.java @@ -35,9 +35,8 @@ import org.springframework.session.Session; import com.mongodb.DBObject; /** - * Base class for serializing and deserializing session objects. To create custom - * serializer you have to implement this interface and simply register your class as a - * bean. + * Base class for serializing and deserializing session objects. To create custom serializer you have to implement this + * interface and simply register your class as a bean. * * @author Jakub Kubrynski * @author Greg Turnquist @@ -45,14 +44,13 @@ import com.mongodb.DBObject; */ public abstract class AbstractMongoSessionConverter implements GenericConverter { - private static final Log LOG = LogFactory.getLog(AbstractMongoSessionConverter.class); - static final String EXPIRE_AT_FIELD_NAME = "expireAt"; - + private static final Log LOG = LogFactory.getLog(AbstractMongoSessionConverter.class); private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; /** * Returns query to be executed to return sessions based on a particular index. + * * @param indexName name of the index * @param indexValue value to query against * @return built query or null if indexName is not supported @@ -60,12 +58,10 @@ public abstract class AbstractMongoSessionConverter implements GenericConverter protected abstract Query getQueryForIndex(String indexName, Object indexValue); /** - * Method ensures that there is a TTL index on {@literal expireAt} field. It's has - * {@literal expireAfterSeconds} set to zero seconds, so the expiration time is - * controlled by the application. - * - * It can be extended in custom converters when there is a need for creating - * additional custom indexes. + * Method ensures that there is a TTL index on {@literal expireAt} field. It's has {@literal expireAfterSeconds} set + * to zero seconds, so the expiration time is controlled by the application. It can be extended in custom converters + * when there is a need for creating additional custom indexes. + * * @param sessionCollectionIndexes {@link IndexOperations} to use */ protected void ensureIndexes(IndexOperations sessionCollectionIndexes) { @@ -79,7 +75,7 @@ public abstract class AbstractMongoSessionConverter implements GenericConverter LOG.info("Creating TTL index on field " + EXPIRE_AT_FIELD_NAME); sessionCollectionIndexes - .ensureIndex(new Index(EXPIRE_AT_FIELD_NAME, Sort.Direction.ASC).named(EXPIRE_AT_FIELD_NAME).expire(0)); + .ensureIndex(new Index(EXPIRE_AT_FIELD_NAME, Sort.Direction.ASC).named(EXPIRE_AT_FIELD_NAME).expire(0)); } protected String extractPrincipal(Session expiringSession) { @@ -95,13 +91,12 @@ public abstract class AbstractMongoSessionConverter implements GenericConverter public Set getConvertibleTypes() { - return Collections.singleton( - new ConvertiblePair(DBObject.class, MongoSession.class)); + return Collections.singleton(new ConvertiblePair(DBObject.class, MongoSession.class)); } @SuppressWarnings("unchecked") public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - + if (source == null) { return null; } diff --git a/src/main/java/org/springframework/session/data/mongo/AuthenticationParser.java b/src/main/java/org/springframework/session/data/mongo/AuthenticationParser.java index 816fb04..0ef73de 100644 --- a/src/main/java/org/springframework/session/data/mongo/AuthenticationParser.java +++ b/src/main/java/org/springframework/session/data/mongo/AuthenticationParser.java @@ -30,6 +30,8 @@ final class AuthenticationParser { private static final SpelExpressionParser PARSER = new SpelExpressionParser(); + private AuthenticationParser() {} + /** * Extracts principal name from authentication. * @@ -46,6 +48,4 @@ final class AuthenticationParser { return expression.getValue(authentication, String.class); } - - private AuthenticationParser() {} } diff --git a/src/main/java/org/springframework/session/data/mongo/JacksonMongoSessionConverter.java b/src/main/java/org/springframework/session/data/mongo/JacksonMongoSessionConverter.java index e0acbf2..9a9d209 100644 --- a/src/main/java/org/springframework/session/data/mongo/JacksonMongoSessionConverter.java +++ b/src/main/java/org/springframework/session/data/mongo/JacksonMongoSessionConverter.java @@ -77,8 +77,7 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Query.query(Criteria.where(PRINCIPAL_FIELD_NAME).is(indexValue)); } else { - return Query.query(Criteria.where(ATTRS_FIELD_NAME + - MongoSession.coverDot(indexName)).is(indexValue)); + return Query.query(Criteria.where(ATTRS_FIELD_NAME + MongoSession.coverDot(indexName)).is(indexValue)); } } @@ -102,20 +101,6 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter return objectMapper; } - /** - * Used to whitelist {@link MongoSession} for {@link SecurityJackson2Modules}. - */ - private static class MongoSessionMixin { - // Nothing special - } - - /** - * Used to whitelist {@link HashMap} for {@link SecurityJackson2Modules}. - */ - private static class HashMapMixin { - // Nothing special - } - @Override protected DBObject convert(MongoSession source) { @@ -132,7 +117,7 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter protected MongoSession convert(Document source) { String json = source.toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build()); - + try { return this.objectMapper.readValue(json, MongoSession.class); } catch (IOException e) { @@ -141,11 +126,25 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter } } + /** + * Used to whitelist {@link MongoSession} for {@link SecurityJackson2Modules}. + */ + private static class MongoSessionMixin { + // Nothing special + } + + /** + * Used to whitelist {@link HashMap} for {@link SecurityJackson2Modules}. + */ + private static class HashMapMixin { + // Nothing special + } + private static class MongoIdNamingStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase { @Override public String translate(String propertyName) { - + switch (propertyName) { case "id": return "_id"; diff --git a/src/main/java/org/springframework/session/data/mongo/JdkMongoSessionConverter.java b/src/main/java/org/springframework/session/data/mongo/JdkMongoSessionConverter.java index 09187bb..96be252 100644 --- a/src/main/java/org/springframework/session/data/mongo/JdkMongoSessionConverter.java +++ b/src/main/java/org/springframework/session/data/mongo/JdkMongoSessionConverter.java @@ -24,7 +24,6 @@ import java.util.Map; import org.bson.Document; import org.bson.types.Binary; - import org.springframework.core.convert.converter.Converter; import org.springframework.core.serializer.support.DeserializingConverter; import org.springframework.core.serializer.support.SerializingConverter; @@ -63,8 +62,9 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter { this(new SerializingConverter(), new DeserializingConverter(), maxInactiveInterval); } - public JdkMongoSessionConverter(Converter serializer, - Converter deserializer, Duration maxInactiveInterval) { + public JdkMongoSessionConverter(Converter serializer, Converter deserializer, + Duration maxInactiveInterval) { + Assert.notNull(serializer, "serializer cannot be null"); Assert.notNull(deserializer, "deserializer cannot be null"); Assert.notNull(maxInactiveInterval, "maxInactiveInterval cannot be null"); @@ -76,8 +76,7 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter { @Override public Query getQueryForIndex(String indexName, Object indexValue) { - if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME - .equals(indexName)) { + if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Query.query(Criteria.where(PRINCIPAL_FIELD_NAME).is(indexValue)); } else { return null; @@ -88,7 +87,7 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter { 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()); @@ -105,12 +104,10 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter { Object maxInterval = sessionWrapper.getOrDefault(MAX_INTERVAL, this.maxInactiveInterval); - Duration maxIntervalDuration = (maxInterval instanceof Duration) - ? (Duration) maxInterval - : Duration.parse(maxInterval.toString()); + Duration maxIntervalDuration = (maxInterval instanceof Duration) ? (Duration) maxInterval + : Duration.parse(maxInterval.toString()); - MongoSession session = new MongoSession( - sessionWrapper.getString(ID), maxIntervalDuration.getSeconds()); + MongoSession session = new MongoSession(sessionWrapper.getString(ID), maxIntervalDuration.getSeconds()); Object creationTime = sessionWrapper.get(CREATION_TIME); if (creationTime instanceof Instant) { @@ -127,7 +124,7 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter { } session.setExpireAt((Date) sessionWrapper.get(EXPIRE_AT_FIELD_NAME)); - + deserializeAttributes(sessionWrapper, session); return session; @@ -140,20 +137,20 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter { for (String attrName : session.getAttributeNames()) { attributes.put(attrName, session.getAttribute(attrName)); } - + return this.serializer.convert(attributes); } @SuppressWarnings("unchecked") private void deserializeAttributes(Document sessionWrapper, Session session) { - + Object sessionAttributes = sessionWrapper.get(ATTRIBUTES); - byte[] attributesBytes = (sessionAttributes instanceof Binary - ? ((Binary) sessionAttributes).getData() : (byte[]) sessionAttributes); + byte[] attributesBytes = (sessionAttributes instanceof Binary ? ((Binary) sessionAttributes).getData() + : (byte[]) sessionAttributes); Map attributes = (Map) this.deserializer.convert(attributesBytes); - + for (Map.Entry entry : attributes.entrySet()) { session.setAttribute(entry.getKey(), entry.getValue()); } diff --git a/src/main/java/org/springframework/session/data/mongo/MongoOperationsSessionRepository.java b/src/main/java/org/springframework/session/data/mongo/MongoOperationsSessionRepository.java index 3d802c7..f082cea 100644 --- a/src/main/java/org/springframework/session/data/mongo/MongoOperationsSessionRepository.java +++ b/src/main/java/org/springframework/session/data/mongo/MongoOperationsSessionRepository.java @@ -41,12 +41,9 @@ import org.springframework.session.events.SessionDeletedEvent; import org.springframework.session.events.SessionExpiredEvent; /** - * Session repository implementation which stores sessions in Mongo. Uses - * {@link AbstractMongoSessionConverter} to transform session objects from/to native Mongo - * representation ({@code DBObject}). - * - * Repository is also responsible for removing expired sessions from database. Cleanup is - * done every minute. + * Session repository implementation which stores sessions in Mongo. Uses {@link AbstractMongoSessionConverter} to + * transform session objects from/to native Mongo representation ({@code DBObject}). Repository is also responsible for + * removing expired sessions from database. Cleanup is done every minute. * * @author Jakub Kubrynski * @author Greg Turnquist @@ -55,24 +52,21 @@ import org.springframework.session.events.SessionExpiredEvent; public class MongoOperationsSessionRepository implements FindByIndexNameSessionRepository, ApplicationEventPublisherAware, InitializingBean { - private static final Logger logger = LoggerFactory.getLogger(MongoOperationsSessionRepository.class); - /** * The default time period in seconds in which a session will expire. */ public static final int DEFAULT_INACTIVE_INTERVAL = 1800; - /** * the default collection name for storing session. */ public static final String DEFAULT_COLLECTION_NAME = "sessions"; - + private static final Logger logger = LoggerFactory.getLogger(MongoOperationsSessionRepository.class); private final MongoOperations mongoOperations; @Setter private Integer maxInactiveIntervalInSeconds = DEFAULT_INACTIVE_INTERVAL; @Setter private String collectionName = DEFAULT_COLLECTION_NAME; @Setter private AbstractMongoSessionConverter mongoSessionConverter = new JdkMongoSessionConverter( - Duration.ofSeconds(this.maxInactiveIntervalInSeconds)); + Duration.ofSeconds(this.maxInactiveIntervalInSeconds)); private ApplicationEventPublisher eventPublisher; public MongoOperationsSessionRepository(MongoOperations mongoOperations) { @@ -113,19 +107,17 @@ public class MongoOperationsSessionRepository publishEvent(new SessionExpiredEvent(this, session)); deleteById(id); - + return null; } - + return session; } /** - * Currently this repository allows only querying against - * {@code PRINCIPAL_NAME_INDEX_NAME}. + * Currently this repository allows only querying against {@code PRINCIPAL_NAME_INDEX_NAME}. * - * @param indexName the name if the index (i.e. - * {@link FindByIndexNameSessionRepository#PRINCIPAL_NAME_INDEX_NAME}) + * @param indexName the name if the index (i.e. {@link FindByIndexNameSessionRepository#PRINCIPAL_NAME_INDEX_NAME}) * @param indexValue the value of the index to search for. * @return sessions map */ @@ -133,21 +125,19 @@ public class MongoOperationsSessionRepository public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { return Optional.ofNullable(this.mongoSessionConverter.getQueryForIndex(indexName, indexValue)) - .map(query -> this.mongoOperations.find(query, Document.class, this.collectionName)) - .orElse(Collections.emptyList()) - .stream() - .map(dbSession -> convertToSession(this.mongoSessionConverter, dbSession)) - .collect(Collectors.toMap(MongoSession::getId, mapSession -> mapSession)); - } + .map(query -> this.mongoOperations.find(query, Document.class, this.collectionName)) + .orElse(Collections.emptyList()).stream() + .map(dbSession -> convertToSession(this.mongoSessionConverter, dbSession)) + .collect(Collectors.toMap(MongoSession::getId, mapSession -> mapSession)); + } @Override public void deleteById(String id) { - - Optional.ofNullable(findSession(id)) - .ifPresent(document -> { - publishEvent(new SessionDeletedEvent(this, convertToSession(this.mongoSessionConverter, document))); - this.mongoOperations.remove(document, this.collectionName); - }); + + Optional.ofNullable(findSession(id)).ifPresent(document -> { + publishEvent(new SessionDeletedEvent(this, convertToSession(this.mongoSessionConverter, document))); + this.mongoOperations.remove(document, this.collectionName); + }); } @Override @@ -167,10 +157,10 @@ public class MongoOperationsSessionRepository } private void publishEvent(ApplicationEvent event) { + try { this.eventPublisher.publishEvent(event); - } - catch (Throwable ex) { + } catch (Throwable ex) { logger.error("Error publishing " + event + ".", ex); } } diff --git a/src/main/java/org/springframework/session/data/mongo/MongoSession.java b/src/main/java/org/springframework/session/data/mongo/MongoSession.java index 6dc91a8..6d18530 100644 --- a/src/main/java/org/springframework/session/data/mongo/MongoSession.java +++ b/src/main/java/org/springframework/session/data/mongo/MongoSession.java @@ -37,7 +37,7 @@ import org.springframework.session.Session; * @author Greg Turnquist * @since 1.2 */ -@EqualsAndHashCode(of = {"id"}) +@EqualsAndHashCode(of = { "id" }) public class MongoSession implements Session { /** @@ -67,6 +67,14 @@ public class MongoSession implements Session { setLastAccessedTime(Instant.ofEpochMilli(this.createdMillis)); } + static String coverDot(String attributeName) { + return attributeName.replace('.', DOT_COVER_CHAR); + } + + static String uncoverDot(String attributeName) { + return attributeName.replace(DOT_COVER_CHAR, '.'); + } + public String changeSessionId() { String changedId = UUID.randomUUID().toString(); @@ -81,9 +89,7 @@ public class MongoSession implements Session { public Set getAttributeNames() { - return this.attrs.keySet().stream() - .map(MongoSession::uncoverDot) - .collect(Collectors.toSet()); + return this.attrs.keySet().stream().map(MongoSession::uncoverDot).collect(Collectors.toSet()); } public void setAttribute(String attributeName, Object attributeValue) { @@ -107,33 +113,25 @@ public class MongoSession implements Session { this.createdMillis = created; } + public Instant getLastAccessedTime() { + return Instant.ofEpochMilli(this.accessedMillis); + } + public void setLastAccessedTime(Instant lastAccessedTime) { this.accessedMillis = lastAccessedTime.toEpochMilli(); this.expireAt = Date.from(lastAccessedTime.plus(Duration.ofSeconds(this.intervalSeconds))); } - public Instant getLastAccessedTime() { - return Instant.ofEpochMilli(this.accessedMillis); + public Duration getMaxInactiveInterval() { + return Duration.ofSeconds(this.intervalSeconds); } public void setMaxInactiveInterval(Duration interval) { this.intervalSeconds = interval.getSeconds(); } - public Duration getMaxInactiveInterval() { - return Duration.ofSeconds(this.intervalSeconds); - } - public boolean isExpired() { return this.intervalSeconds >= 0 && new Date().after(this.expireAt); } - - static String coverDot(String attributeName) { - return attributeName.replace('.', DOT_COVER_CHAR); - } - - static String uncoverDot(String attributeName) { - return attributeName.replace(DOT_COVER_CHAR, '.'); - } } diff --git a/src/main/java/org/springframework/session/data/mongo/MongoSessionUtils.java b/src/main/java/org/springframework/session/data/mongo/MongoSessionUtils.java index e8f2707..11a294a 100644 --- a/src/main/java/org/springframework/session/data/mongo/MongoSessionUtils.java +++ b/src/main/java/org/springframework/session/data/mongo/MongoSessionUtils.java @@ -16,7 +16,6 @@ package org.springframework.session.data.mongo; import org.bson.Document; - import org.springframework.core.convert.TypeDescriptor; import com.mongodb.DBObject; @@ -28,16 +27,14 @@ public final class MongoSessionUtils { static DBObject convertToDBObject(AbstractMongoSessionConverter mongoSessionConverter, MongoSession session) { - return (DBObject) mongoSessionConverter.convert(session, - TypeDescriptor.valueOf(MongoSession.class), - TypeDescriptor.valueOf(DBObject.class)); + return (DBObject) mongoSessionConverter.convert(session, TypeDescriptor.valueOf(MongoSession.class), + TypeDescriptor.valueOf(DBObject.class)); } static MongoSession convertToSession(AbstractMongoSessionConverter mongoSessionConverter, Document session) { - return (MongoSession) mongoSessionConverter.convert(session, - TypeDescriptor.valueOf(Document.class), - TypeDescriptor.valueOf(MongoSession.class)); + return (MongoSession) mongoSessionConverter.convert(session, TypeDescriptor.valueOf(Document.class), + TypeDescriptor.valueOf(MongoSession.class)); } } diff --git a/src/main/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepository.java b/src/main/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepository.java index 83fa6b5..54473b1 100644 --- a/src/main/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepository.java +++ b/src/main/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepository.java @@ -41,7 +41,7 @@ import org.springframework.session.events.SessionDeletedEvent; * @author Greg Turnquist */ public class ReactiveMongoOperationsSessionRepository - implements ReactiveSessionRepository, ApplicationEventPublisherAware, InitializingBean { + implements ReactiveSessionRepository, ApplicationEventPublisherAware, InitializingBean { /** * The default time period in seconds in which a session will expire. @@ -60,7 +60,7 @@ public class ReactiveMongoOperationsSessionRepository @Getter @Setter private Integer maxInactiveIntervalInSeconds = DEFAULT_INACTIVE_INTERVAL; @Getter @Setter private String collectionName = DEFAULT_COLLECTION_NAME; @Setter private AbstractMongoSessionConverter mongoSessionConverter = new JdkMongoSessionConverter( - Duration.ofSeconds(this.maxInactiveIntervalInSeconds)); + Duration.ofSeconds(this.maxInactiveIntervalInSeconds)); @Setter private MongoOperations blockingMongoOperations; private ApplicationEventPublisher eventPublisher; @@ -70,36 +70,29 @@ public class ReactiveMongoOperationsSessionRepository } /** - * Creates a new {@link MongoSession} that is capable of being persisted by this - * {@link ReactiveSessionRepository}. + * Creates a new {@link MongoSession} that is capable of being persisted by this {@link ReactiveSessionRepository}. *

- * This allows optimizations and customizations in how the {@link MongoSession} is - * persisted. For example, the implementation returned might keep track of the changes - * ensuring that only the delta needs to be persisted on a save. + * This allows optimizations and customizations in how the {@link MongoSession} is persisted. For example, the + * implementation returned might keep track of the changes ensuring that only the delta needs to be persisted on a + * save. *

* - * @return a new {@link MongoSession} that is capable of being persisted by this - * {@link ReactiveSessionRepository} + * @return a new {@link MongoSession} that is capable of being persisted by this {@link ReactiveSessionRepository} */ @Override public Mono createSession() { - return Mono.justOrEmpty(this.maxInactiveIntervalInSeconds) - .map(MongoSession::new) - .map(mongoSession -> { - publishEvent(new SessionCreatedEvent(this, mongoSession)); - return mongoSession; - }) - .switchIfEmpty(Mono.just(new MongoSession())); + return Mono.justOrEmpty(this.maxInactiveIntervalInSeconds) // + .map(MongoSession::new) // + .doOnNext(mongoSession -> publishEvent(new SessionCreatedEvent(this, mongoSession))) // + .switchIfEmpty(Mono.just(new MongoSession())); } /** - * Ensures the {@link MongoSession} created by - * {@link ReactiveSessionRepository#createSession()} is saved. + * Ensures the {@link MongoSession} created by {@link ReactiveSessionRepository#createSession()} is saved. *

- * Some implementations may choose to save as the {@link MongoSession} is updated by - * returning a {@link MongoSession} that immediately persists any changes. In this case, - * this method may not actually do anything. + * Some implementations may choose to save as the {@link MongoSession} is updated by returning a {@link MongoSession} + * that immediately persists any changes. In this case, this method may not actually do anything. *

* * @param session the {@link MongoSession} to save @@ -107,9 +100,8 @@ public class ReactiveMongoOperationsSessionRepository @Override public Mono save(MongoSession session) { - return this.mongoOperations - .save(convertToDBObject(this.mongoSessionConverter, session), this.collectionName) - .then(); + return this.mongoOperations.save(convertToDBObject(this.mongoSessionConverter, session), this.collectionName) + .then(); } /** @@ -118,20 +110,20 @@ public class ReactiveMongoOperationsSessionRepository * * @param id the {@link MongoSession#getId()} to lookup * @return the {@link MongoSession} by the {@link MongoSession#getId()} or {@link Mono#empty()} if no - * {@link MongoSession} is found. + * {@link MongoSession} is found. */ @Override public Mono findById(String id) { - return findSession(id) - .map(document -> convertToSession(this.mongoSessionConverter, document)) - .filter(mongoSession -> !mongoSession.isExpired()) - .switchIfEmpty(Mono.defer(() -> this.deleteById(id).then(Mono.empty()))); + return findSession(id) // + .map(document -> convertToSession(this.mongoSessionConverter, document)) // + .filter(mongoSession -> !mongoSession.isExpired()) // + .switchIfEmpty(Mono.defer(() -> this.deleteById(id).then(Mono.empty()))); } /** - * Deletes the {@link MongoSession} with the given {@link MongoSession#getId()} or does nothing - * if the {@link MongoSession} is not found. + * Deletes the {@link MongoSession} with the given {@link MongoSession#getId()} or does nothing if the + * {@link MongoSession} is not found. * * @param id the {@link MongoSession#getId()} to delete */ @@ -139,10 +131,10 @@ public class ReactiveMongoOperationsSessionRepository public Mono deleteById(String id) { return findSession(id) - .flatMap(document -> this.mongoOperations.remove(document, this.collectionName).then(Mono.just(document))) - .map(document -> convertToSession(this.mongoSessionConverter, document)) - .doOnSuccess(mongoSession -> publishEvent(new SessionDeletedEvent(this, mongoSession))) - .then(); + .flatMap(document -> this.mongoOperations.remove(document, this.collectionName).then(Mono.just(document))) + .map(document -> convertToSession(this.mongoSessionConverter, document)) + .doOnSuccess(mongoSession -> publishEvent(new SessionDeletedEvent(this, mongoSession))) // + .then(); } /** @@ -153,6 +145,7 @@ public class ReactiveMongoOperationsSessionRepository public void afterPropertiesSet() { if (this.blockingMongoOperations != null) { + IndexOperations indexOperations = this.blockingMongoOperations.indexOps(this.collectionName); this.mongoSessionConverter.ensureIndexes(indexOperations); } @@ -168,10 +161,10 @@ public class ReactiveMongoOperationsSessionRepository } private void publishEvent(ApplicationEvent event) { + try { this.eventPublisher.publishEvent(event); - } - catch (Throwable ex) { + } catch (Throwable ex) { logger.error("Error publishing " + event + ".", ex); } } diff --git a/src/main/java/org/springframework/session/data/mongo/config/annotation/web/http/EnableMongoHttpSession.java b/src/main/java/org/springframework/session/data/mongo/config/annotation/web/http/EnableMongoHttpSession.java index de1b761..b4e65a7 100644 --- a/src/main/java/org/springframework/session/data/mongo/config/annotation/web/http/EnableMongoHttpSession.java +++ b/src/main/java/org/springframework/session/data/mongo/config/annotation/web/http/EnableMongoHttpSession.java @@ -26,10 +26,11 @@ import org.springframework.context.annotation.Import; import org.springframework.session.data.mongo.MongoOperationsSessionRepository; /** - * Add this annotation to a {@code @Configuration} class to expose the - * SessionRepositoryFilter as a bean named "springSessionRepositoryFilter" and backed by - * Mongo. Use {@code collectionName} to change default name of the collection used to - * store sessions.
+ * Add this annotation to a {@code @Configuration} class to expose the SessionRepositoryFilter as a bean named
+ * "springSessionRepositoryFilter" and backed by Mongo. Use {@code collectionName} to change default name of the
+ * collection used to store sessions.
+ * 
+ * 
  * 
  * {@literal @EnableMongoHttpSession}
  * public class MongoHttpSessionConfig {
@@ -40,7 +41,8 @@ import org.springframework.session.data.mongo.MongoOperationsSessionRepository;
  *     }
  *
  * }
- *  
+ * + *
* * @author Jakub Kubrynski * @since 1.2 diff --git a/src/main/java/org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfiguration.java b/src/main/java/org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfiguration.java index c8df913..bc96453 100644 --- a/src/main/java/org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfiguration.java +++ b/src/main/java/org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfiguration.java @@ -36,8 +36,8 @@ import org.springframework.util.StringUtils; import org.springframework.util.StringValueResolver; /** - * Configuration class registering {@code MongoSessionRepository} bean. To import this - * configuration use {@link EnableMongoHttpSession} annotation. + * Configuration class registering {@code MongoSessionRepository} bean. To import this configuration use + * {@link EnableMongoHttpSession} annotation. * * @author Jakub Kubrynski * @author EddĂș MelĂ©ndez @@ -62,10 +62,9 @@ public class MongoHttpSessionConfiguration extends SpringHttpSessionConfiguratio if (this.mongoSessionConverter != null) { repository.setMongoSessionConverter(this.mongoSessionConverter); } else { - JdkMongoSessionConverter mongoSessionConverter = new JdkMongoSessionConverter( - new SerializingConverter(), - new DeserializingConverter(this.classLoader), - Duration.ofSeconds(MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL)); + JdkMongoSessionConverter mongoSessionConverter = new JdkMongoSessionConverter(new SerializingConverter(), + new DeserializingConverter(this.classLoader), + Duration.ofSeconds(MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL)); repository.setMongoSessionConverter(mongoSessionConverter); } @@ -86,8 +85,8 @@ public class MongoHttpSessionConfiguration extends SpringHttpSessionConfiguratio public void setImportMetadata(AnnotationMetadata importMetadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap( - importMetadata.getAnnotationAttributes(EnableMongoHttpSession.class.getName())); + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(importMetadata.getAnnotationAttributes(EnableMongoHttpSession.class.getName())); this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds"); diff --git a/src/main/java/org/springframework/session/data/mongo/config/annotation/web/reactive/ReactiveMongoWebSessionConfiguration.java b/src/main/java/org/springframework/session/data/mongo/config/annotation/web/reactive/ReactiveMongoWebSessionConfiguration.java index 40274c7..b0b4502 100644 --- a/src/main/java/org/springframework/session/data/mongo/config/annotation/web/reactive/ReactiveMongoWebSessionConfiguration.java +++ b/src/main/java/org/springframework/session/data/mongo/config/annotation/web/reactive/ReactiveMongoWebSessionConfiguration.java @@ -32,7 +32,6 @@ import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.session.config.annotation.web.server.SpringWebSessionConfiguration; import org.springframework.session.data.mongo.AbstractMongoSessionConverter; import org.springframework.session.data.mongo.JdkMongoSessionConverter; -import org.springframework.session.data.mongo.MongoOperationsSessionRepository; import org.springframework.session.data.mongo.ReactiveMongoOperationsSessionRepository; import org.springframework.util.StringUtils; import org.springframework.util.StringValueResolver; @@ -52,22 +51,21 @@ public class ReactiveMongoWebSessionConfiguration extends SpringWebSessionConfig private String collectionName; private StringValueResolver embeddedValueResolver; - @Autowired(required = false) - private MongoOperations mongoOperations; + @Autowired(required = false) private MongoOperations mongoOperations; private ClassLoader classLoader; @Bean - public ReactiveMongoOperationsSessionRepository reactiveMongoOperationsSessionRepository(ReactiveMongoOperations operations) { - + public ReactiveMongoOperationsSessionRepository reactiveMongoOperationsSessionRepository( + ReactiveMongoOperations operations) { + ReactiveMongoOperationsSessionRepository repository = new ReactiveMongoOperationsSessionRepository(operations); if (this.mongoSessionConverter != null) { repository.setMongoSessionConverter(this.mongoSessionConverter); } else { - JdkMongoSessionConverter mongoSessionConverter = new JdkMongoSessionConverter( - new SerializingConverter(), - new DeserializingConverter(this.classLoader), - Duration.ofSeconds(ReactiveMongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL)); + JdkMongoSessionConverter mongoSessionConverter = new JdkMongoSessionConverter(new SerializingConverter(), + new DeserializingConverter(this.classLoader), + Duration.ofSeconds(ReactiveMongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL)); repository.setMongoSessionConverter(mongoSessionConverter); } @@ -82,7 +80,7 @@ public class ReactiveMongoWebSessionConfiguration extends SpringWebSessionConfig if (this.mongoOperations != null) { repository.setBlockingMongoOperations(this.mongoOperations); } - + return repository; } @@ -94,8 +92,8 @@ public class ReactiveMongoWebSessionConfiguration extends SpringWebSessionConfig @Override public void setImportMetadata(AnnotationMetadata importMetadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap( - importMetadata.getAnnotationAttributes(EnableMongoWebSession.class.getName())); + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(importMetadata.getAnnotationAttributes(EnableMongoWebSession.class.getName())); this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds"); @@ -115,6 +113,7 @@ public class ReactiveMongoWebSessionConfiguration extends SpringWebSessionConfig public void setEmbeddedValueResolver(StringValueResolver embeddedValueResolver) { this.embeddedValueResolver = embeddedValueResolver; } + public Integer getMaxInactiveIntervalInSeconds() { return maxInactiveIntervalInSeconds; } diff --git a/src/test/java/org/springframework/session/data/mongo/AbstractMongoSessionConverterTest.java b/src/test/java/org/springframework/session/data/mongo/AbstractMongoSessionConverterTest.java index c641612..bed5346 100644 --- a/src/test/java/org/springframework/session/data/mongo/AbstractMongoSessionConverterTest.java +++ b/src/test/java/org/springframework/session/data/mongo/AbstractMongoSessionConverterTest.java @@ -57,8 +57,7 @@ public abstract class AbstractMongoSessionConverterTest { MongoSession toSerialize = new MongoSession(); String principalName = "john_the_springer"; SecurityContextImpl context = new SecurityContextImpl(); - context.setAuthentication( - new UsernamePasswordAuthenticationToken(principalName, null)); + context.setAuthentication(new UsernamePasswordAuthenticationToken(principalName, null)); toSerialize.setAttribute("SPRING_SECURITY_CONTEXT", context); // when @@ -66,14 +65,14 @@ public abstract class AbstractMongoSessionConverterTest { MongoSession deserialized = convertToSession(serialized); // then - assertThat(deserialized).isEqualToComparingOnlyGivenFields(toSerialize, - "id", "createdMillis", "accessedMillis", "intervalSeconds", "expireAt"); + assertThat(deserialized).isEqualToComparingOnlyGivenFields(toSerialize, "id", "createdMillis", "accessedMillis", + "intervalSeconds", "expireAt"); SecurityContextImpl springSecurityContextBefore = toSerialize.getAttribute("SPRING_SECURITY_CONTEXT"); SecurityContextImpl springSecurityContextAfter = deserialized.getAttribute("SPRING_SECURITY_CONTEXT"); assertThat(springSecurityContextBefore).isEqualToComparingOnlyGivenFields(springSecurityContextAfter, - "authentication.principal", "authentication.authorities", "authentication.authenticated"); + "authentication.principal", "authentication.authorities", "authentication.authenticated"); assertThat(springSecurityContextAfter.getAuthentication().getPrincipal()).isEqualTo("john_the_springer"); assertThat(springSecurityContextAfter.getAuthentication().getCredentials()).isNull(); } @@ -84,9 +83,7 @@ public abstract class AbstractMongoSessionConverterTest { // given MongoSession toSerialize = new MongoSession(); String principalName = "john_the_springer"; - toSerialize.setAttribute( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, - principalName); + toSerialize.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName); // when DBObject dbObject = convertToDBObject(toSerialize); @@ -102,8 +99,7 @@ public abstract class AbstractMongoSessionConverterTest { MongoSession toSerialize = new MongoSession(); String principalName = "john_the_springer"; SecurityContextImpl context = new SecurityContextImpl(); - context.setAuthentication( - new UsernamePasswordAuthenticationToken(principalName, null)); + context.setAuthentication(new UsernamePasswordAuthenticationToken(principalName, null)); toSerialize.setAttribute("SPRING_SECURITY_CONTEXT", context); // when @@ -130,16 +126,13 @@ public abstract class AbstractMongoSessionConverterTest { } MongoSession convertToSession(DBObject session) { - return (MongoSession) getMongoSessionConverter().convert(session, - TypeDescriptor.valueOf(DBObject.class), - TypeDescriptor.valueOf(MongoSession.class)); + return (MongoSession) getMongoSessionConverter().convert(session, TypeDescriptor.valueOf(DBObject.class), + TypeDescriptor.valueOf(MongoSession.class)); } DBObject convertToDBObject(MongoSession session) { - return (DBObject) getMongoSessionConverter().convert(session, - TypeDescriptor.valueOf(MongoSession.class), - TypeDescriptor.valueOf(DBObject.class)); + return (DBObject) getMongoSessionConverter().convert(session, TypeDescriptor.valueOf(MongoSession.class), + TypeDescriptor.valueOf(DBObject.class)); } - } diff --git a/src/test/java/org/springframework/session/data/mongo/AuthenticationParserTest.java b/src/test/java/org/springframework/session/data/mongo/AuthenticationParserTest.java index f4d76a6..5406038 100644 --- a/src/test/java/org/springframework/session/data/mongo/AuthenticationParserTest.java +++ b/src/test/java/org/springframework/session/data/mongo/AuthenticationParserTest.java @@ -18,7 +18,6 @@ package org.springframework.session.data.mongo; import static org.assertj.core.api.Assertions.*; import org.junit.Test; - import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextImpl; diff --git a/src/test/java/org/springframework/session/data/mongo/JacksonMongoSessionConverterTest.java b/src/test/java/org/springframework/session/data/mongo/JacksonMongoSessionConverterTest.java index 244e225..454f981 100644 --- a/src/test/java/org/springframework/session/data/mongo/JacksonMongoSessionConverterTest.java +++ b/src/test/java/org/springframework/session/data/mongo/JacksonMongoSessionConverterTest.java @@ -15,12 +15,11 @@ */ package org.springframework.session.data.mongo; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.*; import java.lang.reflect.Field; import org.junit.Test; - import org.springframework.data.mongodb.core.query.Query; import org.springframework.util.ReflectionUtils; @@ -43,13 +42,13 @@ public class JacksonMongoSessionConverterTest extends AbstractMongoSessionConver @Test public void shouldSaveIdField() throws Exception { - //given + // given MongoSession session = new MongoSession(); - //when + // when DBObject convert = this.mongoSessionConverter.convert(session); - //then + // then assertThat(convert.get("_id")).isEqualTo(session.getId()); assertThat(convert.get("id")).isNull(); } @@ -57,10 +56,10 @@ public class JacksonMongoSessionConverterTest extends AbstractMongoSessionConver @Test public void shouldQueryAgainstAttribute() throws Exception { - //when + // when Query cart = this.mongoSessionConverter.getQueryForIndex("cart", "my-cart"); - //then + // then assertThat(cart.getQueryObject().get("attrs.cart")).isEqualTo("my-cart"); } @@ -73,7 +72,6 @@ public class JacksonMongoSessionConverterTest extends AbstractMongoSessionConver // when JacksonMongoSessionConverter converter = new JacksonMongoSessionConverter(myMapper); - // then Field objectMapperField = ReflectionUtils.findField(JacksonMongoSessionConverter.class, "objectMapper"); ReflectionUtils.makeAccessible(objectMapperField); diff --git a/src/test/java/org/springframework/session/data/mongo/MongoOperationsSessionRepositoryTest.java b/src/test/java/org/springframework/session/data/mongo/MongoOperationsSessionRepositoryTest.java index 5665327..1501f5b 100644 --- a/src/test/java/org/springframework/session/data/mongo/MongoOperationsSessionRepositoryTest.java +++ b/src/test/java/org/springframework/session/data/mongo/MongoOperationsSessionRepositoryTest.java @@ -34,7 +34,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; 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; @@ -53,22 +52,22 @@ import com.mongodb.DBObject; @RunWith(MockitoJUnitRunner.class) public class MongoOperationsSessionRepositoryTest { - @Mock - private AbstractMongoSessionConverter converter; + @Mock private AbstractMongoSessionConverter converter; - @Mock - private MongoOperations mongoOperations; + @Mock private MongoOperations mongoOperations; private MongoOperationsSessionRepository repository; @Before - public void setUp() throws Exception { + public void setUp() { + this.repository = new MongoOperationsSessionRepository(this.mongoOperations); this.repository.setMongoSessionConverter(this.converter); } @Test - public void shouldCreateSession() throws Exception { + public void shouldCreateSession() { + // when MongoSession session = this.repository.createSession(); @@ -79,7 +78,8 @@ public class MongoOperationsSessionRepositoryTest { } @Test - public void shouldCreateSessionWhenMaxInactiveIntervalNotDefined() throws Exception { + public void shouldCreateSessionWhenMaxInactiveIntervalNotDefined() { + // when this.repository.setMaxInactiveIntervalInSeconds(null); MongoSession session = this.repository.createSession(); @@ -91,13 +91,13 @@ public class MongoOperationsSessionRepositoryTest { } @Test - public void shouldSaveSession() throws Exception { + public void shouldSaveSession() { + // given MongoSession session = new MongoSession(); BasicDBObject dbSession = new BasicDBObject(); - given(this.converter.convert(session, - TypeDescriptor.valueOf(MongoSession.class), + given(this.converter.convert(session, TypeDescriptor.valueOf(MongoSession.class), TypeDescriptor.valueOf(DBObject.class))).willReturn(dbSession); // when this.repository.save(session); @@ -107,13 +107,14 @@ public class MongoOperationsSessionRepositoryTest { } @Test - public void shouldGetSession() throws Exception { + public void shouldGetSession() { + // given String sessionId = UUID.randomUUID().toString(); Document sessionDocument = new Document(); given(this.mongoOperations.findById(sessionId, Document.class, - MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(sessionDocument); + MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(sessionDocument); MongoSession session = new MongoSession(); @@ -128,19 +129,20 @@ public class MongoOperationsSessionRepositoryTest { } @Test - public void shouldHandleExpiredSession() throws Exception { + public void shouldHandleExpiredSession() { + // given String sessionId = UUID.randomUUID().toString(); Document sessionDocument = new Document(); given(this.mongoOperations.findById(sessionId, Document.class, - MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(sessionDocument); + MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(sessionDocument); MongoSession session = mock(MongoSession.class); given(session.isExpired()).willReturn(true); given(this.converter.convert(sessionDocument, TypeDescriptor.valueOf(Document.class), - TypeDescriptor.valueOf(MongoSession.class))).willReturn(session); + TypeDescriptor.valueOf(MongoSession.class))).willReturn(session); given(session.getId()).willReturn("sessionId"); // when @@ -152,7 +154,8 @@ public class MongoOperationsSessionRepositoryTest { } @Test - public void shouldDeleteSession() throws Exception { + public void shouldDeleteSession() { + // given String sessionId = UUID.randomUUID().toString(); @@ -162,20 +165,21 @@ public class MongoOperationsSessionRepositoryTest { MongoSession mongoSession = new MongoSession(sessionId, MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL); given(this.converter.convert(sessionDocument, TypeDescriptor.valueOf(Document.class), - TypeDescriptor.valueOf(MongoSession.class))).willReturn(mongoSession); + TypeDescriptor.valueOf(MongoSession.class))).willReturn(mongoSession); given(this.mongoOperations.findById(eq(sessionId), eq(Document.class), - eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME))).willReturn(sessionDocument); + eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME))).willReturn(sessionDocument); // when this.repository.deleteById(sessionId); // then verify(this.mongoOperations).remove(any(Document.class), - eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)); + eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)); } @Test - public void shouldGetSessionsMapByPrincipal() throws Exception { + public void shouldGetSessionsMapByPrincipal() { + // given String principalNameIndexName = FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME; @@ -183,8 +187,7 @@ public class MongoOperationsSessionRepositoryTest { given(this.converter.getQueryForIndex(anyString(), any(Object.class))).willReturn(mock(Query.class)); given(this.mongoOperations.find(any(Query.class), eq(Document.class), - eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME))) - .willReturn(Collections.singletonList(document)); + eq(MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME))).willReturn(Collections.singletonList(document)); String sessionId = UUID.randomUUID().toString(); @@ -194,8 +197,8 @@ public class MongoOperationsSessionRepositoryTest { TypeDescriptor.valueOf(MongoSession.class))).willReturn(session); // when - Map sessionsMap = - this.repository.findByIndexNameAndIndexValue(principalNameIndexName, "john"); + Map sessionsMap = this.repository.findByIndexNameAndIndexValue(principalNameIndexName, + "john"); // then assertThat(sessionsMap).containsOnlyKeys(sessionId); @@ -203,13 +206,13 @@ public class MongoOperationsSessionRepositoryTest { } @Test - public void shouldReturnEmptyMapForNotSupportedIndex() throws Exception { + public void shouldReturnEmptyMapForNotSupportedIndex() { + // given String index = "some_not_supported_index_name"; // when - Map sessionsMap = this.repository - .findByIndexNameAndIndexValue(index, "some_value"); + Map sessionsMap = this.repository.findByIndexNameAndIndexValue(index, "some_value"); // then assertThat(sessionsMap).isEmpty(); diff --git a/src/test/java/org/springframework/session/data/mongo/MongoSessionTest.java b/src/test/java/org/springframework/session/data/mongo/MongoSessionTest.java index 43411b1..bd64cc1 100644 --- a/src/test/java/org/springframework/session/data/mongo/MongoSessionTest.java +++ b/src/test/java/org/springframework/session/data/mongo/MongoSessionTest.java @@ -31,6 +31,7 @@ public class MongoSessionTest { @Test public void isExpiredWhenIntervalNegativeThenFalse() { + MongoSession session = new MongoSession(); session.setMaxInactiveInterval(Duration.ofSeconds(-1)); session.setLastAccessedTime(Instant.ofEpochMilli(0L)); diff --git a/src/test/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepositoryTest.java b/src/test/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepositoryTest.java index c6a3aa6..f21f345 100644 --- a/src/test/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepositoryTest.java +++ b/src/test/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepositoryTest.java @@ -55,23 +55,17 @@ import com.mongodb.client.result.DeleteResult; @RunWith(MockitoJUnitRunner.Silent.class) public class ReactiveMongoOperationsSessionRepositoryTest { - @Mock - private AbstractMongoSessionConverter converter; + @Mock private AbstractMongoSessionConverter converter; + @Mock private ReactiveMongoOperations mongoOperations; - @Mock - private ReactiveMongoOperations mongoOperations; + @Mock private MongoOperations blockingMongoOperations; + @Mock private ApplicationEventPublisher eventPublisher; private ReactiveMongoOperationsSessionRepository repository; - @Mock - private MongoOperations blockingMongoOperations; - - @Mock - private ApplicationEventPublisher eventPublisher; - @Before public void setUp() { - + this.repository = new ReactiveMongoOperationsSessionRepository(this.mongoOperations); this.repository.setMongoSessionConverter(this.converter); this.repository.setApplicationEventPublisher(this.eventPublisher); @@ -80,15 +74,15 @@ public class ReactiveMongoOperationsSessionRepositoryTest { @Test public void shouldCreateSession() { - this.repository.createSession() - .as(StepVerifier::create) - .expectNextMatches(mongoSession -> { - assertThat(mongoSession.getId()).isNotEmpty(); - assertThat(mongoSession.getMaxInactiveInterval().getSeconds()) - .isEqualTo(ReactiveMongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL); - return true; - }) - .verifyComplete(); + this.repository.createSession() // + .as(StepVerifier::create) // + .expectNextMatches(mongoSession -> { + assertThat(mongoSession.getId()).isNotEmpty(); + assertThat(mongoSession.getMaxInactiveInterval().getSeconds()) + .isEqualTo(ReactiveMongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL); + return true; + }) // + .verifyComplete(); } @Test @@ -98,15 +92,15 @@ public class ReactiveMongoOperationsSessionRepositoryTest { this.repository.setMaxInactiveIntervalInSeconds(null); // then - this.repository.createSession() - .as(StepVerifier::create) - .expectNextMatches(mongoSession -> { - assertThat(mongoSession.getId()).isNotEmpty(); - assertThat(mongoSession.getMaxInactiveInterval().getSeconds()) - .isEqualTo(ReactiveMongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL); - return true; - }) - .verifyComplete(); + this.repository.createSession() // + .as(StepVerifier::create) // + .expectNextMatches(mongoSession -> { + assertThat(mongoSession.getId()).isNotEmpty(); + assertThat(mongoSession.getMaxInactiveInterval().getSeconds()) + .isEqualTo(ReactiveMongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL); + return true; + }) // + .verifyComplete(); } @Test @@ -116,16 +110,15 @@ public class ReactiveMongoOperationsSessionRepositoryTest { MongoSession session = new MongoSession(); BasicDBObject dbSession = new BasicDBObject(); - given(this.converter.convert(session, - TypeDescriptor.valueOf(MongoSession.class), + given(this.converter.convert(session, TypeDescriptor.valueOf(MongoSession.class), TypeDescriptor.valueOf(DBObject.class))).willReturn(dbSession); given(this.mongoOperations.save(dbSession, "sessions")).willReturn(Mono.just(dbSession)); // when - this.repository.save(session) - .as(StepVerifier::create) - .verifyComplete(); + this.repository.save(session) // + .as(StepVerifier::create) // + .verifyComplete(); verify(this.mongoOperations).save(dbSession, ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME); } @@ -138,7 +131,7 @@ public class ReactiveMongoOperationsSessionRepositoryTest { Document sessionDocument = new Document(); given(this.mongoOperations.findById(sessionId, Document.class, - ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument)); + ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument)); MongoSession session = new MongoSession(); @@ -146,10 +139,10 @@ public class ReactiveMongoOperationsSessionRepositoryTest { TypeDescriptor.valueOf(MongoSession.class))).willReturn(session); // when - this.repository.findById(sessionId) - .as(StepVerifier::create) - .expectNext(session) - .verifyComplete(); + this.repository.findById(sessionId) // + .as(StepVerifier::create) // + .expectNext(session) // + .verifyComplete(); } @Test @@ -160,52 +153,52 @@ public class ReactiveMongoOperationsSessionRepositoryTest { Document sessionDocument = new Document(); given(this.mongoOperations.findById(sessionId, Document.class, - ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument)); + ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument)); - given(this.mongoOperations.remove(sessionDocument, ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)) - .willReturn(Mono.just(DeleteResult.acknowledged(1))); + given( + this.mongoOperations.remove(sessionDocument, ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)) + .willReturn(Mono.just(DeleteResult.acknowledged(1))); MongoSession session = mock(MongoSession.class); given(session.isExpired()).willReturn(true); given(this.converter.convert(sessionDocument, TypeDescriptor.valueOf(Document.class), - TypeDescriptor.valueOf(MongoSession.class))).willReturn(session); + TypeDescriptor.valueOf(MongoSession.class))).willReturn(session); // when - this.repository.findById(sessionId) - .as(StepVerifier::create) - .verifyComplete(); + this.repository.findById(sessionId) // + .as(StepVerifier::create) // + .verifyComplete(); // then verify(this.mongoOperations).remove(any(Document.class), - eq(ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)); + eq(ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)); } @Test public void shouldDeleteSession() { - + // given String sessionId = UUID.randomUUID().toString(); Document sessionDocument = new Document(); given(this.mongoOperations.findById(sessionId, Document.class, - ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument)); + ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument)); - given(this.mongoOperations.remove(sessionDocument, "sessions")) - .willReturn(Mono.just(DeleteResult.acknowledged(1))); + given(this.mongoOperations.remove(sessionDocument, "sessions")).willReturn(Mono.just(DeleteResult.acknowledged(1))); MongoSession session = mock(MongoSession.class); given(this.converter.convert(sessionDocument, TypeDescriptor.valueOf(Document.class), - TypeDescriptor.valueOf(MongoSession.class))).willReturn(session); + TypeDescriptor.valueOf(MongoSession.class))).willReturn(session); // when - this.repository.deleteById(sessionId) - .as(StepVerifier::create) - .verifyComplete(); + this.repository.deleteById(sessionId) // + .as(StepVerifier::create) // + .verifyComplete(); verify(this.mongoOperations).remove(any(Document.class), - eq(ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)); + eq(ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)); verify(this.eventPublisher).publishEvent(any(SessionDeletedEvent.class)); } diff --git a/src/test/java/org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfigurationTest.java b/src/test/java/org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfigurationTest.java index f7525e8..a7fab44 100644 --- a/src/test/java/org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfigurationTest.java +++ b/src/test/java/org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfigurationTest.java @@ -25,7 +25,6 @@ import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; - import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -51,8 +50,7 @@ public class MongoHttpSessionConfigurationTest { private static final int MAX_INACTIVE_INTERVAL_IN_SECONDS = 600; - @Rule - public final ExpectedException thrown = ExpectedException.none(); + @Rule public final ExpectedException thrown = ExpectedException.none(); private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -78,8 +76,7 @@ public class MongoHttpSessionConfigurationTest { registerAndRefresh(DefaultConfiguration.class); - assertThat(this.context.getBean(MongoOperationsSessionRepository.class)) - .isNotNull(); + assertThat(this.context.getBean(MongoOperationsSessionRepository.class)).isNotNull(); } @Test @@ -90,8 +87,7 @@ public class MongoHttpSessionConfigurationTest { MongoOperationsSessionRepository repository = this.context.getBean(MongoOperationsSessionRepository.class); assertThat(repository).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "collectionName")) - .isEqualTo(COLLECTION_NAME); + assertThat(ReflectionTestUtils.getField(repository, "collectionName")).isEqualTo(COLLECTION_NAME); } @Test @@ -102,8 +98,7 @@ public class MongoHttpSessionConfigurationTest { MongoHttpSessionConfiguration session = this.context.getBean(MongoHttpSessionConfiguration.class); assertThat(session).isNotNull(); - assertThat(ReflectionTestUtils.getField(session, "collectionName")) - .isEqualTo(COLLECTION_NAME); + assertThat(ReflectionTestUtils.getField(session, "collectionName")).isEqualTo(COLLECTION_NAME); } @Test @@ -115,7 +110,7 @@ public class MongoHttpSessionConfigurationTest { assertThat(repository).isNotNull(); assertThat(ReflectionTestUtils.getField(repository, "maxInactiveIntervalInSeconds")) - .isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); + .isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); } @Test @@ -140,8 +135,7 @@ public class MongoHttpSessionConfigurationTest { assertThat(repository).isNotNull(); assertThat(mongoSessionConverter).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "mongoSessionConverter")) - .isEqualTo(mongoSessionConverter); + assertThat(ReflectionTestUtils.getField(repository, "mongoSessionConverter")).isEqualTo(mongoSessionConverter); } @Test @@ -152,8 +146,7 @@ public class MongoHttpSessionConfigurationTest { MongoHttpSessionConfiguration configuration = this.context.getBean(MongoHttpSessionConfiguration.class); - assertThat(ReflectionTestUtils.getField(configuration, "collectionName")) - .isEqualTo(COLLECTION_NAME); + assertThat(ReflectionTestUtils.getField(configuration, "collectionName")).isEqualTo(COLLECTION_NAME); } private void registerAndRefresh(Class... annotatedClasses) { diff --git a/src/test/java/org/springframework/session/data/mongo/config/annotation/web/reactive/ReactiveMongoWebSessionConfigurationTest.java b/src/test/java/org/springframework/session/data/mongo/config/annotation/web/reactive/ReactiveMongoWebSessionConfigurationTest.java index 8b862d9..1f8a827 100644 --- a/src/test/java/org/springframework/session/data/mongo/config/annotation/web/reactive/ReactiveMongoWebSessionConfigurationTest.java +++ b/src/test/java/org/springframework/session/data/mongo/config/annotation/web/reactive/ReactiveMongoWebSessionConfigurationTest.java @@ -52,7 +52,7 @@ import org.springframework.web.server.session.WebSessionManager; public class ReactiveMongoWebSessionConfigurationTest { private AnnotationConfigApplicationContext context; - + @After public void tearDown() { @@ -84,8 +84,7 @@ public class ReactiveMongoWebSessionConfigurationTest { this.context = new AnnotationConfigApplicationContext(); this.context.register(BadConfig.class); - assertThatExceptionOfType(UnsatisfiedDependencyException.class) - .isThrownBy(this.context::refresh) + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(this.context::refresh) .withMessageContaining("Error creating bean with name 'reactiveMongoOperationsSessionRepository'") .withMessageContaining("No qualifying bean of type '" + ReactiveMongoOperations.class.getCanonicalName()); } @@ -97,13 +96,12 @@ public class ReactiveMongoWebSessionConfigurationTest { this.context.register(GoodConfig.class); this.context.refresh(); - ReactiveMongoOperationsSessionRepository repository = this.context.getBean(ReactiveMongoOperationsSessionRepository.class); + ReactiveMongoOperationsSessionRepository repository = this.context + .getBean(ReactiveMongoOperationsSessionRepository.class); AbstractMongoSessionConverter converter = findMongoSessionConverter(repository); - assertThat(converter) - .extracting(AbstractMongoSessionConverter::getClass) - .contains(JdkMongoSessionConverter.class); + assertThat(converter).extracting(AbstractMongoSessionConverter::getClass).contains(JdkMongoSessionConverter.class); } @Test @@ -113,13 +111,13 @@ public class ReactiveMongoWebSessionConfigurationTest { this.context.register(OverrideSessionConverterConfig.class); this.context.refresh(); - ReactiveMongoOperationsSessionRepository repository = this.context.getBean(ReactiveMongoOperationsSessionRepository.class); + ReactiveMongoOperationsSessionRepository repository = this.context + .getBean(ReactiveMongoOperationsSessionRepository.class); AbstractMongoSessionConverter converter = findMongoSessionConverter(repository); - assertThat(converter) - .extracting(AbstractMongoSessionConverter::getClass) - .contains(JacksonMongoSessionConverter.class); + assertThat(converter).extracting(AbstractMongoSessionConverter::getClass) + .contains(JacksonMongoSessionConverter.class); } @Test @@ -129,13 +127,16 @@ public class ReactiveMongoWebSessionConfigurationTest { this.context.register(OverrideMongoParametersConfig.class); this.context.refresh(); - ReactiveMongoOperationsSessionRepository repository = this.context.getBean(ReactiveMongoOperationsSessionRepository.class); + ReactiveMongoOperationsSessionRepository repository = this.context + .getBean(ReactiveMongoOperationsSessionRepository.class); - Field inactiveField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, "maxInactiveIntervalInSeconds"); + Field inactiveField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, + "maxInactiveIntervalInSeconds"); ReflectionUtils.makeAccessible(inactiveField); Integer inactiveSeconds = (Integer) inactiveField.get(repository); - Field collectionNameField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, "collectionName"); + Field collectionNameField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, + "collectionName"); ReflectionUtils.makeAccessible(collectionNameField); String collectionName = (String) collectionNameField.get(repository); @@ -165,14 +166,16 @@ public class ReactiveMongoWebSessionConfigurationTest { this.context.register(CustomizedReactiveConfiguration.class); this.context.refresh(); - ReactiveMongoOperationsSessionRepository repository = this.context.getBean(ReactiveMongoOperationsSessionRepository.class); + ReactiveMongoOperationsSessionRepository repository = this.context + .getBean(ReactiveMongoOperationsSessionRepository.class); + assertThat(repository.getCollectionName()).isEqualTo("custom-collection"); assertThat(repository.getMaxInactiveIntervalInSeconds()).isEqualTo(123); } /** - * Reflectively extract the {@link AbstractMongoSessionConverter} from the {@link ReactiveMongoOperationsSessionRepository}. - * This is to avoid expanding the surface area of the API. + * Reflectively extract the {@link AbstractMongoSessionConverter} from the + * {@link ReactiveMongoOperationsSessionRepository}. This is to avoid expanding the surface area of the API. * * @param repository * @return @@ -249,7 +252,7 @@ public class ReactiveMongoWebSessionConfigurationTest { @Bean MongoOperations mongoOperations(IndexOperations indexOperations) { - + MongoOperations mongoOperations = mock(MongoOperations.class); given(mongoOperations.indexOps((String) any())).willReturn(indexOperations); return mongoOperations; @@ -259,15 +262,15 @@ public class ReactiveMongoWebSessionConfigurationTest { @EnableSpringWebSession static class CustomizedReactiveConfiguration extends ReactiveMongoWebSessionConfiguration { - @Bean - ReactiveMongoOperations reactiveMongoOperations() { - return mock(ReactiveMongoOperations.class); - } - public CustomizedReactiveConfiguration() { this.setCollectionName("custom-collection"); this.setMaxInactiveIntervalInSeconds(123); } + + @Bean + ReactiveMongoOperations reactiveMongoOperations() { + return mock(ReactiveMongoOperations.class); + } } } diff --git a/src/test/java/org/springframework/session/data/mongo/integration/AbstractClassLoaderTest.java b/src/test/java/org/springframework/session/data/mongo/integration/AbstractClassLoaderTest.java index 77a7f1b..6324a91 100644 --- a/src/test/java/org/springframework/session/data/mongo/integration/AbstractClassLoaderTest.java +++ b/src/test/java/org/springframework/session/data/mongo/integration/AbstractClassLoaderTest.java @@ -35,36 +35,36 @@ import org.springframework.util.ReflectionUtils; */ public abstract class AbstractClassLoaderTest extends AbstractITest { - @Autowired - T sessionRepository; - - @Autowired - ApplicationContext applicationContext; + @Autowired T sessionRepository; + + @Autowired ApplicationContext applicationContext; @Test public void verifyContainerClassLoaderLoadedIntoConverter() { Field mongoSessionConverterField = ReflectionUtils.findField(sessionRepository.getClass(), "mongoSessionConverter"); ReflectionUtils.makeAccessible(mongoSessionConverterField); - AbstractMongoSessionConverter sessionConverter = (AbstractMongoSessionConverter) ReflectionUtils.getField(mongoSessionConverterField, this.sessionRepository); + AbstractMongoSessionConverter sessionConverter = (AbstractMongoSessionConverter) ReflectionUtils + .getField(mongoSessionConverterField, this.sessionRepository); assertThat(sessionConverter).isInstanceOf(JdkMongoSessionConverter.class); JdkMongoSessionConverter jdkMongoSessionConverter = (JdkMongoSessionConverter) sessionConverter; - Field converterField = ReflectionUtils.findField(JdkMongoSessionConverter.class, "deserializer"); - ReflectionUtils.makeAccessible(converterField); - DeserializingConverter deserializingConverter = (DeserializingConverter) ReflectionUtils.getField(converterField, jdkMongoSessionConverter); - - Field deserializerField = ReflectionUtils.findField(DeserializingConverter.class, "deserializer"); - ReflectionUtils.makeAccessible(deserializerField); - DefaultDeserializer deserializer = (DefaultDeserializer) ReflectionUtils.getField(deserializerField, deserializingConverter); - - Field classLoaderField = ReflectionUtils.findField(DefaultDeserializer.class, "classLoader"); - ReflectionUtils.makeAccessible(classLoaderField); - ClassLoader classLoader = (ClassLoader) ReflectionUtils.getField(classLoaderField, deserializer); + DeserializingConverter deserializingConverter = (DeserializingConverter) extractField( + JdkMongoSessionConverter.class, "deserializer", jdkMongoSessionConverter); + DefaultDeserializer deserializer = (DefaultDeserializer) extractField(DeserializingConverter.class, "deserializer", + deserializingConverter); + ClassLoader classLoader = (ClassLoader) extractField(DefaultDeserializer.class, "classLoader", deserializer); assertThat(classLoader).isEqualTo(applicationContext.getClassLoader()); } + private static Object extractField(Class clazz, String fieldName, Object obj) { + + Field field = ReflectionUtils.findField(clazz, fieldName); + ReflectionUtils.makeAccessible(field); + return ReflectionUtils.getField(field, obj); + } + } diff --git a/src/test/java/org/springframework/session/data/mongo/integration/AbstractITest.java b/src/test/java/org/springframework/session/data/mongo/integration/AbstractITest.java index ec48ecb..7f28480 100644 --- a/src/test/java/org/springframework/session/data/mongo/integration/AbstractITest.java +++ b/src/test/java/org/springframework/session/data/mongo/integration/AbstractITest.java @@ -19,7 +19,6 @@ import java.util.UUID; import org.junit.Before; import org.junit.runner.RunWith; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; @@ -41,8 +40,7 @@ public abstract class AbstractITest { protected SecurityContext changedContext; - @Autowired(required = false) - protected SessionEventRegistry registry; + @Autowired(required = false) protected SessionEventRegistry registry; @Before public void setup() { @@ -52,14 +50,12 @@ public abstract class AbstractITest { } this.context = SecurityContextHolder.createEmptyContext(); - this.context.setAuthentication( - new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), - "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); + this.context.setAuthentication(new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), "na", + AuthorityUtils.createAuthorityList("ROLE_USER"))); this.changedContext = SecurityContextHolder.createEmptyContext(); - this.changedContext.setAuthentication(new UsernamePasswordAuthenticationToken( - "changedContext-" + UUID.randomUUID(), "na", - AuthorityUtils.createAuthorityList("ROLE_USER"))); + this.changedContext.setAuthentication(new UsernamePasswordAuthenticationToken("changedContext-" + UUID.randomUUID(), + "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); } } diff --git a/src/test/java/org/springframework/session/data/mongo/integration/AbstractMongoRepositoryITest.java b/src/test/java/org/springframework/session/data/mongo/integration/AbstractMongoRepositoryITest.java index b36df66..0a2c3e6 100644 --- a/src/test/java/org/springframework/session/data/mongo/integration/AbstractMongoRepositoryITest.java +++ b/src/test/java/org/springframework/session/data/mongo/integration/AbstractMongoRepositoryITest.java @@ -26,7 +26,6 @@ import java.util.UUID; import de.flapdoodle.embed.mongo.MongodExecutable; import org.junit.Test; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.DependsOn; @@ -58,19 +57,19 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { protected static final String INDEX_NAME = FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME; - @Autowired - protected MongoOperationsSessionRepository repository; + @Autowired protected MongoOperationsSessionRepository repository; @Test public void saves() throws InterruptedException { + String username = "saves-" + System.currentTimeMillis(); MongoSession toSave = this.repository.createSession(); String expectedAttributeName = "a"; String expectedAttributeValue = "b"; toSave.setAttribute(expectedAttributeName, expectedAttributeValue); - Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, - "password", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, "password", + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext(); toSaveContext.setAuthentication(toSaveToken); toSave.setAttribute(SPRING_SECURITY_CONTEXT, toSaveContext); @@ -82,7 +81,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { assertThat(session.getId()).isEqualTo(toSave.getId()); assertThat(session.getAttributeNames()).isEqualTo(toSave.getAttributeNames()); - assertThat(session.getAttribute(expectedAttributeName)) + assertThat(session. getAttribute(expectedAttributeName)) .isEqualTo(toSave.getAttribute(expectedAttributeName)); this.repository.deleteById(toSave.getId()); @@ -107,8 +106,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { Session session = this.repository.findById(toSave.getId()); assertThat(session.getAttributeNames().size()).isEqualTo(2); - assertThat(session.getAttribute("a")).isEqualTo("b"); - assertThat(session.getAttribute("1")).isEqualTo("2"); + assertThat(session. getAttribute("a")).isEqualTo("b"); + assertThat(session. getAttribute("1")).isEqualTo("2"); this.repository.deleteById(toSave.getId()); } @@ -122,16 +121,15 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); this.repository.deleteById(toSave.getId()); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - principalName); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalName); assertThat(findByPrincipalName).hasSize(0); assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId()); @@ -144,9 +142,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { @Test public void findByPrincipalNameNoPrincipalNameChange() throws Exception { - - String principalName = "findByPrincipalNameNoPrincipalNameChange" - + UUID.randomUUID(); + + String principalName = "findByPrincipalNameNoPrincipalNameChange" + UUID.randomUUID(); MongoSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); @@ -155,8 +152,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { toSave.setAttribute("other", "value"); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -165,8 +162,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { @Test public void findByPrincipalNameNoPrincipalNameChangeReload() throws Exception { - String principalName = "findByPrincipalNameNoPrincipalNameChangeReload" - + UUID.randomUUID(); + String principalName = "findByPrincipalNameNoPrincipalNameChangeReload" + UUID.randomUUID(); MongoSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); @@ -177,8 +173,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { toSave.setAttribute("other", "value"); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -196,8 +192,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { toSave.setAttribute(INDEX_NAME, null); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).isEmpty(); } @@ -215,12 +211,11 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { toSave.setAttribute(INDEX_NAME, principalNameChanged); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - principalNameChanged); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalNameChanged); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -239,8 +234,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { getSession.setAttribute(INDEX_NAME, null); this.repository.save(getSession); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).isEmpty(); } @@ -260,12 +255,11 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { getSession.setAttribute(INDEX_NAME, principalNameChanged); this.repository.save(getSession); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - principalNameChanged); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalNameChanged); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -279,16 +273,15 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); this.repository.deleteById(toSave.getId()); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - getSecurityName()); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); assertThat(findByPrincipalName).hasSize(0); assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId()); @@ -305,8 +298,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { toSave.setAttribute("other", "value"); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -323,8 +316,8 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { toSave.setAttribute(SPRING_SECURITY_CONTEXT, null); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).isEmpty(); } @@ -340,12 +333,11 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.changedContext); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - getChangedSecurityName()); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -364,12 +356,11 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { getSession.setAttribute(SPRING_SECURITY_CONTEXT, this.changedContext); this.repository.save(getSession); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - getChangedSecurityName()); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -377,7 +368,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { @Test public void loadExpiredSession() throws Exception { - + // given MongoSession expiredSession = this.repository.createSession(); Instant thirtyOneMinutesAgo = Instant.ofEpochMilli(System.currentTimeMillis()).minus(Duration.ofMinutes(31)); @@ -385,8 +376,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest { this.repository.save(expiredSession); // then - MongoSession expiredSessionFromDb = this.repository - .findById(expiredSession.getId()); + MongoSession expiredSessionFromDb = this.repository.findById(expiredSession.getId()); assertThat(expiredSessionFromDb).isNull(); } diff --git a/src/test/java/org/springframework/session/data/mongo/integration/MongoITestUtils.java b/src/test/java/org/springframework/session/data/mongo/integration/MongoITestUtils.java index c1008f4..a3df095 100644 --- a/src/test/java/org/springframework/session/data/mongo/integration/MongoITestUtils.java +++ b/src/test/java/org/springframework/session/data/mongo/integration/MongoITestUtils.java @@ -32,24 +32,22 @@ import de.flapdoodle.embed.process.runtime.Network; */ final class MongoITestUtils { - private MongoITestUtils() { - } + private MongoITestUtils() {} /** * Creates {@link MongodExecutable} for use in integration tests. + * * @param port the port for embedded Mongo to bind to * @return the {@link MongodExecutable} instance * @throws IOException in case of I/O errors */ static MongodExecutable embeddedMongoServer(int port) throws IOException { - IMongodConfig mongodConfig = new MongodConfigBuilder() - .version(Version.Main.PRODUCTION) - .net(new Net(port, Network.localhostIsIPv6())) - .build(); + IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION) + .net(new Net(port, Network.localhostIsIPv6())).build(); MongodStarter mongodStarter = MongodStarter.getDefaultInstance(); - + return mongodStarter.prepare(mongodConfig); } diff --git a/src/test/java/org/springframework/session/data/mongo/integration/MongoRepositoryJacksonITest.java b/src/test/java/org/springframework/session/data/mongo/integration/MongoRepositoryJacksonITest.java index 8a77ef6..bc15d78 100644 --- a/src/test/java/org/springframework/session/data/mongo/integration/MongoRepositoryJacksonITest.java +++ b/src/test/java/org/springframework/session/data/mongo/integration/MongoRepositoryJacksonITest.java @@ -51,8 +51,7 @@ public class MongoRepositoryJacksonITest extends AbstractMongoRepositoryITest { this.repository.save(toSave); - Map findByCartId = this.repository - .findByIndexNameAndIndexValue("cartId", cartId); + Map findByCartId = this.repository.findByIndexNameAndIndexValue("cartId", cartId); assertThat(findByCartId).hasSize(1); assertThat(findByCartId.keySet()).containsOnly(toSave.getId()); diff --git a/src/test/java/org/springframework/session/data/mongo/integration/MongoRepositoryJdkSerializationITest.java b/src/test/java/org/springframework/session/data/mongo/integration/MongoRepositoryJdkSerializationITest.java index 3460eab..da5b94e 100644 --- a/src/test/java/org/springframework/session/data/mongo/integration/MongoRepositoryJdkSerializationITest.java +++ b/src/test/java/org/springframework/session/data/mongo/integration/MongoRepositoryJdkSerializationITest.java @@ -52,8 +52,8 @@ public class MongoRepositoryJdkSerializationITest extends AbstractMongoRepositor getSession.setAttribute(INDEX_NAME, null); this.repository.save(getSession); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getChangedSecurityName()); assertThat(findByPrincipalName).isEmpty(); } @@ -71,8 +71,8 @@ public class MongoRepositoryJdkSerializationITest extends AbstractMongoRepositor toSave.setAttribute("other", "value"); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); diff --git a/src/test/java/org/springframework/session/data/mongo/integration/SessionEventRegistry.java b/src/test/java/org/springframework/session/data/mongo/integration/SessionEventRegistry.java index 9e98bc7..dbe98cf 100644 --- a/src/test/java/org/springframework/session/data/mongo/integration/SessionEventRegistry.java +++ b/src/test/java/org/springframework/session/data/mongo/integration/SessionEventRegistry.java @@ -23,7 +23,7 @@ import org.springframework.context.ApplicationListener; import org.springframework.session.events.AbstractSessionEvent; public class SessionEventRegistry implements ApplicationListener { - + private Map events = new HashMap(); private Map locks = new HashMap(); @@ -48,14 +48,12 @@ public class SessionEventRegistry implements ApplicationListener E getEvent(String sessionId) - throws InterruptedException { + public E getEvent(String sessionId) throws InterruptedException { return (E) waitForEvent(sessionId); } @SuppressWarnings("unchecked") - private E waitForEvent(String sessionId) - throws InterruptedException { + private E waitForEvent(String sessionId) throws InterruptedException { Object lock = getLock(sessionId); synchronized (lock) { diff --git a/src/test/java/org/springframework/session/data/mongo/integration/TraditionalConfigurationTest.java b/src/test/java/org/springframework/session/data/mongo/integration/TraditionalConfigurationTest.java index f7dab9a..f6318a3 100644 --- a/src/test/java/org/springframework/session/data/mongo/integration/TraditionalConfigurationTest.java +++ b/src/test/java/org/springframework/session/data/mongo/integration/TraditionalConfigurationTest.java @@ -26,9 +26,8 @@ import org.springframework.test.context.ContextConfiguration; */ @ContextConfiguration public class TraditionalConfigurationTest extends AbstractClassLoaderTest { - + @Configuration @EnableMongoHttpSession - static class Config extends BaseConfig { - } + static class Config extends BaseConfig {} }