Merge branch '3.0.x' into 3.1.x

Closes gh-2529
This commit is contained in:
Marcus Da Coregio
2023-10-19 10:34:23 -03:00
102 changed files with 766 additions and 656 deletions

View File

@@ -72,7 +72,7 @@ dependencies {
implementation 'com.apollographql.apollo:apollo-runtime:2.4.5'
implementation 'com.github.ben-manes:gradle-versions-plugin:0.38.0'
implementation 'com.github.spullara.mustache.java:compiler:0.9.11'
implementation 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.34'
implementation 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.39'
implementation 'io.spring.nohttp:nohttp-gradle:0.0.11'
implementation 'net.sourceforge.htmlunit:htmlunit:2.37.0'
implementation 'org.hidetake:gradle-ssh-plugin:2.10.1'

View File

@@ -18,6 +18,7 @@ package io.spring.gradle.convention
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.plugins.JavaPlugin
/**
@@ -31,12 +32,14 @@ class CheckstylePlugin implements Plugin<Project> {
@Override
void apply(Project project) {
def versionCatalog = project.rootProject.extensions.getByType(VersionCatalogsExtension.class)
.named("libs")
project.plugins.withType(JavaPlugin) {
def checkstyleDir = project.rootProject.file(CHECKSTYLE_DIR)
if (checkstyleDir.exists() && checkstyleDir.directory) {
project.getPluginManager().apply('checkstyle')
project.dependencies.add('checkstyle', 'io.spring.javaformat:spring-javaformat-checkstyle:0.0.29')
project.dependencies.add('checkstyle', 'io.spring.nohttp:nohttp-checkstyle:0.0.3.RELEASE')
project.dependencies.add('checkstyle', versionCatalog.findLibrary('io-spring-javaformat-spring-javaformat-checkstyle').get())
project.dependencies.add('checkstyle', versionCatalog.findLibrary('io-spring-nohttp-nohttp-checkstyle').get())
project.checkstyle {
configDirectory = checkstyleDir

View File

@@ -28,7 +28,7 @@ io-lettuce-lettuce-core = "io.lettuce:lettuce-core:6.2.6.RELEASE"
io-projectreactor-reactor-bom = "io.projectreactor:reactor-bom:2022.0.12"
io-projectreactor-reactor-core = { module = "io.projectreactor:reactor-core", version.ref = "io-projectreactor" }
io-projectreactor-reactor-test = { module = "io.projectreactor:reactor-test", version.ref = "io-projectreactor" }
io-spring-javaformat-spring-javaformat-checkstyle = "io.spring.javaformat:spring-javaformat-checkstyle:0.0.29"
io-spring-javaformat-spring-javaformat-checkstyle = "io.spring.javaformat:spring-javaformat-checkstyle:0.0.39"
io-spring-nohttp-nohttp-checkstyle = "io.spring.nohttp:nohttp-checkstyle:0.0.3.RELEASE"
jakarta-servlet-jakarta-servlet-api = "jakarta.servlet:jakarta.servlet-api:6.0.0"
jakarta-servlet-jsp-jstl-jakarta-servlet-jsp-jstl-api = "jakarta.servlet.jsp.jstl:jakarta.servlet.jsp.jstl-api:3.0.0"

View File

@@ -38,7 +38,7 @@ public interface FindByIndexNameSessionRepository<S extends Session> extends Ses
* @since 1.1
*/
String PRINCIPAL_NAME_INDEX_NAME = FindByIndexNameSessionRepository.class.getName()
.concat(".PRINCIPAL_NAME_INDEX_NAME");
.concat(".PRINCIPAL_NAME_INDEX_NAME");
/**
* Find a {@link Map} of the session id to the {@link Session} of all sessions that

View File

@@ -57,7 +57,7 @@ public final class MapSession implements Session, Serializable {
* Default {@link #setMaxInactiveInterval(Duration)} (30 minutes).
*/
public static final Duration DEFAULT_MAX_INACTIVE_INTERVAL = Duration
.ofSeconds(DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
.ofSeconds(DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
private String id;

View File

@@ -33,16 +33,17 @@ class CommonSessionRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
Arrays.asList(TypeReference.of(String.class), TypeReference.of(ArrayList.class),
TypeReference.of(TreeSet.class), TypeReference.of(Number.class), TypeReference.of(Long.class),
TypeReference.of(Integer.class), TypeReference.of(StackTraceElement.class),
TypeReference.of(Throwable.class), TypeReference.of(Exception.class),
TypeReference.of(RuntimeException.class),
TypeReference.of("java.util.Collections$UnmodifiableCollection"),
TypeReference.of("java.util.Collections$UnmodifiableList"),
TypeReference.of("java.util.Collections$EmptyList"),
TypeReference.of("java.util.Collections$UnmodifiableRandomAccessList"),
TypeReference.of("java.util.Collections$UnmodifiableSet")).forEach(hints.serialization()::registerType);
Arrays
.asList(TypeReference.of(String.class), TypeReference.of(ArrayList.class), TypeReference.of(TreeSet.class),
TypeReference.of(Number.class), TypeReference.of(Long.class), TypeReference.of(Integer.class),
TypeReference.of(StackTraceElement.class), TypeReference.of(Throwable.class),
TypeReference.of(Exception.class), TypeReference.of(RuntimeException.class),
TypeReference.of("java.util.Collections$UnmodifiableCollection"),
TypeReference.of("java.util.Collections$UnmodifiableList"),
TypeReference.of("java.util.Collections$EmptyList"),
TypeReference.of("java.util.Collections$UnmodifiableRandomAccessList"),
TypeReference.of("java.util.Collections$UnmodifiableSet"))
.forEach(hints.serialization()::registerType);
}
}

View File

@@ -53,34 +53,37 @@ class CommonSessionSecurityRuntimeHints implements RuntimeHintsRegistrar {
TypeReference.of("org.springframework.security.authentication.CredentialsExpiredException"),
TypeReference.of("org.springframework.security.authentication.InsufficientAuthenticationException"),
TypeReference
.of("org.springframework.security.web.authentication.session.SessionAuthenticationException"),
TypeReference.of(
"org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException"),
.of("org.springframework.security.web.authentication.session.SessionAuthenticationException"),
TypeReference
.of("org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException"),
TypeReference.of("org.springframework.security.core.userdetails.User$AuthorityComparator"))
.forEach((type) -> hints.serialization().registerType(type, (hint) -> hint.onReachableType(
.forEach((type) -> hints.serialization()
.registerType(type, (hint) -> hint.onReachableType(
TypeReference.of("org.springframework.security.core.context.SecurityContextImpl"))));
}
private void registerOAuth2ResourceServerHintsIfNeeded(RuntimeHints hints) {
Arrays.asList(
TypeReference.of("org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken"),
TypeReference.of(
"org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken"),
TypeReference
.of("org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken"),
TypeReference.of("org.springframework.security.oauth2.core.OAuth2AuthenticationException"))
.forEach((type) -> hints.serialization().registerType(type, (hint) -> hint.onReachableType(TypeReference
.of("org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken"))));
.forEach((type) -> hints.serialization()
.registerType(type, (hint) -> hint.onReachableType(TypeReference
.of("org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken"))));
}
private void registerOAuth2ClientHintsIfNeeded(RuntimeHints hints) {
Arrays.asList(
TypeReference.of("org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken"),
TypeReference
.of("org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken"),
TypeReference.of(
"org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken"),
.of("org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken"),
TypeReference
.of("org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken"),
TypeReference.of("org.springframework.security.oauth2.core.OAuth2AuthenticationException"))
.forEach((type) -> hints.serialization().registerType(type, (hint) -> hint.onReachableType(TypeReference
.of("org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken"))));
.forEach((type) -> hints.serialization()
.registerType(type, (hint) -> hint.onReachableType(TypeReference
.of("org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken"))));
}
}

View File

@@ -31,7 +31,7 @@ class WebSessionSecurityRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
if (!ClassUtils.isPresent("org.springframework.web.server.WebSession", classLoader) || !ClassUtils
.isPresent("org.springframework.security.web.server.csrf.DefaultCsrfToken", classLoader)) {
.isPresent("org.springframework.security.web.server.csrf.DefaultCsrfToken", classLoader)) {
return;
}
hints.serialization().registerType(DefaultCsrfToken.class);

View File

@@ -42,11 +42,12 @@ class HttpSessionSecurityRuntimeHints implements RuntimeHintsRegistrar {
|| !ClassUtils.isPresent("org.springframework.security.web.csrf.DefaultCsrfToken", classLoader)) {
return;
}
Arrays.asList(TypeReference.of(TreeMap.class), TypeReference.of(Locale.class),
TypeReference.of(DefaultSavedRequest.class), TypeReference.of(DefaultCsrfToken.class),
TypeReference.of(WebAuthenticationDetails.class), TypeReference.of(SavedCookie.class),
TypeReference.of("java.lang.String$CaseInsensitiveComparator"))
.forEach(hints.serialization()::registerType);
Arrays
.asList(TypeReference.of(TreeMap.class), TypeReference.of(Locale.class),
TypeReference.of(DefaultSavedRequest.class), TypeReference.of(DefaultCsrfToken.class),
TypeReference.of(WebAuthenticationDetails.class), TypeReference.of(SavedCookie.class),
TypeReference.of("java.lang.String$CaseInsensitiveComparator"))
.forEach(hints.serialization()::registerType);
}
}

View File

@@ -131,7 +131,7 @@ public class SpringHttpSessionConfiguration implements InitializingBean, Applica
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (ClassUtils.isPresent("org.springframework.security.web.authentication.RememberMeServices", null)) {
this.usesSpringSessionRememberMeServices = !ObjectUtils
.isEmpty(applicationContext.getBeanNamesForType(SpringSessionRememberMeServices.class));
.isEmpty(applicationContext.getBeanNamesForType(SpringSessionRememberMeServices.class));
}
}

View File

@@ -64,7 +64,7 @@ import org.springframework.session.web.http.CookieSerializer.CookieValue;
public final class CookieHttpSessionIdResolver implements HttpSessionIdResolver {
private static final String WRITTEN_SESSION_ID_ATTR = CookieHttpSessionIdResolver.class.getName()
.concat(".WRITTEN_SESSION_ID_ATTR");
.concat(".WRITTEN_SESSION_ID_ATTR");
private CookieSerializer cookieSerializer = new DefaultCookieSerializer();

View File

@@ -118,7 +118,7 @@ class HttpSessionAdapter<S extends Session> implements HttpSession {
if (oldValue instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) oldValue)
.valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
.valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);

View File

@@ -92,7 +92,8 @@ public class SpringSessionWebSessionStore<S extends Session> implements WebSessi
@Override
public Mono<WebSession> retrieveSession(String sessionId) {
return this.sessions.findById(sessionId)
.doOnNext((session) -> session.setLastAccessedTime(this.clock.instant())).map(this::existingSession);
.doOnNext((session) -> session.setLastAccessedTime(this.clock.instant()))
.map(this::existingSession);
}
@Override
@@ -233,8 +234,9 @@ public class SpringSessionWebSessionStore<S extends Session> implements WebSessi
@Override
public boolean containsValue(Object value) {
return this.session.getAttributeNames().stream()
.anyMatch((attrName) -> this.session.getAttribute(attrName) != null);
return this.session.getAttributeNames()
.stream()
.anyMatch((attrName) -> this.session.getAttribute(attrName) != null);
}
@Override

View File

@@ -67,7 +67,7 @@ public final class WebSocketRegistryListener implements ApplicationListener<Appl
else if (event instanceof SessionDisconnectEvent) {
SessionDisconnectEvent e = (SessionDisconnectEvent) event;
Map<String, Object> sessionAttributes = SimpMessageHeaderAccessor
.getSessionAttributes(e.getMessage().getHeaders());
.getSessionAttributes(e.getMessage().getHeaders());
String httpSessionId = (sessionAttributes != null)
? SessionRepositoryMessageInterceptor.getSessionId(sessionAttributes) : null;
afterConnectionClosed(httpSessionId, e.getSessionId());

View File

@@ -39,7 +39,7 @@ class MapSessionTests {
@Test
void constructorNullSession() {
assertThatIllegalArgumentException().isThrownBy(() -> new MapSession((Session) null))
.withMessage("session cannot be null");
.withMessage("session cannot be null");
}
@Test
@@ -70,7 +70,7 @@ class MapSessionTests {
@Test
void getRequiredAttributeWhenNullThenException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.session.getRequiredAttribute("attrName"))
.withMessage("Required attribute 'attrName' is missing.");
.withMessage("Required attribute 'attrName' is missing.");
}
@Test

View File

@@ -61,7 +61,7 @@ class ReactiveMapSessionRepositoryTests {
@Test
void constructorMapWhenNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveMapSessionRepository(null))
.withMessage("sessions cannot be null");
.withMessage("sessions cannot be null");
}
@Test

View File

@@ -53,8 +53,9 @@ class CommonSessionRuntimeHintsTests {
@Test
void aotFactoriesContainsRegistrar() {
boolean match = SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
.load(RuntimeHintsRegistrar.class).stream()
.anyMatch((registrar) -> registrar instanceof CommonSessionRuntimeHints);
.load(RuntimeHintsRegistrar.class)
.stream()
.anyMatch((registrar) -> registrar instanceof CommonSessionRuntimeHints);
assertThat(match).isTrue();
}

View File

@@ -51,8 +51,9 @@ class CommonSessionSecurityRuntimeHintsTests {
@Test
void aotFactoriesContainsRegistrar() {
boolean match = SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
.load(RuntimeHintsRegistrar.class).stream()
.anyMatch((registrar) -> registrar instanceof CommonSessionSecurityRuntimeHints);
.load(RuntimeHintsRegistrar.class)
.stream()
.anyMatch((registrar) -> registrar instanceof CommonSessionSecurityRuntimeHints);
assertThat(match).isTrue();
}
@@ -73,19 +74,19 @@ class CommonSessionSecurityRuntimeHintsTests {
TypeReference.of("org.springframework.security.authentication.CredentialsExpiredException"),
TypeReference.of("org.springframework.security.authentication.InsufficientAuthenticationException"),
TypeReference
.of("org.springframework.security.web.authentication.session.SessionAuthenticationException"),
TypeReference.of(
"org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException"),
.of("org.springframework.security.web.authentication.session.SessionAuthenticationException"),
TypeReference
.of("org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException"),
TypeReference.of("org.springframework.security.core.userdetails.User$AuthorityComparator"),
TypeReference.of("org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken"),
TypeReference.of(
"org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken"),
TypeReference
.of("org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken"),
TypeReference.of("org.springframework.security.oauth2.core.OAuth2AuthenticationException"),
TypeReference.of("org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken"),
TypeReference
.of("org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken"),
TypeReference.of(
"org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken"),
.of("org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken"),
TypeReference
.of("org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken"),
TypeReference.of("org.springframework.security.oauth2.core.OAuth2AuthenticationException"));
}

View File

@@ -52,7 +52,7 @@ class WebSessionSecurityRuntimeHintsTests {
void registerHintsWhenWebSessionMissingThenDoNotRegisterHints() {
try (MockedStatic<ClassUtils> classUtilsMock = mockStatic(ClassUtils.class)) {
classUtilsMock.when(() -> ClassUtils.isPresent(eq("org.springframework.web.server.WebSession"), any()))
.thenReturn(false);
.thenReturn(false);
this.webSessionSecurityRuntimeHints.registerHints(this.hints, getClass().getClassLoader());
assertThat(this.hints.serialization().javaSerializationHints()).isEmpty();
}
@@ -62,9 +62,9 @@ class WebSessionSecurityRuntimeHintsTests {
void registerHintsWhenDefaultCsrfTokenMissingThenDoNotRegisterHints() {
try (MockedStatic<ClassUtils> classUtilsMock = mockStatic(ClassUtils.class)) {
classUtilsMock
.when(() -> ClassUtils
.isPresent(eq("org.springframework.security.web.server.csrf.DefaultCsrfToken"), any()))
.thenReturn(false);
.when(() -> ClassUtils.isPresent(eq("org.springframework.security.web.server.csrf.DefaultCsrfToken"),
any()))
.thenReturn(false);
this.webSessionSecurityRuntimeHints.registerHints(this.hints, getClass().getClassLoader());
assertThat(this.hints.serialization().javaSerializationHints()).isEmpty();
}
@@ -73,8 +73,9 @@ class WebSessionSecurityRuntimeHintsTests {
@Test
void aotFactoriesContainsRegistrar() {
boolean match = SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
.load(RuntimeHintsRegistrar.class).stream()
.anyMatch((registrar) -> registrar instanceof WebSessionSecurityRuntimeHints);
.load(RuntimeHintsRegistrar.class)
.stream()
.anyMatch((registrar) -> registrar instanceof WebSessionSecurityRuntimeHints);
assertThat(match).isTrue();
}

View File

@@ -63,7 +63,7 @@ class HttpSessionSecurityRuntimeHintsTests {
void registerHintsWhenHttpSessionMissingThenDoNotRegisterHints() {
try (MockedStatic<ClassUtils> classUtilsMock = mockStatic(ClassUtils.class)) {
classUtilsMock.when(() -> ClassUtils.isPresent(eq("jakarta.servlet.http.HttpSession"), any()))
.thenReturn(false);
.thenReturn(false);
this.httpSessionSecurityRuntimeHints.registerHints(this.hints, getClass().getClassLoader());
assertThat(this.hints.serialization().javaSerializationHints()).isEmpty();
}
@@ -72,9 +72,9 @@ class HttpSessionSecurityRuntimeHintsTests {
@Test
void registerHintsWhenDefaultCsrfTokenMissingThenDoNotRegisterHints() {
try (MockedStatic<ClassUtils> classUtilsMock = mockStatic(ClassUtils.class)) {
classUtilsMock.when(
() -> ClassUtils.isPresent(eq("org.springframework.security.web.csrf.DefaultCsrfToken"), any()))
.thenReturn(false);
classUtilsMock
.when(() -> ClassUtils.isPresent(eq("org.springframework.security.web.csrf.DefaultCsrfToken"), any()))
.thenReturn(false);
this.httpSessionSecurityRuntimeHints.registerHints(this.hints, getClass().getClassLoader());
assertThat(this.hints.serialization().javaSerializationHints()).isEmpty();
}
@@ -83,8 +83,9 @@ class HttpSessionSecurityRuntimeHintsTests {
@Test
void aotFactoriesContainsRegistrar() {
boolean match = SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
.load(RuntimeHintsRegistrar.class).stream()
.anyMatch((registrar) -> registrar instanceof HttpSessionSecurityRuntimeHints);
.load(RuntimeHintsRegistrar.class)
.stream()
.anyMatch((registrar) -> registrar instanceof HttpSessionSecurityRuntimeHints);
assertThat(match).isTrue();
}

View File

@@ -92,7 +92,7 @@ class EnableSpringHttpSessionCustomCookieSerializerTests {
void usesReadSessionIds() throws Exception {
String sessionId = "sessionId";
given(this.cookieSerializer.readCookieValues(any(HttpServletRequest.class)))
.willReturn(Collections.singletonList(sessionId));
.willReturn(Collections.singletonList(sessionId));
given(this.sessionRepository.findById(anyString())).willReturn(new MapSession(sessionId));
this.sessionRepositoryFilter.doFilter(this.request, this.response, this.chain);

View File

@@ -64,8 +64,8 @@ class SpringHttpSessionConfigurationTests {
@Test
void noSessionRepositoryConfiguration() {
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(() -> registerAndRefresh(EmptyConfiguration.class))
.withMessageContaining("org.springframework.session.SessionRepository");
.isThrownBy(() -> registerAndRefresh(EmptyConfiguration.class))
.withMessageContaining("org.springframework.session.SessionRepository");
}
@Test
@@ -84,10 +84,10 @@ class SpringHttpSessionConfigurationTests {
SessionRepositoryFilter sessionRepositoryFilter = this.context.getBean(SessionRepositoryFilter.class);
assertThat(sessionRepositoryFilter).isNotNull();
CookieHttpSessionIdResolver httpSessionIdResolver = (CookieHttpSessionIdResolver) ReflectionTestUtils
.getField(sessionRepositoryFilter, "httpSessionIdResolver");
.getField(sessionRepositoryFilter, "httpSessionIdResolver");
assertThat(httpSessionIdResolver).isNotNull();
DefaultCookieSerializer cookieSerializer = (DefaultCookieSerializer) ReflectionTestUtils
.getField(httpSessionIdResolver, "cookieSerializer");
.getField(httpSessionIdResolver, "cookieSerializer");
assertThat(cookieSerializer).isNotNull();
assertThat(ReflectionTestUtils.getField(cookieSerializer, "cookieName")).isEqualTo("test-name");
assertThat(ReflectionTestUtils.getField(cookieSerializer, "cookiePath")).isEqualTo("test-path");
@@ -102,13 +102,13 @@ class SpringHttpSessionConfigurationTests {
SessionRepositoryFilter sessionRepositoryFilter = this.context.getBean(SessionRepositoryFilter.class);
assertThat(sessionRepositoryFilter).isNotNull();
CookieHttpSessionIdResolver httpSessionIdResolver = (CookieHttpSessionIdResolver) ReflectionTestUtils
.getField(sessionRepositoryFilter, "httpSessionIdResolver");
.getField(sessionRepositoryFilter, "httpSessionIdResolver");
assertThat(httpSessionIdResolver).isNotNull();
DefaultCookieSerializer cookieSerializer = (DefaultCookieSerializer) ReflectionTestUtils
.getField(httpSessionIdResolver, "cookieSerializer");
.getField(httpSessionIdResolver, "cookieSerializer");
assertThat(cookieSerializer).isNotNull();
assertThat(ReflectionTestUtils.getField(cookieSerializer, "rememberMeRequestAttribute"))
.isEqualTo(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR);
.isEqualTo(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR);
}
@Configuration

View File

@@ -77,8 +77,8 @@ class SpringWebSessionConfigurationTests {
this.context.register(BadConfig.class);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(this.context::refresh)
.withMessageContaining("Error creating bean with name 'webSessionManager'").withMessageContaining(
"No qualifying bean of type '" + ReactiveSessionRepository.class.getCanonicalName());
.withMessageContaining("Error creating bean with name 'webSessionManager'")
.withMessageContaining("No qualifying bean of type '" + ReactiveSessionRepository.class.getCanonicalName());
}
@Test

View File

@@ -77,7 +77,7 @@ class SpringSessionBackedSessionRegistryTest {
assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID);
assertThat(sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS));
assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
assertThat(sessionInfo.isExpired()).isFalse();
}
@@ -92,7 +92,7 @@ class SpringSessionBackedSessionRegistryTest {
assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID);
assertThat(sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS));
assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
assertThat(sessionInfo.isExpired()).isTrue();
}
@@ -113,7 +113,7 @@ class SpringSessionBackedSessionRegistryTest {
void getAllSessionsForAuthenticatedPrincipal() {
setUpSessions();
List<SessionInformation> allSessionInfos = this.sessionRegistry
.getAllSessions((AuthenticatedPrincipal) () -> USER_NAME, true);
.getAllSessions((AuthenticatedPrincipal) () -> USER_NAME, true);
assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, SESSION_ID2);
}
@@ -148,7 +148,7 @@ class SpringSessionBackedSessionRegistryTest {
ArgumentCaptor<Session> captor = ArgumentCaptor.forClass(Session.class);
verify(this.sessionRepository).save(captor.capture());
assertThat(captor.getValue().<Boolean>getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))
.isEqualTo(Boolean.TRUE);
.isEqualTo(Boolean.TRUE);
}
private Session createSession(String sessionId, String userName, Instant lastAccessed) {

View File

@@ -48,7 +48,7 @@ class SpringSessionRememberMeServicesTests {
void create() {
this.rememberMeServices = new SpringSessionRememberMeServices();
assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "rememberMeParameterName"))
.isEqualTo("remember-me");
.isEqualTo("remember-me");
assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "alwaysRemember")).isEqualTo(false);
assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "validitySeconds")).isEqualTo(2592000);
}
@@ -58,14 +58,14 @@ class SpringSessionRememberMeServicesTests {
this.rememberMeServices = new SpringSessionRememberMeServices();
this.rememberMeServices.setRememberMeParameterName("test-param");
assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "rememberMeParameterName"))
.isEqualTo("test-param");
.isEqualTo("test-param");
}
@Test
void createWithNullParameter() {
this.rememberMeServices = new SpringSessionRememberMeServices();
assertThatIllegalArgumentException().isThrownBy(() -> this.rememberMeServices.setRememberMeParameterName(null))
.withMessage("rememberMeParameterName cannot be empty or null");
.withMessage("rememberMeParameterName cannot be empty or null");
}
@Test

View File

@@ -64,7 +64,7 @@ class CookieHttpSessionIdResolverTests {
void getRequestedSessionIdNotNull() {
setSessionCookie(this.session.getId());
assertThat(this.strategy.resolveSessionIds(this.request))
.isEqualTo(Collections.singletonList(this.session.getId()));
.isEqualTo(Collections.singletonList(this.session.getId()));
}
@Test
@@ -72,7 +72,7 @@ class CookieHttpSessionIdResolverTests {
setCookieName("CUSTOM");
setSessionCookie(this.session.getId());
assertThat(this.strategy.resolveSessionIds(this.request))
.isEqualTo(Collections.singletonList(this.session.getId()));
.isEqualTo(Collections.singletonList(this.session.getId()));
}
@Test
@@ -144,7 +144,7 @@ class CookieHttpSessionIdResolverTests {
@Test
void createSessionCookieValue() {
assertThat(createSessionCookieValue(17))
.isEqualToIgnoringCase("0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 a 10 b 11 c 12 d 13 e 14 f 15 10 16");
.isEqualToIgnoringCase("0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 a 10 b 11 c 12 d 13 e 14 f 15 10 16");
}
private String createSessionCookieValue(long size) {

View File

@@ -200,7 +200,7 @@ class DefaultCookieSerializerTests {
void setDomainNameAndDomainNamePatternThrows() {
this.serializer.setDomainName("example.com");
assertThatIllegalStateException().isThrownBy(() -> this.serializer.setDomainNamePattern(".*"))
.withMessage("Cannot set both domainName and domainNamePattern");
.withMessage("Cannot set both domainName and domainNamePattern");
}
// --- domainNamePattern ---
@@ -229,7 +229,7 @@ class DefaultCookieSerializerTests {
void setDomainNamePatternAndDomainNameThrows() {
this.serializer.setDomainNamePattern(".*");
assertThatIllegalStateException().isThrownBy(() -> this.serializer.setDomainName("example.com"))
.withMessage("Cannot set both domainName and domainNamePattern");
.withMessage("Cannot set both domainName and domainNamePattern");
}
// --- cookieName ---
@@ -251,7 +251,7 @@ class DefaultCookieSerializerTests {
@Test
void setCookieNameNullThrows() {
assertThatIllegalArgumentException().isThrownBy(() -> this.serializer.setCookieName(null))
.withMessage("cookieName cannot be null");
.withMessage("cookieName cannot be null");
}
// --- cookiePath ---

View File

@@ -70,7 +70,7 @@ class HeaderHttpSessionIdResolverTests {
@Test
void createResolverWithNullHeaderName() {
assertThatIllegalArgumentException().isThrownBy(() -> new HeaderHttpSessionIdResolver(null))
.withMessage("headerName cannot be null");
.withMessage("headerName cannot be null");
}
@Test

View File

@@ -40,8 +40,9 @@ class OncePerRequestFilterAopTests {
@Test
void doFilterOnce(@Autowired final OncePerRequestFilter filter) {
assertThatCode(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
new MockFilterChain())).as("`doFilter` does not throw NPE with the bean is being proxied by Spring AOP")
.doesNotThrowAnyException();
new MockFilterChain()))
.as("`doFilter` does not throw NPE with the bean is being proxied by Spring AOP")
.doesNotThrowAnyException();
}
@SuppressWarnings({ "rawtypes", "unchecked" })

View File

@@ -998,7 +998,7 @@ class SessionRepositoryFilterTests {
final String expectedId = "HttpSessionIdResolver-requested-id";
given(this.strategy.resolveSessionIds(any(HttpServletRequest.class)))
.willReturn(Collections.singletonList(expectedId));
.willReturn(Collections.singletonList(expectedId));
given(sessionRepository.findById(anyString())).willReturn(new MapSession(expectedId));
doFilter(new DoInFilter() {
@@ -1020,7 +1020,7 @@ class SessionRepositoryFilterTests {
final String otherId = "HttpSessionIdResolver-requested-id2";
given(this.strategy.resolveSessionIds(any(HttpServletRequest.class)))
.willReturn(Arrays.asList(expectedId, otherId));
.willReturn(Arrays.asList(expectedId, otherId));
doFilter(new DoInFilter() {
@Override
@@ -1189,7 +1189,7 @@ class SessionRepositoryFilterTests {
void order() {
assertThat(
AnnotationAwareOrderComparator.INSTANCE.compare(this.filter, new SessionRepositoryFilterDefaultOrder()))
.isZero();
.isZero();
}
// We want the filter to work without any dependencies on Spring
@@ -1201,7 +1201,7 @@ class SessionRepositoryFilterTests {
@Test
void setHttpSessionIdResolverNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setHttpSessionIdResolver(null))
.withMessage("httpSessionIdResolver cannot be null");
.withMessage("httpSessionIdResolver cannot be null");
}
@Test
@@ -1329,16 +1329,18 @@ class SessionRepositoryFilterTests {
assertThat(cookie.getValue()).isNotEqualTo("INVALID");
assertThat(cookie.isHttpOnly()).describedAs("Cookie is expected to be HTTP Only").isTrue();
assertThat(cookie.getSecure()).describedAs("Cookie secured is expected to be " + this.request.isSecure())
.isEqualTo(this.request.isSecure());
.isEqualTo(this.request.isSecure());
assertThat(this.request.getSession(false))
.describedAs("The original HttpServletRequest HttpSession should be null").isNull();
.describedAs("The original HttpServletRequest HttpSession should be null")
.isNull();
}
private void assertNoSession() {
Cookie cookie = getSessionCookie();
assertThat(cookie).isNull();
assertThat(this.request.getSession(false))
.describedAs("The original HttpServletRequest HttpSession should be null").isNull();
.describedAs("The original HttpServletRequest HttpSession should be null")
.isNull();
}
private Cookie getSessionCookie() {

View File

@@ -68,7 +68,7 @@ class SpringSessionWebSessionStoreTests<S extends Session> {
@Test
void constructorWhenNullRepositoryThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new SpringSessionWebSessionStore<S>(null))
.withMessage("reactiveSessionRepository cannot be null");
.withMessage("reactiveSessionRepository cannot be null");
}
@Test
@@ -248,7 +248,7 @@ class SpringSessionWebSessionStoreTests<S extends Session> {
@Test
void setClockWhenNullThenException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.webSessionStore.setClock(null))
.withMessage("clock cannot be null");
.withMessage("clock cannot be null");
}
@Test // gh-1114

View File

@@ -61,7 +61,7 @@ class WebSocketConnectHandlerDecoratorFactoryTests {
@Test
void constructorNullEventPublisher() {
assertThatIllegalArgumentException().isThrownBy(() -> new WebSocketConnectHandlerDecoratorFactory(null))
.withMessage("eventPublisher cannot be null");
.withMessage("eventPublisher cannot be null");
}
@Test
@@ -78,7 +78,7 @@ class WebSocketConnectHandlerDecoratorFactoryTests {
void decorateAfterConnectionEstablishedEventError() throws Exception {
WebSocketHandler decorated = this.factory.decorate(this.delegate);
willThrow(new IllegalStateException("Test throw on publishEvent")).given(this.eventPublisher)
.publishEvent(any(ApplicationEvent.class));
.publishEvent(any(ApplicationEvent.class));
decorated.afterConnectionEstablished(this.session);

View File

@@ -150,7 +150,7 @@ class WebSocketRegistryListenerTests {
this.listener.onApplicationEvent(this.disconnect);
Map<String, Map<String, WebSocketSession>> httpSessionIdToWsSessions = (Map<String, Map<String, WebSocketSession>>) ReflectionTestUtils
.getField(this.listener, "httpSessionIdToWsSessions");
.getField(this.listener, "httpSessionIdToWsSessions");
assertThat(httpSessionIdToWsSessions).isEmpty();
}

View File

@@ -85,7 +85,7 @@ class SessionRepositoryMessageInterceptorTests {
@Test
void preSendconstructorNullRepository() {
assertThatIllegalArgumentException().isThrownBy(() -> new SessionRepositoryMessageInterceptor<>(null))
.withMessage("sessionRepository cannot be null");
.withMessage("sessionRepository cannot be null");
}
@Test
@@ -132,14 +132,14 @@ class SessionRepositoryMessageInterceptorTests {
@Test
void setMatchingMessageTypesNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.setMatchingMessageTypes(null))
.withMessage("matchingMessageTypes cannot be null or empty");
.withMessage("matchingMessageTypes cannot be null or empty");
}
@Test
void setMatchingMessageTypesEmpty() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.interceptor.setMatchingMessageTypes(Collections.emptySet()))
.withMessage("matchingMessageTypes cannot be null or empty");
.isThrownBy(() -> this.interceptor.setMatchingMessageTypes(Collections.emptySet()))
.withMessage("matchingMessageTypes cannot be null or empty");
}
@Test

View File

@@ -48,7 +48,7 @@ public abstract class AbstractClassLoaderTest<T> extends AbstractITest {
"mongoSessionConverter");
ReflectionUtils.makeAccessible(mongoSessionConverterField);
AbstractMongoSessionConverter sessionConverter = (AbstractMongoSessionConverter) ReflectionUtils
.getField(mongoSessionConverterField, this.sessionRepository);
.getField(mongoSessionConverterField, this.sessionRepository);
AssertionsForClassTypes.assertThat(sessionConverter).isInstanceOf(JdkMongoSessionConverter.class);

View File

@@ -79,7 +79,7 @@ public abstract class AbstractMongoRepositoryITest extends AbstractITest {
assertThat(session.getId()).isEqualTo(toSave.getId());
assertThat(session.getAttributeNames()).isEqualTo(toSave.getAttributeNames());
assertThat(session.<String>getAttribute(expectedAttributeName))
.isEqualTo(toSave.getAttribute(expectedAttributeName));
.isEqualTo(toSave.getAttribute(expectedAttributeName));
this.repository.deleteById(toSave.getId());
@@ -400,7 +400,7 @@ public abstract class AbstractMongoRepositoryITest extends AbstractITest {
public MongoOperations mongoOperations(MongoDBContainer mongoContainer) {
MongoClient mongo = MongoClients
.create("mongodb://" + mongoContainer.getHost() + ":" + mongoContainer.getFirstMappedPort());
.create("mongodb://" + mongoContainer.getHost() + ":" + mongoContainer.getFirstMappedPort());
return new MongoTemplate(mongo, "test");
}

View File

@@ -73,13 +73,14 @@ public class MongoDbDeleteJacksonSessionVerificationTest {
// 1. Login and capture the SESSION cookie value.
FluxExchangeResult<String> loginResult = this.client.post().uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED) //
.body(BodyInserters //
.fromFormData("username", "admin") //
.with("password", "password")) //
.exchange() //
.returnResult(String.class);
FluxExchangeResult<String> loginResult = this.client.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED) //
.body(BodyInserters //
.fromFormData("username", "admin") //
.with("password", "password")) //
.exchange() //
.returnResult(String.class);
AssertionsForClassTypes.assertThat(loginResult.getResponseHeaders().getLocation()).isEqualTo(URI.create("/"));
@@ -87,42 +88,54 @@ public class MongoDbDeleteJacksonSessionVerificationTest {
// 2. Fetch a protected resource using the SESSION cookie.
this.client.get().uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isOk() //
.returnResult(String.class).getResponseBody() //
.as(StepVerifier::create) //
.expectNext("HelloWorld") //
.verifyComplete();
this.client.get()
.uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus()
.isOk() //
.returnResult(String.class)
.getResponseBody() //
.as(StepVerifier::create) //
.expectNext("HelloWorld") //
.verifyComplete();
// 3. Logout using the SESSION cookie, and capture the new SESSION cookie.
String newSessionId = this.client.post().uri("/logout") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isFound() //
.returnResult(String.class).getResponseCookies().getFirst("SESSION").getValue();
String newSessionId = this.client.post()
.uri("/logout") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus()
.isFound() //
.returnResult(String.class)
.getResponseCookies()
.getFirst("SESSION")
.getValue();
AssertionsForClassTypes.assertThat(newSessionId).isNotEqualTo(originalSessionId);
// 4. Verify the new SESSION cookie is not yet authorized.
this.client.get().uri("/hello") //
.cookie("SESSION", newSessionId) //
.exchange() //
.expectStatus().isFound() //
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
this.client.get()
.uri("/hello") //
.cookie("SESSION", newSessionId) //
.exchange() //
.expectStatus()
.isFound() //
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
// 5. Verify the original SESSION cookie no longer works.
this.client.get().uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isFound() //
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
this.client.get()
.uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus()
.isFound() //
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
}
@RestController
@@ -142,23 +155,25 @@ public class MongoDbDeleteJacksonSessionVerificationTest {
@Bean
SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http //
.logout()//
/**/.and() //
.formLogin() //
/**/.and() //
.csrf().disable() //
.authorizeExchange() //
.anyExchange().authenticated() //
/**/.and() //
.build();
.logout()//
/**/.and() //
.formLogin() //
/**/.and() //
.csrf()
.disable() //
.authorizeExchange() //
.anyExchange()
.authenticated() //
/**/.and() //
.build();
}
@Bean
MapReactiveUserDetailsService userDetailsService() {
return new MapReactiveUserDetailsService(User.withUsername("admin") //
.password("{noop}password") //
.roles("USER,ADMIN") //
.build());
.password("{noop}password") //
.roles("USER,ADMIN") //
.build());
}
@Bean
@@ -186,7 +201,7 @@ public class MongoDbDeleteJacksonSessionVerificationTest {
ReactiveMongoOperations mongoOperations(MongoDBContainer mongoContainer) {
MongoClient mongo = MongoClients
.create("mongodb://" + mongoContainer.getHost() + ":" + mongoContainer.getFirstMappedPort());
.create("mongodb://" + mongoContainer.getHost() + ":" + mongoContainer.getFirstMappedPort());
return new ReactiveMongoTemplate(mongo, "DB_Name_DeleteJacksonSessionVerificationTest");
}

View File

@@ -73,13 +73,14 @@ public class MongoDbLogoutVerificationTest {
// 1. Login and capture the SESSION cookie value.
FluxExchangeResult<String> loginResult = this.client.post().uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED) //
.body(BodyInserters //
.fromFormData("username", "admin") //
.with("password", "password")) //
.exchange() //
.returnResult(String.class);
FluxExchangeResult<String> loginResult = this.client.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED) //
.body(BodyInserters //
.fromFormData("username", "admin") //
.with("password", "password")) //
.exchange() //
.returnResult(String.class);
AssertionsForClassTypes.assertThat(loginResult.getResponseHeaders().getLocation()).isEqualTo(URI.create("/"));
@@ -87,42 +88,54 @@ public class MongoDbLogoutVerificationTest {
// 2. Fetch a protected resource using the SESSION cookie.
this.client.get().uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isOk() //
.returnResult(String.class).getResponseBody() //
.as(StepVerifier::create) //
.expectNext("HelloWorld") //
.verifyComplete();
this.client.get()
.uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus()
.isOk() //
.returnResult(String.class)
.getResponseBody() //
.as(StepVerifier::create) //
.expectNext("HelloWorld") //
.verifyComplete();
// 3. Logout using the SESSION cookie, and capture the new SESSION cookie.
String newSessionId = this.client.post().uri("/logout") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isFound() //
.returnResult(String.class).getResponseCookies().getFirst("SESSION").getValue();
String newSessionId = this.client.post()
.uri("/logout") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus()
.isFound() //
.returnResult(String.class)
.getResponseCookies()
.getFirst("SESSION")
.getValue();
AssertionsForClassTypes.assertThat(newSessionId).isNotEqualTo(originalSessionId);
// 4. Verify the new SESSION cookie is not yet authorized.
this.client.get().uri("/hello") //
.cookie("SESSION", newSessionId) //
.exchange() //
.expectStatus().isFound() //
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
this.client.get()
.uri("/hello") //
.cookie("SESSION", newSessionId) //
.exchange() //
.expectStatus()
.isFound() //
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
// 5. Verify the original SESSION cookie no longer works.
this.client.get().uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus().isFound() //
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
this.client.get()
.uri("/hello") //
.cookie("SESSION", originalSessionId) //
.exchange() //
.expectStatus()
.isFound() //
.expectHeader()
.value(HttpHeaders.LOCATION, (value) -> AssertionsForClassTypes.assertThat(value).isEqualTo("/login"));
}
@RestController
@@ -143,24 +156,26 @@ public class MongoDbLogoutVerificationTest {
SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http //
.logout()//
/**/.and() //
.formLogin() //
/**/.and() //
.csrf().disable() //
.authorizeExchange() //
.anyExchange().authenticated() //
/**/.and() //
.build();
.logout()//
/**/.and() //
.formLogin() //
/**/.and() //
.csrf()
.disable() //
.authorizeExchange() //
.anyExchange()
.authenticated() //
/**/.and() //
.build();
}
@Bean
MapReactiveUserDetailsService userDetailsService() {
return new MapReactiveUserDetailsService(User.withUsername("admin") //
.password("{noop}password") //
.roles("USER,ADMIN") //
.build());
.password("{noop}password") //
.roles("USER,ADMIN") //
.build());
}
}
@@ -183,7 +198,7 @@ public class MongoDbLogoutVerificationTest {
ReactiveMongoOperations mongoOperations(MongoDBContainer mongoContainer) {
MongoClient mongo = MongoClients
.create("mongodb://" + mongoContainer.getHost() + ":" + mongoContainer.getFirstMappedPort());
.create("mongodb://" + mongoContainer.getHost() + ":" + mongoContainer.getFirstMappedPort());
return new ReactiveMongoTemplate(mongo, "test");
}

View File

@@ -86,13 +86,13 @@ 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(MongoSession expiringSession) {
return this.indexResolver.resolveIndexesFor(expiringSession)
.get(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
.get(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
}
public Set<ConvertiblePair> getConvertibleTypes() {

View File

@@ -137,10 +137,11 @@ public class MongoIndexedSessionRepository
public Map<String, MongoSession> 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) -> MongoSessionUtils.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) -> MongoSessionUtils.convertToSession(this.mongoSessionConverter, dbSession))
.collect(Collectors.toMap(MongoSession::getId, (mapSession) -> mapSession));
}
@Override

View File

@@ -95,50 +95,50 @@ public class ReactiveMongoSessionRepository
public Mono<MongoSession> createSession() {
return Mono.justOrEmpty(this.defaultMaxInactiveInterval.toSeconds()) //
.map(MongoSession::new) //
.doOnNext((mongoSession) -> publishEvent(new SessionCreatedEvent(this, mongoSession))) //
.switchIfEmpty(Mono.just(new MongoSession()));
.map(MongoSession::new) //
.doOnNext((mongoSession) -> publishEvent(new SessionCreatedEvent(this, mongoSession))) //
.switchIfEmpty(Mono.just(new MongoSession()));
}
@Override
public Mono<Void> save(MongoSession session) {
return Mono //
.justOrEmpty(MongoSessionUtils.convertToDBObject(this.mongoSessionConverter, session)) //
.flatMap((dbObject) -> {
if (session.hasChangedSessionId()) {
.justOrEmpty(MongoSessionUtils.convertToDBObject(this.mongoSessionConverter, session)) //
.flatMap((dbObject) -> {
if (session.hasChangedSessionId()) {
return this.mongoOperations
.remove(Query.query(Criteria.where("_id").is(session.getOriginalSessionId())),
this.collectionName) //
.then(this.mongoOperations.save(dbObject, this.collectionName));
}
else {
return this.mongoOperations
.remove(Query.query(Criteria.where("_id").is(session.getOriginalSessionId())),
this.collectionName) //
.then(this.mongoOperations.save(dbObject, this.collectionName));
}
else {
return this.mongoOperations.save(dbObject, this.collectionName);
}
}) //
.then();
return this.mongoOperations.save(dbObject, this.collectionName);
}
}) //
.then();
}
@Override
public Mono<MongoSession> findById(String id) {
return findSession(id) //
.map((document) -> MongoSessionUtils.convertToSession(this.mongoSessionConverter, document)) //
.filter((mongoSession) -> !mongoSession.isExpired()) //
.switchIfEmpty(Mono.defer(() -> this.deleteById(id).then(Mono.empty())));
.map((document) -> MongoSessionUtils.convertToSession(this.mongoSessionConverter, document)) //
.filter((mongoSession) -> !mongoSession.isExpired()) //
.switchIfEmpty(Mono.defer(() -> this.deleteById(id).then(Mono.empty())));
}
@Override
public Mono<Void> deleteById(String id) {
return findSession(id) //
.flatMap((document) -> this.mongoOperations.remove(document, this.collectionName) //
.then(Mono.just(document))) //
.map((document) -> MongoSessionUtils.convertToSession(this.mongoSessionConverter, document)) //
.doOnNext((mongoSession) -> publishEvent(new SessionDeletedEvent(this, mongoSession))) //
.then();
.flatMap((document) -> this.mongoOperations.remove(document, this.collectionName) //
.then(Mono.just(document))) //
.map((document) -> MongoSessionUtils.convertToSession(this.mongoSessionConverter, document)) //
.doOnNext((mongoSession) -> publishEvent(new SessionDeletedEvent(this, mongoSession))) //
.then();
}
/**

View File

@@ -100,7 +100,7 @@ public class MongoHttpSessionConfiguration implements BeanClassLoaderAware, Embe
}
this.sessionRepositoryCustomizers
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(repository));
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(repository));
return repository;
}
@@ -121,11 +121,11 @@ public class MongoHttpSessionConfiguration implements BeanClassLoaderAware, Embe
public void setImportMetadata(AnnotationMetadata importMetadata) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importMetadata.getAnnotationAttributes(EnableMongoHttpSession.class.getName()));
.fromMap(importMetadata.getAnnotationAttributes(EnableMongoHttpSession.class.getName()));
if (attributes != null) {
this.maxInactiveInterval = Duration
.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds"));
.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds"));
}
String collectionNameValue = (attributes != null) ? attributes.getString("collectionName") : "";

View File

@@ -110,7 +110,7 @@ public class ReactiveMongoWebSessionConfiguration
}
this.sessionRepositoryCustomizers
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(repository));
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(repository));
return repository;
}
@@ -124,11 +124,11 @@ public class ReactiveMongoWebSessionConfiguration
public void setImportMetadata(AnnotationMetadata importMetadata) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importMetadata.getAnnotationAttributes(EnableMongoWebSession.class.getName()));
.fromMap(importMetadata.getAnnotationAttributes(EnableMongoWebSession.class.getName()));
if (attributes != null) {
this.maxInactiveInterval = Duration
.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds"));
.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds"));
}
String collectionNameValue = (attributes != null) ? attributes.getString("collectionName") : "";

View File

@@ -89,7 +89,7 @@ public class JacksonMongoSessionConverterTest extends AbstractMongoSessionConver
void shouldNotAllowNullObjectMapperToBeInjected() {
Assertions.assertThatIllegalArgumentException()
.isThrownBy(() -> new JacksonMongoSessionConverter((ObjectMapper) null));
.isThrownBy(() -> new JacksonMongoSessionConverter((ObjectMapper) null));
}
@Test

View File

@@ -43,14 +43,14 @@ public class JdkMongoSessionConverterTest extends AbstractMongoSessionConverterT
@Test
void constructorNullSerializer() {
assertThatIllegalArgumentException().isThrownBy(
() -> new JdkMongoSessionConverter(null, new DeserializingConverter(), this.inactiveInterval));
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdkMongoSessionConverter(null, new DeserializingConverter(), this.inactiveInterval));
}
@Test
void constructorNullDeserializer() {
assertThatIllegalArgumentException().isThrownBy(
() -> new JdkMongoSessionConverter(new SerializingConverter(), null, this.inactiveInterval));
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdkMongoSessionConverter(new SerializingConverter(), null, this.inactiveInterval));
}
}

View File

@@ -77,7 +77,7 @@ public class MongoIndexedSessionRepositoryTest {
// then
assertThat(session.getId()).isNotEmpty();
assertThat(session.getMaxInactiveInterval().getSeconds())
.isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
.isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
}
@Test
@@ -88,7 +88,8 @@ public class MongoIndexedSessionRepositoryTest {
BasicDBObject dbSession = new BasicDBObject();
given(this.converter.convert(session, TypeDescriptor.valueOf(MongoSession.class),
TypeDescriptor.valueOf(DBObject.class))).willReturn(dbSession);
TypeDescriptor.valueOf(DBObject.class)))
.willReturn(dbSession);
// when
this.repository.save(session);
@@ -104,12 +105,14 @@ public class MongoIndexedSessionRepositoryTest {
Document sessionDocument = new Document();
given(this.mongoOperations.findById(sessionId, Document.class,
MongoIndexedSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(sessionDocument);
MongoIndexedSessionRepository.DEFAULT_COLLECTION_NAME))
.willReturn(sessionDocument);
MongoSession session = new MongoSession();
given(this.converter.convert(sessionDocument, TypeDescriptor.valueOf(Document.class),
TypeDescriptor.valueOf(MongoSession.class))).willReturn(session);
TypeDescriptor.valueOf(MongoSession.class)))
.willReturn(session);
// when
MongoSession retrievedSession = this.repository.findById(sessionId);
@@ -126,13 +129,15 @@ public class MongoIndexedSessionRepositoryTest {
Document sessionDocument = new Document();
given(this.mongoOperations.findById(sessionId, Document.class,
MongoIndexedSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(sessionDocument);
MongoIndexedSessionRepository.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
@@ -155,9 +160,11 @@ public class MongoIndexedSessionRepositoryTest {
MongoSession mongoSession = new MongoSession(sessionId, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
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(MongoIndexedSessionRepository.DEFAULT_COLLECTION_NAME))).willReturn(sessionDocument);
eq(MongoIndexedSessionRepository.DEFAULT_COLLECTION_NAME)))
.willReturn(sessionDocument);
// when
this.repository.deleteById(sessionId);
@@ -178,14 +185,15 @@ public class MongoIndexedSessionRepositoryTest {
given(this.converter.getQueryForIndex(anyString(), any(Object.class))).willReturn(mock(Query.class));
given(this.mongoOperations.find(any(Query.class), eq(Document.class),
eq(MongoIndexedSessionRepository.DEFAULT_COLLECTION_NAME)))
.willReturn(Collections.singletonList(document));
.willReturn(Collections.singletonList(document));
String sessionId = UUID.randomUUID().toString();
MongoSession session = new MongoSession(sessionId, 1800);
given(this.converter.convert(document, TypeDescriptor.valueOf(Document.class),
TypeDescriptor.valueOf(MongoSession.class))).willReturn(session);
TypeDescriptor.valueOf(MongoSession.class)))
.willReturn(session);
// when
Map<String, MongoSession> sessionsMap = this.repository.findByIndexNameAndIndexValue(principalNameIndexName,

View File

@@ -83,14 +83,14 @@ public class ReactiveMongoSessionRepositoryTest {
void shouldCreateSession() {
this.repository.createSession() //
.as(StepVerifier::create) //
.expectNextMatches((mongoSession) -> {
assertThat(mongoSession.getId()).isNotEmpty();
assertThat(mongoSession.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
return true;
}) //
.verifyComplete();
.as(StepVerifier::create) //
.expectNextMatches((mongoSession) -> {
assertThat(mongoSession.getId()).isNotEmpty();
assertThat(mongoSession.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
return true;
}) //
.verifyComplete();
}
@Test
@@ -101,14 +101,15 @@ public class ReactiveMongoSessionRepositoryTest {
BasicDBObject dbSession = new BasicDBObject();
given(this.converter.convert(session, TypeDescriptor.valueOf(MongoSession.class),
TypeDescriptor.valueOf(DBObject.class))).willReturn(dbSession);
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();
.as(StepVerifier::create) //
.verifyComplete();
verify(this.mongoOperations).save(dbSession, ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME);
}
@@ -121,18 +122,20 @@ public class ReactiveMongoSessionRepositoryTest {
Document sessionDocument = new Document();
given(this.mongoOperations.findById(sessionId, Document.class,
ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument));
ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME))
.willReturn(Mono.just(sessionDocument));
MongoSession session = new MongoSession();
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) //
.expectNext(session) //
.verifyComplete();
.as(StepVerifier::create) //
.expectNext(session) //
.verifyComplete();
}
@Test
@@ -143,21 +146,23 @@ public class ReactiveMongoSessionRepositoryTest {
Document sessionDocument = new Document();
given(this.mongoOperations.findById(sessionId, Document.class,
ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument));
ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME))
.willReturn(Mono.just(sessionDocument));
given(this.mongoOperations.remove(sessionDocument, ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME))
.willReturn(Mono.just(DeleteResult.acknowledged(1)));
.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();
.as(StepVerifier::create) //
.verifyComplete();
// then
verify(this.mongoOperations).remove(any(Document.class),
@@ -172,20 +177,22 @@ public class ReactiveMongoSessionRepositoryTest {
Document sessionDocument = new Document();
given(this.mongoOperations.findById(sessionId, Document.class,
ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument));
ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME))
.willReturn(Mono.just(sessionDocument));
given(this.mongoOperations.remove(sessionDocument, "sessions"))
.willReturn(Mono.just(DeleteResult.acknowledged(1)));
.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();
.as(StepVerifier::create) //
.verifyComplete();
verify(this.mongoOperations).remove(any(Document.class),
eq(ReactiveMongoSessionRepository.DEFAULT_COLLECTION_NAME));

View File

@@ -72,8 +72,8 @@ public class MongoHttpSessionConfigurationTest {
void noMongoOperationsConfiguration() {
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(() -> registerAndRefresh(EmptyConfiguration.class))
.withMessageContaining("mongoSessionRepository");
.isThrownBy(() -> registerAndRefresh(EmptyConfiguration.class))
.withMessageContaining("mongoSessionRepository");
}
@Test
@@ -114,7 +114,7 @@ public class MongoHttpSessionConfigurationTest {
MongoIndexedSessionRepository repository = this.context.getBean(MongoIndexedSessionRepository.class);
assertThat(repository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -125,7 +125,7 @@ public class MongoHttpSessionConfigurationTest {
MongoIndexedSessionRepository repository = this.context.getBean(MongoIndexedSessionRepository.class);
assertThat(repository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -145,7 +145,7 @@ public class MongoHttpSessionConfigurationTest {
void resolveCollectionNameByPropertyPlaceholder() {
this.context
.setEnvironment(new MockEnvironment().withProperty("session.mongo.collectionName", COLLECTION_NAME));
.setEnvironment(new MockEnvironment().withProperty("session.mongo.collectionName", COLLECTION_NAME));
registerAndRefresh(CustomMongoJdbcSessionConfiguration.class);
MongoHttpSessionConfiguration configuration = this.context.getBean(MongoHttpSessionConfiguration.class);
@@ -174,8 +174,8 @@ public class MongoHttpSessionConfigurationTest {
assertThat(repository).isNotNull();
assertThat(indexResolver).isNotNull();
assertThat(repository).extracting("mongoSessionConverter").hasFieldOrPropertyWithValue("indexResolver",
indexResolver);
assertThat(repository).extracting("mongoSessionConverter")
.hasFieldOrPropertyWithValue("indexResolver", indexResolver);
}
@Test
@@ -189,8 +189,8 @@ public class MongoHttpSessionConfigurationTest {
assertThat(repository).isNotNull();
assertThat(indexResolver).isNotNull();
assertThat(repository).extracting("mongoSessionConverter").hasFieldOrPropertyWithValue("indexResolver",
indexResolver);
assertThat(repository).extracting("mongoSessionConverter")
.hasFieldOrPropertyWithValue("indexResolver", indexResolver);
}
@Test

View File

@@ -95,9 +95,8 @@ public class ReactiveMongoWebSessionConfigurationTest {
this.context.register(BadConfig.class);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(this.context::refresh)
.withMessageContaining("Error creating bean with name 'reactiveMongoSessionRepository'")
.withMessageContaining(
"No qualifying bean of type '" + ReactiveMongoOperations.class.getCanonicalName());
.withMessageContaining("Error creating bean with name 'reactiveMongoSessionRepository'")
.withMessageContaining("No qualifying bean of type '" + ReactiveMongoOperations.class.getCanonicalName());
}
@Test
@@ -193,8 +192,8 @@ public class ReactiveMongoWebSessionConfigurationTest {
assertThat(repository).isNotNull();
assertThat(indexResolver).isNotNull();
assertThat(repository).extracting("mongoSessionConverter").hasFieldOrPropertyWithValue("indexResolver",
indexResolver);
assertThat(repository).extracting("mongoSessionConverter")
.hasFieldOrPropertyWithValue("indexResolver", indexResolver);
}
@Test
@@ -209,8 +208,8 @@ public class ReactiveMongoWebSessionConfigurationTest {
assertThat(repository).isNotNull();
assertThat(indexResolver).isNotNull();
assertThat(repository).extracting("mongoSessionConverter").hasFieldOrPropertyWithValue("indexResolver",
indexResolver);
assertThat(repository).extracting("mongoSessionConverter")
.hasFieldOrPropertyWithValue("indexResolver", indexResolver);
}
@Test

View File

@@ -81,7 +81,7 @@ class ReactiveRedisSessionRepositoryITests extends AbstractRedisITests {
assertThat(session.getId()).isEqualTo(toSave.getId());
assertThat(session.getAttributeNames()).isEqualTo(toSave.getAttributeNames());
assertThat(session.<String>getAttribute(expectedAttributeName))
.isEqualTo(toSave.getAttribute(expectedAttributeName));
.isEqualTo(toSave.getAttribute(expectedAttributeName));
this.repository.deleteById(toSave.getId()).block();
@@ -229,7 +229,7 @@ class ReactiveRedisSessionRepositoryITests extends AbstractRedisITests {
toSave.setLastAccessedTime(Instant.now());
assertThatIllegalStateException().isThrownBy(() -> this.repository.save(toSave).block())
.withMessage("Session was invalidated");
.withMessage("Session was invalidated");
assertThat(this.repository.findById(sessionId).block()).isNull();
assertThat(this.repository.findById(session.getId()).block()).isNotNull();
@@ -240,7 +240,7 @@ class ReactiveRedisSessionRepositoryITests extends AbstractRedisITests {
@SuppressWarnings("unchecked")
void saveChangeSessionIdAfterCheckWhenOriginalKeyDoesNotExistsThenIgnoreError() {
ReactiveRedisOperations<String, Object> sessionRedisOperations = (ReactiveRedisOperations<String, Object>) ReflectionTestUtils
.getField(this.repository, "sessionRedisOperations");
.getField(this.repository, "sessionRedisOperations");
ReactiveRedisOperations<String, Object> spyOperations = spy(sessionRedisOperations);
ReflectionTestUtils.setField(this.repository, "sessionRedisOperations", spyOperations);
@@ -267,7 +267,8 @@ class ReactiveRedisSessionRepositoryITests extends AbstractRedisITests {
ReactiveHashOperations<String, Object, Object> opsForHash = spy(this.sessionRedisOperations.opsForHash());
given(spy.opsForHash()).willReturn(opsForHash);
willAnswer((invocation) -> Mono.delay(Duration.ofSeconds(1)).then((Mono<Void>) invocation.callRealMethod()))
.given(opsForHash).putAll(anyString(), any());
.given(opsForHash)
.putAll(anyString(), any());
RedisSession toSave = this.repository.createSession().block();
String expectedAttributeName = "a";

View File

@@ -81,7 +81,7 @@ class RedisIndexedSessionRepositoryDynamicITests extends AbstractRedisITests {
this.context.refresh();
this.sessionRepository = this.context.getBean(RedisIndexedSessionRepository.class);
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(this.sessionRepository, "sessionRedisOperations");
.getField(this.sessionRepository, "sessionRedisOperations");
this.spyOperations = spy(redisOperations);
ReflectionTestUtils.setField(this.sessionRepository, "sessionRedisOperations", this.spyOperations);
}

View File

@@ -119,7 +119,7 @@ class RedisIndexedSessionRepositoryITests extends AbstractRedisITests {
assertThat(session.getId()).isEqualTo(toSave.getId());
assertThat(session.getAttributeNames()).isEqualTo(toSave.getAttributeNames());
assertThat(session.<String>getAttribute(expectedAttributeName))
.isEqualTo(toSave.getAttribute(expectedAttributeName));
.isEqualTo(toSave.getAttribute(expectedAttributeName));
this.registry.clear();
@@ -127,11 +127,11 @@ class RedisIndexedSessionRepositoryITests extends AbstractRedisITests {
assertThat(this.repository.findById(toSave.getId())).isNull();
assertThat(this.registry.<SessionDestroyedEvent>getEvent(toSave.getId()))
.isInstanceOf(SessionDestroyedEvent.class);
.isInstanceOf(SessionDestroyedEvent.class);
assertThat(this.redis.boundSetOps(usernameSessionKey).members()).doesNotContain(toSave.getId());
assertThat(this.registry.getEvent(toSave.getId()).getSession().<String>getAttribute(expectedAttributeName))
.isEqualTo(expectedAttributeValue);
.isEqualTo(expectedAttributeValue);
}
@Test

View File

@@ -54,7 +54,7 @@ class RedisSessionRepositoryITests extends AbstractRedisITests {
void save_NewSession_ShouldSaveSession() {
RedisSession session = createAndSaveSession(Instant.now());
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
assertThat(session.getAttributeNames()).isEqualTo(Collections.singleton("attribute1"));
assertThat(session.<String>getAttribute("attribute1")).isEqualTo("value1");
}
@@ -69,7 +69,7 @@ class RedisSessionRepositoryITests extends AbstractRedisITests {
RedisSession session = createAndSaveSession(Instant.now());
this.sessionRepository.deleteById(session.getId());
assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(session))
.withMessage("Session was invalidated");
.withMessage("Session was invalidated");
}
@Test
@@ -160,7 +160,7 @@ class RedisSessionRepositoryITests extends AbstractRedisITests {
updateSession(session, Instant.now(), "attribute1", "value1");
String newSessionId = session.changeSessionId();
assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(session))
.withMessage("Session was invalidated");
.withMessage("Session was invalidated");
assertThat(this.sessionRepository.findById(newSessionId)).isNull();
assertThat(this.sessionRepository.findById(originalSessionId)).isNull();
}
@@ -177,7 +177,7 @@ class RedisSessionRepositoryITests extends AbstractRedisITests {
updateSession(copy2, now.plusSeconds(2L), "attribute3", "value3");
String newSessionId2 = copy2.changeSessionId();
assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(copy2))
.withMessage("Session was invalidated");
.withMessage("Session was invalidated");
assertThat(this.sessionRepository.findById(newSessionId1)).isNotNull();
assertThat(this.sessionRepository.findById(newSessionId2)).isNull();
assertThat(this.sessionRepository.findById(originalSessionId)).isNull();

View File

@@ -56,7 +56,7 @@ class RedisListenerContainerTaskExecutorITests extends AbstractRedisITests {
@Test
void testRedisDelEventsAreDispatchedInSessionTaskExecutor() throws InterruptedException {
BoundSetOperations<Object, Object> ops = this.redis
.boundSetOps("spring:session:RedisListenerContainerTaskExecutorITests:expirations:dummy");
.boundSetOps("spring:session:RedisListenerContainerTaskExecutorITests:expirations:dummy");
ops.add("value");
ops.remove("value");
assertThat(this.executor.taskDispatched()).isTrue();

View File

@@ -133,8 +133,9 @@ public class ReactiveRedisSessionRepository
return session.save();
}
String sessionKey = getSessionKey(session.hasChangedSessionId() ? session.originalSessionId : session.getId());
return this.sessionRedisOperations.hasKey(sessionKey).flatMap(
(exists) -> exists ? session.save() : Mono.error(new IllegalStateException("Session was invalidated")));
return this.sessionRedisOperations.hasKey(sessionKey)
.flatMap((exists) -> exists ? session.save()
: Mono.error(new IllegalStateException("Session was invalidated")));
}
@Override
@@ -283,7 +284,7 @@ public class ReactiveRedisSessionRepository
String sessionKey = getSessionKey(getId());
Mono<Boolean> update = ReactiveRedisSessionRepository.this.sessionRedisOperations.opsForHash()
.putAll(sessionKey, new HashMap<>(this.delta));
.putAll(sessionKey, new HashMap<>(this.delta));
Mono<Boolean> setTtl;
if (getMaxInactiveInterval().getSeconds() >= 0) {
setTtl = ReactiveRedisSessionRepository.this.sessionRedisOperations.expire(sessionKey,
@@ -320,10 +321,11 @@ public class ReactiveRedisSessionRepository
String sessionKey = getSessionKey(sessionId);
return ReactiveRedisSessionRepository.this.sessionRedisOperations.rename(originalSessionKey, sessionKey)
.flatMap((unused) -> Mono.fromDirect(replaceSessionId)).onErrorResume((ex) -> {
String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
return StringUtils.startsWithIgnoreCase(message, "ERR no such key");
}, (ex) -> Mono.empty());
.flatMap((unused) -> Mono.fromDirect(replaceSessionId))
.onErrorResume((ex) -> {
String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
return StringUtils.startsWithIgnoreCase(message, "ERR no such key");
}, (ex) -> Mono.empty());
}
}

View File

@@ -857,7 +857,7 @@ public class RedisIndexedSessionRepository
if (this.originalPrincipalName != null) {
String originalPrincipalRedisKey = getPrincipalKey(this.originalPrincipalName);
RedisIndexedSessionRepository.this.sessionRedisOperations.boundSetOps(originalPrincipalRedisKey)
.remove(sessionId);
.remove(sessionId);
}
Map<String, String> indexes = RedisIndexedSessionRepository.this.indexResolver.resolveIndexesFor(this);
String principal = indexes.get(PRINCIPAL_NAME_INDEX_NAME);
@@ -865,7 +865,7 @@ public class RedisIndexedSessionRepository
if (principal != null) {
String principalRedisKey = getPrincipalKey(principal);
RedisIndexedSessionRepository.this.sessionRedisOperations.boundSetOps(principalRedisKey)
.add(sessionId);
.add(sessionId);
}
}
if (this.isNew) {
@@ -905,9 +905,9 @@ public class RedisIndexedSessionRepository
if (this.originalPrincipalName != null) {
String originalPrincipalRedisKey = getPrincipalKey(this.originalPrincipalName);
RedisIndexedSessionRepository.this.sessionRedisOperations.boundSetOps(originalPrincipalRedisKey)
.remove(this.originalSessionId);
.remove(this.originalSessionId);
RedisIndexedSessionRepository.this.sessionRedisOperations.boundSetOps(originalPrincipalRedisKey)
.add(sessionId);
.add(sessionId);
}
}
this.originalSessionId = sessionId;

View File

@@ -298,7 +298,7 @@ public class RedisSessionRepository implements SessionRepository<RedisSessionRep
RedisSessionRepository.this.sessionRedisOperations.opsForHash().putAll(key, new HashMap<>(this.delta));
RedisSessionRepository.this.sessionRedisOperations.expireAt(key,
Instant.ofEpochMilli(getLastAccessedTime().toEpochMilli())
.plusSeconds(getMaxInactiveInterval().getSeconds()));
.plusSeconds(getMaxInactiveInterval().getSeconds()));
this.delta.clear();
}

View File

@@ -119,7 +119,7 @@ public abstract class AbstractRedisHttpSessionConfiguration<T extends SessionRep
@SpringSessionRedisConnectionFactory ObjectProvider<RedisConnectionFactory> springSessionRedisConnectionFactory,
ObjectProvider<RedisConnectionFactory> redisConnectionFactory) {
this.redisConnectionFactory = springSessionRedisConnectionFactory
.getIfAvailable(redisConnectionFactory::getObject);
.getIfAvailable(redisConnectionFactory::getObject);
}
protected RedisConnectionFactory getRedisConnectionFactory() {

View File

@@ -61,7 +61,7 @@ public class RedisHttpSessionConfiguration extends AbstractRedisHttpSessionConfi
sessionRepository.setFlushMode(getFlushMode());
sessionRepository.setSaveMode(getSaveMode());
getSessionRepositoryCustomizers()
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
return sessionRepository;
}
@@ -73,7 +73,7 @@ public class RedisHttpSessionConfiguration extends AbstractRedisHttpSessionConfi
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableRedisHttpSession.class.getName());
.getAnnotationAttributes(EnableRedisHttpSession.class.getName());
AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;

View File

@@ -102,7 +102,7 @@ public class RedisIndexedHttpSessionConfiguration
int database = resolveDatabase();
sessionRepository.setDatabase(database);
getSessionRepositoryCustomizers()
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
return sessionRepository;
}
@@ -174,7 +174,7 @@ public class RedisIndexedHttpSessionConfiguration
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableRedisIndexedHttpSession.class.getName());
.getAnnotationAttributes(EnableRedisIndexedHttpSession.class.getName());
AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;

View File

@@ -87,7 +87,7 @@ public class RedisWebSessionConfiguration implements BeanClassLoaderAware, Embed
}
sessionRepository.setSaveMode(this.saveMode);
this.sessionRepositoryCustomizers
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
return sessionRepository;
}
@@ -113,7 +113,7 @@ public class RedisWebSessionConfiguration implements BeanClassLoaderAware, Embed
@SpringSessionRedisConnectionFactory ObjectProvider<ReactiveRedisConnectionFactory> springSessionRedisConnectionFactory,
ObjectProvider<ReactiveRedisConnectionFactory> redisConnectionFactory) {
ReactiveRedisConnectionFactory redisConnectionFactoryToUse = springSessionRedisConnectionFactory
.getIfAvailable();
.getIfAvailable();
if (redisConnectionFactoryToUse == null) {
redisConnectionFactoryToUse = redisConnectionFactory.getObject();
}
@@ -145,7 +145,7 @@ public class RedisWebSessionConfiguration implements BeanClassLoaderAware, Embed
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableRedisWebSession.class.getName());
.getAnnotationAttributes(EnableRedisWebSession.class.getName());
AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;
@@ -163,8 +163,10 @@ public class RedisWebSessionConfiguration implements BeanClassLoaderAware, Embed
RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer
: new JdkSerializationRedisSerializer(this.classLoader);
RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
.<String, Object>newSerializationContext(defaultSerializer).key(keySerializer).hashKey(keySerializer)
.build();
.<String, Object>newSerializationContext(defaultSerializer)
.key(keySerializer)
.hashKey(keySerializer)
.build();
return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext);
}

View File

@@ -79,7 +79,7 @@ class ReactiveRedisSessionRepositoryTests {
@Test
void constructorWithNullReactiveRedisOperations() {
assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveRedisSessionRepository(null))
.withMessageContaining("sessionRedisOperations cannot be null");
.withMessageContaining("sessionRedisOperations cannot be null");
}
@Test
@@ -92,13 +92,13 @@ class ReactiveRedisSessionRepositoryTests {
@Test
void nullRedisKeyNamespace() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisKeyNamespace(null))
.withMessage("namespace cannot be null or empty");
.withMessage("namespace cannot be null or empty");
}
@Test
void emptyRedisKeyNamespace() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisKeyNamespace(""))
.withMessage("namespace cannot be null or empty");
.withMessage("namespace cannot be null or empty");
}
@Test
@@ -112,9 +112,9 @@ class ReactiveRedisSessionRepositoryTests {
@Test
void createSessionDefaultMaxInactiveInterval() {
StepVerifier.create(this.repository.createSession())
.consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)))
.verifyComplete();
.consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)))
.verifyComplete();
}
@Test
@@ -123,8 +123,8 @@ class ReactiveRedisSessionRepositoryTests {
this.repository.setDefaultMaxInactiveInterval(interval);
StepVerifier.create(this.repository.createSession())
.consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval()).isEqualTo(interval))
.verifyComplete();
.consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval()).isEqualTo(interval))
.verifyComplete();
}
@Test
@@ -145,11 +145,11 @@ class ReactiveRedisSessionRepositoryTests {
Map<String, Object> delta = this.delta.getAllValues().get(0);
assertThat(delta.size()).isEqualTo(3);
assertThat(delta.get(RedisSessionMapper.CREATION_TIME_KEY))
.isEqualTo(newSession.getCreationTime().toEpochMilli());
.isEqualTo(newSession.getCreationTime().toEpochMilli());
assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
.isEqualTo((int) newSession.getMaxInactiveInterval().getSeconds());
.isEqualTo((int) newSession.getMaxInactiveInterval().getSeconds());
assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY))
.isEqualTo(newSession.getLastAccessedTime().toEpochMilli());
.isEqualTo(newSession.getLastAccessedTime().toEpochMilli());
}
@Test
@@ -172,11 +172,11 @@ class ReactiveRedisSessionRepositoryTests {
Map<String, Object> delta = this.delta.getAllValues().get(0);
assertThat(delta.size()).isEqualTo(3);
assertThat(delta.get(RedisSessionMapper.CREATION_TIME_KEY))
.isEqualTo(newSession.getCreationTime().toEpochMilli());
.isEqualTo(newSession.getCreationTime().toEpochMilli());
assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
.isEqualTo((int) newSession.getMaxInactiveInterval().getSeconds());
.isEqualTo((int) newSession.getMaxInactiveInterval().getSeconds());
assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY))
.isEqualTo(newSession.getLastAccessedTime().toEpochMilli());
.isEqualTo(newSession.getLastAccessedTime().toEpochMilli());
}
@Test
@@ -211,8 +211,8 @@ class ReactiveRedisSessionRepositoryTests {
verifyNoMoreInteractions(this.redisOperations);
verifyNoMoreInteractions(this.hashOperations);
assertThat(this.delta.getAllValues().get(0)).isEqualTo(
map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
assertThat(this.delta.getAllValues().get(0))
.isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
}
@Test
@@ -258,7 +258,7 @@ class ReactiveRedisSessionRepositoryTests {
verifyNoMoreInteractions(this.hashOperations);
assertThat(this.delta.getAllValues().get(0))
.isEqualTo(map(RedisIndexedSessionRepository.getSessionAttrNameKey(attrName), null));
.isEqualTo(map(RedisIndexedSessionRepository.getSessionAttrNameKey(attrName), null));
}
@Test
@@ -328,10 +328,10 @@ class ReactiveRedisSessionRepositoryTests {
assertThat(session.<String>getAttribute(attribute1)).isEqualTo(expected.getAttribute(attribute1));
assertThat(session.<String>getAttribute(attribute2)).isEqualTo(expected.getAttribute(attribute2));
assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
assertThat(session.getMaxInactiveInterval()).isEqualTo(expected.getMaxInactiveInterval());
assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS));
}).verifyComplete();
}

View File

@@ -112,7 +112,7 @@ class RedisIndexedSessionRepositoryTests {
@Test
void setApplicationEventPublisherNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setApplicationEventPublisher(null))
.withMessage("applicationEventPublisher cannot be null");
.withMessage("applicationEventPublisher cannot be null");
}
@Test
@@ -178,9 +178,9 @@ class RedisIndexedSessionRepositoryTests {
Object creationTime = delta.get(RedisSessionMapper.CREATION_TIME_KEY);
assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli());
assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY))
.isEqualTo(session.getCreationTime().toEpochMilli());
.isEqualTo(session.getCreationTime().toEpochMilli());
}
// gh-467
@@ -199,7 +199,7 @@ class RedisIndexedSessionRepositoryTests {
String sessionKey = "spring:session:sessions:" + session.getId();
String backgroundExpireKey = "spring:session:expirations:" + RedisSessionExpirationPolicy
.roundUpToNextMinute(RedisSessionExpirationPolicy.expiresInMillis(session));
.roundUpToNextMinute(RedisSessionExpirationPolicy.expiresInMillis(session));
String destroyedTriggerKey = "spring:session:sessions:expires:" + session.getId();
given(this.redisOperations.<String, Object>boundHashOps(sessionKey)).willReturn(this.boundHashOperations);
@@ -226,11 +226,11 @@ class RedisIndexedSessionRepositoryTests {
session.setLastAccessedTime(session.getLastAccessedTime());
given(this.redisOperations.<String, Object>boundHashOps("spring:session:sessions:session-id"))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
given(this.redisOperations.boundSetOps("spring:session:expirations:1404361860000"))
.willReturn(this.boundSetOperations);
.willReturn(this.boundSetOperations);
given(this.redisOperations.boundValueOps("spring:session:sessions:expires:session-id"))
.willReturn(this.boundValueOperations);
.willReturn(this.boundValueOperations);
this.redisRepository.save(session);
@@ -252,8 +252,8 @@ class RedisIndexedSessionRepositoryTests {
this.redisRepository.save(session);
assertThat(getDelta()).isEqualTo(
map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
assertThat(getDelta())
.isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
}
@Test
@@ -362,7 +362,7 @@ class RedisIndexedSessionRepositoryTests {
expected.setAttribute(attribute1, "test");
expected.setAttribute(attribute2, null);
given(this.redisOperations.<String, Object>boundHashOps(getKey(expected.getId())))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
Map<String, Object> map = map(RedisIndexedSessionRepository.getSessionAttrNameKey(attribute1),
expected.getAttribute(attribute1), RedisIndexedSessionRepository.getSessionAttrNameKey(attribute2),
expected.getAttribute(attribute2), RedisSessionMapper.CREATION_TIME_KEY,
@@ -377,17 +377,17 @@ class RedisIndexedSessionRepositoryTests {
assertThat(session.<String>getAttribute(attribute1)).isEqualTo(expected.getAttribute(attribute1));
assertThat(session.<String>getAttribute(attribute2)).isEqualTo(expected.getAttribute(attribute2));
assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
assertThat(session.getMaxInactiveInterval()).isEqualTo(expected.getMaxInactiveInterval());
assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS));
}
@Test
void getSessionExpired() {
String expiredId = "expired-id";
given(this.redisOperations.<String, Object>boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
Map<String, Object> map = map(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
@@ -402,15 +402,15 @@ class RedisIndexedSessionRepositoryTests {
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.singleton(expiredId));
given(this.redisOperations.<String, Object>boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
Map<String, Object> map = map(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
assertThat(this.redisRepository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"))
.isEmpty();
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"))
.isEmpty();
}
@Test
@@ -422,24 +422,24 @@ class RedisIndexedSessionRepositoryTests {
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.singleton(sessionId));
given(this.redisOperations.<String, Object>boundHashOps(getKey(sessionId)))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
Map<String, Object> map = map(RedisSessionMapper.CREATION_TIME_KEY, createdTime.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) maxInactive.getSeconds(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, lastAccessed.toEpochMilli());
given(this.boundHashOperations.entries()).willReturn(map);
Map<String, RedisSession> sessionIdToSessions = this.redisRepository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal");
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal");
assertThat(sessionIdToSessions).hasSize(1);
RedisSession session = sessionIdToSessions.get(sessionId);
assertThat(session).isNotNull();
assertThat(session.getId()).isEqualTo(sessionId);
assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(lastAccessed.truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(lastAccessed.truncatedTo(ChronoUnit.MILLIS));
assertThat(session.getMaxInactiveInterval()).isEqualTo(maxInactive);
assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(createdTime.truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(createdTime.truncatedTo(ChronoUnit.MILLIS));
}
@Test
@@ -503,7 +503,7 @@ class RedisIndexedSessionRepositoryTests {
void onMessageDeletedSessionFound() {
String deletedId = "deleted-id";
given(this.redisOperations.<String, Object>boundHashOps(getKey(deletedId)))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
Map<String, Object> map = map(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 0, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
@@ -531,7 +531,7 @@ class RedisIndexedSessionRepositoryTests {
void onMessageDeletedSessionNotFound() {
String deletedId = "deleted-id";
given(this.redisOperations.<String, Object>boundHashOps(getKey(deletedId)))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
given(this.boundHashOperations.entries()).willReturn(map());
String channel = "__keyevent@0__:del";
@@ -554,7 +554,7 @@ class RedisIndexedSessionRepositoryTests {
void onMessageExpiredSessionFound() {
String expiredId = "expired-id";
given(this.redisOperations.<String, Object>boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
Map<String, Object> map = map(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5));
@@ -582,7 +582,7 @@ class RedisIndexedSessionRepositoryTests {
void onMessageExpiredSessionNotFound() {
String expiredId = "expired-id";
given(this.redisOperations.<String, Object>boundHashOps(getKey(expiredId)))
.willReturn(this.boundHashOperations);
.willReturn(this.boundHashOperations);
given(this.boundHashOperations.entries()).willReturn(map());
String channel = "__keyevent@0__:expired";
@@ -654,9 +654,9 @@ class RedisIndexedSessionRepositoryTests {
Object creationTime = delta.get(RedisSessionMapper.CREATION_TIME_KEY);
assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli());
assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY))
.isEqualTo(session.getCreationTime().toEpochMilli());
.isEqualTo(session.getCreationTime().toEpochMilli());
}
@Test // gh-1409
@@ -736,26 +736,26 @@ class RedisIndexedSessionRepositoryTests {
Map<String, Object> delta = getDelta(2);
assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo(
map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
assertThat(delta)
.isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli()));
}
@Test
void setFlushModeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setFlushMode(null))
.withMessage("flushMode cannot be null");
.withMessage("flushMode cannot be null");
}
@Test
void setCleanupCronNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setCleanupCron(null))
.withMessage("cleanupCron must not be null");
.withMessage("cleanupCron must not be null");
}
@Test
void setCleanupCronInvalid() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setCleanupCron("test"))
.withMessage("cleanupCron must be valid");
.withMessage("cleanupCron must be valid");
}
@Test
@@ -784,13 +784,13 @@ class RedisIndexedSessionRepositoryTests {
@Test
void setRedisKeyNamespaceNullNamespace() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(null))
.withMessage("namespace cannot be null or empty");
.withMessage("namespace cannot be null or empty");
}
@Test
void setRedisKeyNamespaceEmptyNamespace() {
assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(" "))
.withMessage("namespace cannot be null or empty");
.withMessage("namespace cannot be null or empty");
}
@Test // gh-1120

View File

@@ -84,7 +84,7 @@ class RedisSessionExpirationPolicyTests {
void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp() {
long originalExpirationTimeInMs = ONE_MINUTE_AGO;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy
.roundUpToNextMinute(originalExpirationTimeInMs);
.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);
@@ -98,7 +98,7 @@ class RedisSessionExpirationPolicyTests {
void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange() {
long originalExpirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session) - 10;
long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy
.roundUpToNextMinute(originalExpirationTimeInMs);
.roundUpToNextMinute(originalExpirationTimeInMs);
String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs);
this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session);

View File

@@ -48,25 +48,25 @@ class RedisSessionMapperTests {
@Test
void constructor_NullId_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new RedisSessionMapper(null))
.withMessage("sessionId must not be empty");
.withMessage("sessionId must not be empty");
}
@Test
void constructor_EmptyId_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new RedisSessionMapper(" "))
.withMessage("sessionId must not be empty");
.withMessage("sessionId must not be empty");
}
@Test
void apply_NullMap_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.mapper.apply(null))
.withMessage("map must not be empty");
.withMessage("map must not be empty");
}
@Test
void apply_EmptyMap_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.mapper.apply(Collections.emptyMap()))
.withMessage("map must not be empty");
.withMessage("map must not be empty");
}
@Test
@@ -75,7 +75,7 @@ class RedisSessionMapperTests {
sessionMap.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, 0L);
sessionMap.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1800);
assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap))
.withMessage(RedisSessionMapper.CREATION_TIME_KEY + " key must not be null");
.withMessage(RedisSessionMapper.CREATION_TIME_KEY + " key must not be null");
}
@Test
@@ -84,7 +84,7 @@ class RedisSessionMapperTests {
sessionMap.put(RedisSessionMapper.CREATION_TIME_KEY, 0L);
sessionMap.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1800);
assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap))
.withMessage(RedisSessionMapper.LAST_ACCESSED_TIME_KEY + " key must not be null");
.withMessage(RedisSessionMapper.LAST_ACCESSED_TIME_KEY + " key must not be null");
}
@Test
@@ -93,7 +93,7 @@ class RedisSessionMapperTests {
sessionMap.put(RedisSessionMapper.CREATION_TIME_KEY, 0L);
sessionMap.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, 0L);
assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap))
.withMessage(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY + " key must not be null");
.withMessage(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY + " key must not be null");
}
@Test

View File

@@ -79,21 +79,21 @@ class RedisSessionRepositoryTests {
@Test
void constructor_NullRedisOperations_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveRedisSessionRepository(null))
.withMessageContaining("sessionRedisOperations cannot be null");
.withMessageContaining("sessionRedisOperations cannot be null");
}
@Test
void setDefaultMaxInactiveInterval_ValidInterval_ShouldSetInterval() {
this.sessionRepository.setDefaultMaxInactiveInterval(Duration.ofMinutes(10));
assertThat(ReflectionTestUtils.getField(this.sessionRepository, "defaultMaxInactiveInterval"))
.isEqualTo(Duration.ofMinutes(10));
.isEqualTo(Duration.ofMinutes(10));
}
@Test
void setDefaultMaxInactiveInterval_NullInterval_ShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.sessionRepository.setDefaultMaxInactiveInterval(null))
.withMessage("defaultMaxInactiveInterval must not be null");
.isThrownBy(() -> this.sessionRepository.setDefaultMaxInactiveInterval(null))
.withMessage("defaultMaxInactiveInterval must not be null");
}
@Test
@@ -105,13 +105,13 @@ class RedisSessionRepositoryTests {
@Test
void setRedisKeyNamespace_NullNamespace_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setRedisKeyNamespace(null))
.withMessage("namespace must not be empty");
.withMessage("namespace must not be empty");
}
@Test
void setRedisKeyNamespace_EmptyNamespace_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setRedisKeyNamespace(" "))
.withMessage("namespace must not be empty");
.withMessage("namespace must not be empty");
}
@Test
@@ -123,27 +123,27 @@ class RedisSessionRepositoryTests {
@Test
void setFlushMode_NullFlushMode_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setFlushMode(null))
.withMessage("flushMode must not be null");
.withMessage("flushMode must not be null");
}
@Test
void setSaveMode_ValidSaveMode_ShouldSetSaveMode() {
this.sessionRepository.setSaveMode(SaveMode.ON_GET_ATTRIBUTE);
assertThat(ReflectionTestUtils.getField(this.sessionRepository, "saveMode"))
.isEqualTo(SaveMode.ON_GET_ATTRIBUTE);
.isEqualTo(SaveMode.ON_GET_ATTRIBUTE);
}
@Test
void setSaveMode_NullSaveMode_ShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setSaveMode(null))
.withMessage("saveMode must not be null");
.withMessage("saveMode must not be null");
}
@Test
void createSession_DefaultMaxInactiveInterval_ShouldCreateSession() {
RedisSession redisSession = this.sessionRepository.createSession();
assertThat(redisSession.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
verifyNoMoreInteractions(this.sessionRedisOperations);
verifyNoMoreInteractions(this.sessionHashOperations);
}
@@ -304,7 +304,7 @@ class RedisSessionRepositoryTests {
void save_SessionNotExists_ShouldThrowException() {
RedisSession session = createTestSession();
assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(session))
.withMessage("Session was invalidated");
.withMessage("Session was invalidated");
verify(this.sessionRedisOperations).hasKey(eq(TEST_SESSION_KEY));
verifyNoMoreInteractions(this.sessionRedisOperations);
verifyNoMoreInteractions(this.sessionHashOperations);
@@ -315,16 +315,16 @@ class RedisSessionRepositoryTests {
void findById_SessionExists_ShouldReturnSession() {
Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY)))
.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, now.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, now.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
RedisSession session = this.sessionRepository.findById(TEST_SESSION_ID);
assertThat(session.getId()).isEqualTo(TEST_SESSION_ID);
assertThat(session.getCreationTime()).isEqualTo(Instant.EPOCH);
assertThat(session.getLastAccessedTime()).isEqualTo(now);
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
assertThat(session.getAttributeNames()).isEqualTo(Collections.singleton("attribute1"));
assertThat(session.<String>getAttribute("attribute1")).isEqualTo("value1");
verify(this.sessionRedisOperations).opsForHash();
@@ -337,10 +337,10 @@ class RedisSessionRepositoryTests {
@SuppressWarnings("unchecked")
void findById_SessionExistsAndIsExpired_ShouldReturnNull() {
given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY)))
.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.EPOCH.toEpochMilli(),
RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
assertThat(this.sessionRepository.findById(TEST_SESSION_ID)).isNull();
verify(this.sessionRedisOperations).opsForHash();
verify(this.sessionHashOperations).entries(eq(TEST_SESSION_KEY));
@@ -379,7 +379,7 @@ class RedisSessionRepositoryTests {
private static Instant getExpiry(RedisSession session) {
return Instant.ofEpochMilli(session.getLastAccessedTime().toEpochMilli())
.plusSeconds(session.getMaxInactiveInterval().getSeconds());
.plusSeconds(session.getMaxInactiveInterval().getSeconds());
}
private static Map mapOf(Object... objects) {

View File

@@ -86,7 +86,7 @@ class RedisHttpsSessionConfigurationTests {
@Test
void resolveValueByPlaceholder() {
this.context
.setEnvironment(new MockEnvironment().withProperty("session.redis.namespace", "customRedisNamespace"));
.setEnvironment(new MockEnvironment().withProperty("session.redis.namespace", "customRedisNamespace"));
registerAndRefresh(RedisConfig.class, PropertySourceConfiguration.class,
CustomRedisHttpSessionConfiguration2.class);
RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class);
@@ -127,10 +127,10 @@ class RedisHttpsSessionConfigurationTests {
assertThat(redisConnectionFactory).isNotNull();
@SuppressWarnings("unchecked")
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
.getField(repository, "sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -144,10 +144,10 @@ class RedisHttpsSessionConfigurationTests {
assertThat(redisConnectionFactory).isNotNull();
@SuppressWarnings("unchecked")
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
.getField(repository, "sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -161,10 +161,10 @@ class RedisHttpsSessionConfigurationTests {
assertThat(redisConnectionFactory).isNotNull();
@SuppressWarnings("unchecked")
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
.getField(repository, "sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -178,17 +178,18 @@ class RedisHttpsSessionConfigurationTests {
assertThat(redisConnectionFactory).isNotNull();
@SuppressWarnings("unchecked")
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
.getField(repository, "sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
void multipleConnectionFactoryRedisConfig() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class))
.havingRootCause().withMessageContaining("expected single matching bean but found 2");
.isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class))
.havingRootCause()
.withMessageContaining("expected single matching bean but found 2");
}
@Test
@@ -365,7 +366,7 @@ class RedisHttpsSessionConfigurationTests {
@Order(1)
SessionRepositoryCustomizer<RedisSessionRepository> sessionRepositoryCustomizerTwo() {
return (sessionRepository) -> sessionRepository
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
}

View File

@@ -84,18 +84,18 @@ class RedisIndexedHttpSessionConfigurationTests {
void resolveValue() {
registerAndRefresh(RedisConfig.class, CustomRedisHttpSessionConfiguration.class);
RedisIndexedHttpSessionConfiguration configuration = this.context
.getBean(RedisIndexedHttpSessionConfiguration.class);
.getBean(RedisIndexedHttpSessionConfiguration.class);
assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace")).isEqualTo("myRedisNamespace");
}
@Test
void resolveValueByPlaceholder() {
this.context
.setEnvironment(new MockEnvironment().withProperty("session.redis.namespace", "customRedisNamespace"));
.setEnvironment(new MockEnvironment().withProperty("session.redis.namespace", "customRedisNamespace"));
registerAndRefresh(RedisConfig.class, PropertySourceConfiguration.class,
CustomRedisHttpSessionConfiguration2.class);
RedisIndexedHttpSessionConfiguration configuration = this.context
.getBean(RedisIndexedHttpSessionConfiguration.class);
.getBean(RedisIndexedHttpSessionConfiguration.class);
assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace")).isEqualTo("customRedisNamespace");
}
@@ -141,10 +141,10 @@ class RedisIndexedHttpSessionConfigurationTests {
assertThat(redisConnectionFactory).isNotNull();
@SuppressWarnings("unchecked")
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
.getField(repository, "sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -158,10 +158,10 @@ class RedisIndexedHttpSessionConfigurationTests {
assertThat(redisConnectionFactory).isNotNull();
@SuppressWarnings("unchecked")
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
.getField(repository, "sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -175,10 +175,10 @@ class RedisIndexedHttpSessionConfigurationTests {
assertThat(redisConnectionFactory).isNotNull();
@SuppressWarnings("unchecked")
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
.getField(repository, "sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -192,17 +192,18 @@ class RedisIndexedHttpSessionConfigurationTests {
assertThat(redisConnectionFactory).isNotNull();
@SuppressWarnings("unchecked")
RedisOperations<String, Object> redisOperations = (RedisOperations<String, Object>) ReflectionTestUtils
.getField(repository, "sessionRedisOperations");
.getField(repository, "sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
void multipleConnectionFactoryRedisConfig() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class))
.havingRootCause().withMessageContaining("expected single matching bean but found 2");
.isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class))
.havingRootCause()
.withMessageContaining("expected single matching bean but found 2");
}
@Test
@@ -220,7 +221,7 @@ class RedisIndexedHttpSessionConfigurationTests {
void customRedisMessageListenerContainerConfig() {
registerAndRefresh(RedisConfig.class, CustomRedisMessageListenerContainerConfig.class);
Map<String, RedisMessageListenerContainer> beans = this.context
.getBeansOfType(RedisMessageListenerContainer.class);
.getBeansOfType(RedisMessageListenerContainer.class);
assertThat(beans).hasSize(2);
assertThat(beans).containsKeys("springSessionRedisMessageListenerContainer", "redisMessageListenerContainer");
}
@@ -230,7 +231,7 @@ class RedisIndexedHttpSessionConfigurationTests {
registerAndRefresh(RedisConfig.class, SessionRepositoryCustomizerConfiguration.class);
RedisIndexedSessionRepository sessionRepository = this.context.getBean(RedisIndexedSessionRepository.class);
assertThat(sessionRepository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -428,7 +429,7 @@ class RedisIndexedHttpSessionConfigurationTests {
@Order(1)
SessionRepositoryCustomizer<RedisIndexedSessionRepository> sessionRepositoryCustomizerTwo() {
return (sessionRepository) -> sessionRepository
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
}

View File

@@ -85,10 +85,11 @@ class RedisWebSessionConfigurationTests {
ReactiveRedisSessionRepository repository = this.context.getBean(ReactiveRedisSessionRepository.class);
assertThat(repository).isNotNull();
ReactiveRedisOperations<String, Object> springSessionRedisOperations = this.context
.getBean(SpringSessionRedisOperationsResolvingConfig.class).getSpringSessionRedisOperations();
.getBean(SpringSessionRedisOperationsResolvingConfig.class)
.getSpringSessionRedisOperations();
assertThat(springSessionRedisOperations).isNotNull();
assertThat((ReactiveRedisOperations) ReflectionTestUtils.getField(repository, "sessionRedisOperations"))
.isEqualTo(springSessionRedisOperations);
.isEqualTo(springSessionRedisOperations);
}
@Test
@@ -106,7 +107,7 @@ class RedisWebSessionConfigurationTests {
ReactiveRedisSessionRepository repository = this.context.getBean(ReactiveRedisSessionRepository.class);
assertThat(repository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -136,7 +137,7 @@ class RedisWebSessionConfigurationTests {
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -152,7 +153,7 @@ class RedisWebSessionConfigurationTests {
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -168,7 +169,7 @@ class RedisWebSessionConfigurationTests {
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
@@ -184,15 +185,16 @@ class RedisWebSessionConfigurationTests {
"sessionRedisOperations");
assertThat(redisOperations).isNotNull();
assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
.isEqualTo(redisConnectionFactory);
.isEqualTo(redisConnectionFactory);
}
@Test
void multipleConnectionFactoryRedisConfig() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class))
.havingRootCause().isInstanceOf(NoUniqueBeanDefinitionException.class)
.withMessageContaining("expected single matching bean but found 2");
.isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class))
.havingRootCause()
.isInstanceOf(NoUniqueBeanDefinitionException.class)
.withMessageContaining("expected single matching bean but found 2");
}
@Test
@@ -210,13 +212,17 @@ class RedisWebSessionConfigurationTests {
assertThat(redisOperations).isNotNull();
RedisSerializationContext serializationContext = redisOperations.getSerializationContext();
assertThat(ReflectionTestUtils.getField(serializationContext.getValueSerializationPair().getReader(),
"serializer")).isEqualTo(redisSerializer);
"serializer"))
.isEqualTo(redisSerializer);
assertThat(ReflectionTestUtils.getField(serializationContext.getValueSerializationPair().getWriter(),
"serializer")).isEqualTo(redisSerializer);
"serializer"))
.isEqualTo(redisSerializer);
assertThat(ReflectionTestUtils.getField(serializationContext.getHashValueSerializationPair().getReader(),
"serializer")).isEqualTo(redisSerializer);
"serializer"))
.isEqualTo(redisSerializer);
assertThat(ReflectionTestUtils.getField(serializationContext.getHashValueSerializationPair().getWriter(),
"serializer")).isEqualTo(redisSerializer);
"serializer"))
.isEqualTo(redisSerializer);
}
@Test
@@ -224,7 +230,7 @@ class RedisWebSessionConfigurationTests {
registerAndRefresh(RedisConfig.class, SessionRepositoryCustomizerConfiguration.class);
ReactiveRedisSessionRepository sessionRepository = this.context.getBean(ReactiveRedisSessionRepository.class);
assertThat(sessionRepository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -385,7 +391,7 @@ class RedisWebSessionConfigurationTests {
@Order(1)
ReactiveSessionRepositoryCustomizer<ReactiveRedisSessionRepository> sessionRepositoryCustomizerTwo() {
return (sessionRepository) -> sessionRepository
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
}

View File

@@ -147,7 +147,8 @@ class IndexDocTests {
void newReactiveRedisSessionRepository() {
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();
RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
.<String, Object>newSerializationContext(new JdkSerializationRedisSerializer()).build();
.<String, Object>newSerializationContext(new JdkSerializationRedisSerializer())
.build();
// tag::new-reactiveredissessionrepository[]
// ... create and configure connectionFactory and serializationContext ...

View File

@@ -41,11 +41,12 @@ public class HazelcastHttpSessionConfig {
public HazelcastInstance hazelcastInstance() {
Config config = new Config();
AttributeConfig attributeConfig = new AttributeConfig()
.setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(PrincipalNameExtractor.class.getName());
.setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(PrincipalNameExtractor.class.getName());
config.getMapConfig(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME) // <2>
.addAttributeConfig(attributeConfig).addIndexConfig(
new IndexConfig(IndexType.HASH, HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE));
.addAttributeConfig(attributeConfig)
.addIndexConfig(
new IndexConfig(IndexType.HASH, HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE));
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setImplementation(new HazelcastSessionSerializer()).setTypeClass(MapSession.class);
config.getSerializationConfig().addSerializerConfig(serializerConfig); // <3>

View File

@@ -59,7 +59,7 @@ abstract class AbstractHazelcastIndexedSessionRepositoryITests {
String sessionId = sessionToSave.getId();
IMap<String, MapSession> hazelcastMap = this.hazelcastInstance
.getMap(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);
.getMap(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);
this.repository.save(sessionToSave);
@@ -222,8 +222,8 @@ abstract class AbstractHazelcastIndexedSessionRepositoryITests {
this.repository.save(session);
assertThat(this.repository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username))
.hasSize(1);
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username))
.hasSize(1);
this.repository.deleteById(session.getId());
}
@@ -233,7 +233,7 @@ abstract class AbstractHazelcastIndexedSessionRepositoryITests {
final Duration defaultSessionTimeout = Duration.ofSeconds(1800);
final IMap<String, MapSession> hazelcastMap = this.hazelcastInstance
.getMap(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);
.getMap(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);
HazelcastSession session = this.repository.createSession();
String sessionId = session.getId();
@@ -256,7 +256,7 @@ abstract class AbstractHazelcastIndexedSessionRepositoryITests {
final Duration individualSessionTimeout = Duration.ofSeconds(23);
final IMap<String, MapSession> hazelcastMap = this.hazelcastInstance
.getMap(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);
.getMap(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);
HazelcastSession session = this.repository.createSession();
session.setMaxInactiveInterval(individualSessionTimeout);

View File

@@ -78,8 +78,11 @@ class ClientServerHazelcastIndexedSessionRepositoryITests extends AbstractHazelc
HazelcastInstance hazelcastInstance() {
ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().addAddress(container.getHost() + ":" + container.getFirstMappedPort());
clientConfig.getUserCodeDeploymentConfig().setEnabled(true).addClass(Session.class)
.addClass(MapSession.class).addClass(SessionUpdateEntryProcessor.class);
clientConfig.getUserCodeDeploymentConfig()
.setEnabled(true)
.addClass(Session.class)
.addClass(MapSession.class)
.addClass(SessionUpdateEntryProcessor.class);
return HazelcastClient.newHazelcastClient(clientConfig);
}

View File

@@ -68,7 +68,7 @@ class FlushImmediateHazelcastIndexedSessionRepositoryITests {
this.repository.save(session);
Map<String, HazelcastIndexedSessionRepository.HazelcastSession> findByPrincipalName = this.repository
.findByPrincipalName(username);
.findByPrincipalName(username);
assertThat(findByPrincipalName).hasSize(1);
assertThat(findByPrincipalName.keySet()).containsOnly(sessionId);

View File

@@ -47,11 +47,12 @@ final class HazelcastITestUtils {
networkConfig.setPort(0);
networkConfig.getJoin().getAutoDetectionConfig().setEnabled(false);
AttributeConfig attributeConfig = new AttributeConfig()
.setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(PrincipalNameExtractor.class.getName());
.setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(PrincipalNameExtractor.class.getName());
config.getMapConfig(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME)
.addAttributeConfig(attributeConfig).addIndexConfig(
new IndexConfig(IndexType.HASH, HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE));
.addAttributeConfig(attributeConfig)
.addIndexConfig(
new IndexConfig(IndexType.HASH, HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE));
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setImplementation(new HazelcastSessionSerializer()).setTypeClass(MapSession.class);
config.getSerializationConfig().addSerializerConfig(serializerConfig);

View File

@@ -91,14 +91,14 @@ class SessionEventHazelcastIndexedSessionRepositoryTests<S extends Session> {
assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionCreatedEvent>getEvent(sessionToSave.getId()))
.isInstanceOf(SessionCreatedEvent.class);
.isInstanceOf(SessionCreatedEvent.class);
Session session = this.repository.findById(sessionToSave.getId());
assertThat(session.getId()).isEqualTo(sessionToSave.getId());
assertThat(session.getAttributeNames()).isEqualTo(sessionToSave.getAttributeNames());
assertThat(session.<String>getAttribute(expectedAttributeName))
.isEqualTo(sessionToSave.getAttribute(expectedAttributeName));
.isEqualTo(sessionToSave.getAttribute(expectedAttributeName));
}
@Test
@@ -109,15 +109,15 @@ class SessionEventHazelcastIndexedSessionRepositoryTests<S extends Session> {
assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionCreatedEvent>getEvent(sessionToSave.getId()))
.isInstanceOf(SessionCreatedEvent.class);
.isInstanceOf(SessionCreatedEvent.class);
this.registry.clear();
assertThat(sessionToSave.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionExpiredEvent>getEvent(sessionToSave.getId()))
.isInstanceOf(SessionExpiredEvent.class);
.isInstanceOf(SessionExpiredEvent.class);
assertThat(this.repository.findById(sessionToSave.getId())).isNull();
}
@@ -130,14 +130,14 @@ class SessionEventHazelcastIndexedSessionRepositoryTests<S extends Session> {
assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionCreatedEvent>getEvent(sessionToSave.getId()))
.isInstanceOf(SessionCreatedEvent.class);
.isInstanceOf(SessionCreatedEvent.class);
this.registry.clear();
this.repository.deleteById(sessionToSave.getId());
assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionDeletedEvent>getEvent(sessionToSave.getId()))
.isInstanceOf(SessionDeletedEvent.class);
.isInstanceOf(SessionDeletedEvent.class);
assertThat(this.repository.findById(sessionToSave.getId())).isNull();
}
@@ -169,7 +169,7 @@ class SessionEventHazelcastIndexedSessionRepositoryTests<S extends Session> {
assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionCreatedEvent>getEvent(sessionToSave.getId()))
.isInstanceOf(SessionCreatedEvent.class);
.isInstanceOf(SessionCreatedEvent.class);
this.registry.clear();
sessionToSave.changeSessionId();
@@ -186,7 +186,7 @@ class SessionEventHazelcastIndexedSessionRepositoryTests<S extends Session> {
assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionCreatedEvent>getEvent(sessionToSave.getId()))
.isInstanceOf(SessionCreatedEvent.class);
.isInstanceOf(SessionCreatedEvent.class);
this.registry.clear();
S sessionToUpdate = this.repository.findById(sessionToSave.getId());
@@ -196,7 +196,7 @@ class SessionEventHazelcastIndexedSessionRepositoryTests<S extends Session> {
assertThat(this.registry.receivedEvent(sessionToUpdate.getId())).isTrue();
assertThat(this.registry.<SessionExpiredEvent>getEvent(sessionToUpdate.getId()))
.isInstanceOf(SessionExpiredEvent.class);
.isInstanceOf(SessionExpiredEvent.class);
assertThat(this.repository.findById(sessionToUpdate.getId())).isNull();
}

View File

@@ -377,7 +377,7 @@ public class HazelcastIndexedSessionRepository
this.originalId = cached.getId();
if (this.isNew || (HazelcastIndexedSessionRepository.this.saveMode == SaveMode.ALWAYS)) {
getAttributeNames()
.forEach((attributeName) -> this.delta.put(attributeName, cached.getAttribute(attributeName)));
.forEach((attributeName) -> this.delta.put(attributeName, cached.getAttribute(attributeName)));
}
}
@@ -448,7 +448,7 @@ public class HazelcastIndexedSessionRepository
this.delta.put(attributeName, attributeValue);
if (SPRING_SECURITY_CONTEXT.equals(attributeName)) {
Map<String, String> indexes = HazelcastIndexedSessionRepository.this.indexResolver
.resolveIndexesFor(this);
.resolveIndexesFor(this);
String principal = (attributeValue != null) ? indexes.get(PRINCIPAL_NAME_INDEX_NAME) : null;
this.delegate.setAttribute(PRINCIPAL_NAME_INDEX_NAME, principal);
this.delta.put(PRINCIPAL_NAME_INDEX_NAME, principal);

View File

@@ -131,7 +131,7 @@ public class HazelcastHttpSessionConfiguration implements ImportAware {
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableHazelcastHttpSession.class.getName());
.getAnnotationAttributes(EnableHazelcastHttpSession.class.getName());
AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;
@@ -159,7 +159,7 @@ public class HazelcastHttpSessionConfiguration implements ImportAware {
sessionRepository.setFlushMode(this.flushMode);
sessionRepository.setSaveMode(this.saveMode);
this.sessionRepositoryCustomizers
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
return sessionRepository;
}

View File

@@ -82,13 +82,13 @@ class HazelcastIndexedSessionRepositoryTests {
@Test
void constructorNullHazelcastInstance() {
assertThatIllegalArgumentException().isThrownBy(() -> new HazelcastIndexedSessionRepository(null))
.withMessage("HazelcastInstance must not be null");
.withMessage("HazelcastInstance must not be null");
}
@Test
void setSaveModeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setSaveMode(null))
.withMessage("saveMode must not be null");
.withMessage("saveMode must not be null");
}
@Test
@@ -364,7 +364,7 @@ class HazelcastIndexedSessionRepositoryTests {
String principal = "username";
Map<String, HazelcastSession> sessions = this.repository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
assertThat(sessions).isEmpty();
verify(this.sessions, times(1)).values(isA(EqualPredicate.class));
@@ -388,7 +388,7 @@ class HazelcastIndexedSessionRepositoryTests {
given(this.sessions.values(isA(EqualPredicate.class))).willReturn(saved);
Map<String, HazelcastSession> sessions = this.repository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
assertThat(sessions).hasSize(2);
verify(this.sessions, times(1)).values(isA(EqualPredicate.class));

View File

@@ -71,8 +71,10 @@ class HazelcastHttpSessionConfigurationTests {
@Test
void noHazelcastInstanceConfiguration() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> registerAndRefresh(NoHazelcastInstanceConfiguration.class)).havingRootCause()
.isInstanceOf(NoSuchBeanDefinitionException.class).withMessageContaining("HazelcastInstance");
.isThrownBy(() -> registerAndRefresh(NoHazelcastInstanceConfiguration.class))
.havingRootCause()
.isInstanceOf(NoSuchBeanDefinitionException.class)
.withMessageContaining("HazelcastInstance");
}
@Test
@@ -108,7 +110,7 @@ class HazelcastHttpSessionConfigurationTests {
HazelcastIndexedSessionRepository repository = this.context.getBean(HazelcastIndexedSessionRepository.class);
assertThat(repository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -117,7 +119,7 @@ class HazelcastHttpSessionConfigurationTests {
HazelcastIndexedSessionRepository repository = this.context.getBean(HazelcastIndexedSessionRepository.class);
assertThat(repository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -142,14 +144,14 @@ class HazelcastHttpSessionConfigurationTests {
void customSaveModeAnnotation() {
registerAndRefresh(BaseConfiguration.class, CustomSaveModeExpressionAnnotationConfiguration.class);
assertThat(this.context.getBean(HazelcastIndexedSessionRepository.class))
.hasFieldOrPropertyWithValue("saveMode", SaveMode.ALWAYS);
.hasFieldOrPropertyWithValue("saveMode", SaveMode.ALWAYS);
}
@Test
void customSaveModeSetter() {
registerAndRefresh(BaseConfiguration.class, CustomSaveModeExpressionSetterConfiguration.class);
assertThat(this.context.getBean(HazelcastIndexedSessionRepository.class))
.hasFieldOrPropertyWithValue("saveMode", SaveMode.ALWAYS);
.hasFieldOrPropertyWithValue("saveMode", SaveMode.ALWAYS);
}
@Test
@@ -162,7 +164,7 @@ class HazelcastHttpSessionConfigurationTests {
assertThat(repository).isNotNull();
assertThat(hazelcastInstance).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "sessions"))
.isEqualTo(QualifiedHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions);
.isEqualTo(QualifiedHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions);
}
@Test
@@ -174,7 +176,7 @@ class HazelcastHttpSessionConfigurationTests {
assertThat(repository).isNotNull();
assertThat(hazelcastInstance).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "sessions"))
.isEqualTo(PrimaryHazelcastInstanceConfiguration.primaryHazelcastInstanceSessions);
.isEqualTo(PrimaryHazelcastInstanceConfiguration.primaryHazelcastInstanceSessions);
}
@Test
@@ -187,7 +189,7 @@ class HazelcastHttpSessionConfigurationTests {
assertThat(repository).isNotNull();
assertThat(hazelcastInstance).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "sessions"))
.isEqualTo(QualifiedAndPrimaryHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions);
.isEqualTo(QualifiedAndPrimaryHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions);
}
@Test
@@ -199,15 +201,16 @@ class HazelcastHttpSessionConfigurationTests {
assertThat(repository).isNotNull();
assertThat(hazelcastInstance).isNotNull();
assertThat(ReflectionTestUtils.getField(repository, "sessions"))
.isEqualTo(NamedHazelcastInstanceConfiguration.hazelcastInstanceSessions);
.isEqualTo(NamedHazelcastInstanceConfiguration.hazelcastInstanceSessions);
}
@Test
void multipleHazelcastInstanceConfiguration() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> registerAndRefresh(MultipleHazelcastInstanceConfiguration.class)).havingRootCause()
.isInstanceOf(NoUniqueBeanDefinitionException.class)
.withMessageContaining("expected single matching bean but found 2");
.isThrownBy(() -> registerAndRefresh(MultipleHazelcastInstanceConfiguration.class))
.havingRootCause()
.isInstanceOf(NoUniqueBeanDefinitionException.class)
.withMessageContaining("expected single matching bean but found 2");
}
@Test
@@ -225,16 +228,16 @@ class HazelcastHttpSessionConfigurationTests {
void sessionRepositoryCustomizer() {
registerAndRefresh(SessionRepositoryCustomizerConfiguration.class);
HazelcastIndexedSessionRepository sessionRepository = this.context
.getBean(HazelcastIndexedSessionRepository.class);
.getBean(HazelcastIndexedSessionRepository.class);
assertThat(sessionRepository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
void importConfigAndCustomize() {
registerAndRefresh(ImportConfigAndCustomizeConfiguration.class);
HazelcastIndexedSessionRepository sessionRepository = this.context
.getBean(HazelcastIndexedSessionRepository.class);
.getBean(HazelcastIndexedSessionRepository.class);
assertThat(sessionRepository).extracting("defaultMaxInactiveInterval").isEqualTo(Duration.ZERO);
}
@@ -449,7 +452,7 @@ class HazelcastHttpSessionConfigurationTests {
@Order(1)
SessionRepositoryCustomizer<HazelcastIndexedSessionRepository> sessionRepositoryCustomizerTwo() {
return (sessionRepository) -> sessionRepository
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
}

View File

@@ -134,7 +134,7 @@ abstract class AbstractJdbcIndexedSessionRepositoryITests {
assertThat(session.getDelta()).isEmpty();
assertThat(session.getAttributeNames()).isEqualTo(toSave.getAttributeNames());
assertThat(session.<String>getAttribute(expectedAttributeName))
.isEqualTo(toSave.getAttribute(expectedAttributeName));
.isEqualTo(toSave.getAttribute(expectedAttributeName));
this.repository.deleteById(toSave.getId());
@@ -190,7 +190,7 @@ abstract class AbstractJdbcIndexedSessionRepositoryITests {
assertThat(session.getDelta()).isEmpty();
assertThat(session.isExpired()).isFalse();
assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS))
.isEqualTo(lastAccessedTime.truncatedTo(ChronoUnit.MILLIS));
.isEqualTo(lastAccessedTime.truncatedTo(ChronoUnit.MILLIS));
}
@Test
@@ -816,7 +816,7 @@ abstract class AbstractJdbcIndexedSessionRepositoryITests {
// with DB specific upsert configured we're fine
assertThatCode(() -> this.repository.save(session)).doesNotThrowAnyException();
assertThat((String) this.repository.findById(session.getId()).getAttribute(attributeName))
.isEqualTo(attributeValue);
.isEqualTo(attributeValue);
}
}

View File

@@ -43,7 +43,8 @@ class DerbyJdbcIndexedSessionRepositoryITests extends AbstractJdbcIndexedSession
@Bean
EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.DERBY)
.addScript("org/springframework/session/jdbc/schema-derby.sql").build();
.addScript("org/springframework/session/jdbc/schema-derby.sql")
.build();
}
}

View File

@@ -43,7 +43,8 @@ class H2JdbcIndexedSessionRepositoryITests extends AbstractJdbcIndexedSessionRep
@Bean
EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.addScript("org/springframework/session/jdbc/schema-h2.sql").build();
.addScript("org/springframework/session/jdbc/schema-h2.sql")
.build();
}
}

View File

@@ -43,7 +43,8 @@ class HsqldbJdbcIndexedSessionRepositoryITests extends AbstractJdbcIndexedSessio
@Bean
EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.addScript("org/springframework/session/jdbc/schema-hsqldb.sql").build();
.addScript("org/springframework/session/jdbc/schema-hsqldb.sql")
.build();
}
}

View File

@@ -499,7 +499,7 @@ public class JdbcIndexedSessionRepository implements
@Override
public void deleteById(final String id) {
this.transactionOperations.executeWithoutResult((status) -> JdbcIndexedSessionRepository.this.jdbcOperations
.update(JdbcIndexedSessionRepository.this.deleteSessionQuery, id));
.update(JdbcIndexedSessionRepository.this.deleteSessionQuery, id));
}
@Override
@@ -509,9 +509,9 @@ public class JdbcIndexedSessionRepository implements
}
List<JdbcSession> sessions = this.transactionOperations
.execute((status) -> JdbcIndexedSessionRepository.this.jdbcOperations.query(
JdbcIndexedSessionRepository.this.listSessionsByPrincipalNameQuery,
(ps) -> ps.setString(1, indexValue), JdbcIndexedSessionRepository.this.extractor));
.execute((status) -> JdbcIndexedSessionRepository.this.jdbcOperations.query(
JdbcIndexedSessionRepository.this.listSessionsByPrincipalNameQuery,
(ps) -> ps.setString(1, indexValue), JdbcIndexedSessionRepository.this.extractor));
Map<String, JdbcSession> sessionMap = new HashMap<>(sessions.size());
@@ -641,8 +641,8 @@ public class JdbcIndexedSessionRepository implements
public void cleanUpExpiredSessions() {
Integer deletedCount = this.transactionOperations
.execute((status) -> JdbcIndexedSessionRepository.this.jdbcOperations.update(
JdbcIndexedSessionRepository.this.deleteSessionsByExpiryTimeQuery, System.currentTimeMillis()));
.execute((status) -> JdbcIndexedSessionRepository.this.jdbcOperations
.update(JdbcIndexedSessionRepository.this.deleteSessionsByExpiryTimeQuery, System.currentTimeMillis()));
if (logger.isDebugEnabled()) {
logger.debug("Cleaned up " + deletedCount + " expired sessions");
@@ -873,17 +873,17 @@ public class JdbcIndexedSessionRepository implements
if (this.isNew) {
JdbcIndexedSessionRepository.this.transactionOperations.executeWithoutResult((status) -> {
Map<String, String> indexes = JdbcIndexedSessionRepository.this.indexResolver
.resolveIndexesFor(JdbcSession.this);
.resolveIndexesFor(JdbcSession.this);
JdbcIndexedSessionRepository.this.jdbcOperations
.update(JdbcIndexedSessionRepository.this.createSessionQuery, (ps) -> {
ps.setString(1, JdbcSession.this.primaryKey);
ps.setString(2, getId());
ps.setLong(3, getCreationTime().toEpochMilli());
ps.setLong(4, getLastAccessedTime().toEpochMilli());
ps.setInt(5, (int) getMaxInactiveInterval().getSeconds());
ps.setLong(6, getExpiryTime().toEpochMilli());
ps.setString(7, indexes.get(PRINCIPAL_NAME_INDEX_NAME));
});
.update(JdbcIndexedSessionRepository.this.createSessionQuery, (ps) -> {
ps.setString(1, JdbcSession.this.primaryKey);
ps.setString(2, getId());
ps.setLong(3, getCreationTime().toEpochMilli());
ps.setLong(4, getLastAccessedTime().toEpochMilli());
ps.setInt(5, (int) getMaxInactiveInterval().getSeconds());
ps.setLong(6, getExpiryTime().toEpochMilli());
ps.setString(7, indexes.get(PRINCIPAL_NAME_INDEX_NAME));
});
Set<String> attributeNames = getAttributeNames();
if (!attributeNames.isEmpty()) {
insertSessionAttributes(JdbcSession.this, new ArrayList<>(attributeNames));
@@ -894,32 +894,38 @@ public class JdbcIndexedSessionRepository implements
JdbcIndexedSessionRepository.this.transactionOperations.executeWithoutResult((status) -> {
if (JdbcSession.this.changed) {
Map<String, String> indexes = JdbcIndexedSessionRepository.this.indexResolver
.resolveIndexesFor(JdbcSession.this);
.resolveIndexesFor(JdbcSession.this);
JdbcIndexedSessionRepository.this.jdbcOperations
.update(JdbcIndexedSessionRepository.this.updateSessionQuery, (ps) -> {
ps.setString(1, getId());
ps.setLong(2, getLastAccessedTime().toEpochMilli());
ps.setInt(3, (int) getMaxInactiveInterval().getSeconds());
ps.setLong(4, getExpiryTime().toEpochMilli());
ps.setString(5, indexes.get(PRINCIPAL_NAME_INDEX_NAME));
ps.setString(6, JdbcSession.this.primaryKey);
});
.update(JdbcIndexedSessionRepository.this.updateSessionQuery, (ps) -> {
ps.setString(1, getId());
ps.setLong(2, getLastAccessedTime().toEpochMilli());
ps.setInt(3, (int) getMaxInactiveInterval().getSeconds());
ps.setLong(4, getExpiryTime().toEpochMilli());
ps.setString(5, indexes.get(PRINCIPAL_NAME_INDEX_NAME));
ps.setString(6, JdbcSession.this.primaryKey);
});
}
List<String> addedAttributeNames = JdbcSession.this.delta.entrySet().stream()
.filter((entry) -> entry.getValue() == DeltaValue.ADDED).map(Map.Entry::getKey)
.collect(Collectors.toList());
List<String> addedAttributeNames = JdbcSession.this.delta.entrySet()
.stream()
.filter((entry) -> entry.getValue() == DeltaValue.ADDED)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
if (!addedAttributeNames.isEmpty()) {
insertSessionAttributes(JdbcSession.this, addedAttributeNames);
}
List<String> updatedAttributeNames = JdbcSession.this.delta.entrySet().stream()
.filter((entry) -> entry.getValue() == DeltaValue.UPDATED).map(Map.Entry::getKey)
.collect(Collectors.toList());
List<String> updatedAttributeNames = JdbcSession.this.delta.entrySet()
.stream()
.filter((entry) -> entry.getValue() == DeltaValue.UPDATED)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
if (!updatedAttributeNames.isEmpty()) {
updateSessionAttributes(JdbcSession.this, updatedAttributeNames);
}
List<String> removedAttributeNames = JdbcSession.this.delta.entrySet().stream()
.filter((entry) -> entry.getValue() == DeltaValue.REMOVED).map(Map.Entry::getKey)
.collect(Collectors.toList());
List<String> removedAttributeNames = JdbcSession.this.delta.entrySet()
.stream()
.filter((entry) -> entry.getValue() == DeltaValue.REMOVED)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
if (!removedAttributeNames.isEmpty()) {
deleteSessionAttributes(JdbcSession.this, removedAttributeNames);
}

View File

@@ -30,28 +30,30 @@ class SessionJdbcRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerType(TypeReference.of("javax.sql.DataSource"),
(hint) -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
hints.resources().registerPattern("org/springframework/session/jdbc/schema-db2.sql")
.registerPattern("org/springframework/session/jdbc/schema-derby.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-db2.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-derby.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-h2.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-hsqldb.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-mysql.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-oracle.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-postgresql.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-sqlite.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-sqlserver.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-sybase.sql")
.registerPattern("org/springframework/session/jdbc/schema-h2.sql")
.registerPattern("org/springframework/session/jdbc/schema-hsqldb.sql")
.registerPattern("org/springframework/session/jdbc/schema-mysql.sql")
.registerPattern("org/springframework/session/jdbc/schema-oracle.sql")
.registerPattern("org/springframework/session/jdbc/schema-postgresql.sql")
.registerPattern("org/springframework/session/jdbc/schema-sqlite.sql")
.registerPattern("org/springframework/session/jdbc/schema-sqlserver.sql")
.registerPattern("org/springframework/session/jdbc/schema-sybase.sql");
hints.reflection()
.registerType(TypeReference.of("javax.sql.DataSource"),
(hint) -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
hints.resources()
.registerPattern("org/springframework/session/jdbc/schema-db2.sql")
.registerPattern("org/springframework/session/jdbc/schema-derby.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-db2.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-derby.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-h2.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-hsqldb.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-mysql.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-oracle.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-postgresql.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-sqlite.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-sqlserver.sql")
.registerPattern("org/springframework/session/jdbc/schema-drop-sybase.sql")
.registerPattern("org/springframework/session/jdbc/schema-h2.sql")
.registerPattern("org/springframework/session/jdbc/schema-hsqldb.sql")
.registerPattern("org/springframework/session/jdbc/schema-mysql.sql")
.registerPattern("org/springframework/session/jdbc/schema-oracle.sql")
.registerPattern("org/springframework/session/jdbc/schema-postgresql.sql")
.registerPattern("org/springframework/session/jdbc/schema-sqlite.sql")
.registerPattern("org/springframework/session/jdbc/schema-sqlserver.sql")
.registerPattern("org/springframework/session/jdbc/schema-sybase.sql");
}
}

View File

@@ -145,7 +145,7 @@ public class JdbcHttpSessionConfiguration implements BeanClassLoaderAware, Embed
sessionRepository.setConversionService(createConversionServiceWithBeanClassLoader(this.classLoader));
}
this.sessionRepositoryCustomizers
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
return sessionRepository;
}
@@ -248,7 +248,7 @@ public class JdbcHttpSessionConfiguration implements BeanClassLoaderAware, Embed
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableJdbcHttpSession.class.getName());
.getAnnotationAttributes(EnableJdbcHttpSession.class.getName());
AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;

View File

@@ -89,171 +89,171 @@ class JdbcIndexedSessionRepositoryTests {
@Test
void constructorNullJdbcOperations() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcIndexedSessionRepository(null, TransactionOperations.withoutTransaction()))
.withMessage("jdbcOperations must not be null");
.isThrownBy(() -> new JdbcIndexedSessionRepository(null, TransactionOperations.withoutTransaction()))
.withMessage("jdbcOperations must not be null");
}
@Test
void constructorNullTransactionOperations() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcIndexedSessionRepository(this.jdbcOperations, null))
.withMessage("transactionOperations must not be null");
.isThrownBy(() -> new JdbcIndexedSessionRepository(this.jdbcOperations, null))
.withMessage("transactionOperations must not be null");
}
@Test
void setTableNameNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setTableName(null))
.withMessage("Table name must not be empty");
.withMessage("Table name must not be empty");
}
@Test
void setTableNameEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setTableName(" "))
.withMessage("Table name must not be empty");
.withMessage("Table name must not be empty");
}
@Test
void setCreateSessionQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCreateSessionQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setCreateSessionQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCreateSessionQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setCreateSessionAttributeQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCreateSessionAttributeQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setCreateSessionAttributeQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCreateSessionAttributeQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setGetSessionQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setGetSessionQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setGetSessionQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setGetSessionQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setUpdateSessionQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setUpdateSessionQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setUpdateSessionQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setUpdateSessionQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setUpdateSessionAttributeQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setUpdateSessionAttributeQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setUpdateSessionAttributeQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setUpdateSessionAttributeQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setDeleteSessionAttributeQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionAttributeQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setDeleteSessionAttributeQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionAttributeQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setDeleteSessionQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setDeleteSessionQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setListSessionsByPrincipalNameQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setListSessionsByPrincipalNameQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setListSessionsByPrincipalNameQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setListSessionsByPrincipalNameQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setDeleteSessionsByLastAccessTimeQueryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionsByExpiryTimeQuery(null))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setDeleteSessionsByLastAccessTimeQueryEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionsByExpiryTimeQuery(" "))
.withMessage("Query must not be empty");
.withMessage("Query must not be empty");
}
@Test
void setLobHandlerNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setLobHandler(null))
.withMessage("LobHandler must not be null");
.withMessage("LobHandler must not be null");
}
@Test
void setConversionServiceNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setConversionService(null))
.withMessage("conversionService must not be null");
.withMessage("conversionService must not be null");
}
@Test
void setFlushModeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setFlushMode(null))
.withMessage("flushMode must not be null");
.withMessage("flushMode must not be null");
}
@Test
void setSaveModeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setSaveMode(null))
.withMessage("saveMode must not be null");
.withMessage("saveMode must not be null");
}
@Test
void setCleanupCronNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCleanupCron(null))
.withMessage("cleanupCron must not be null");
.withMessage("cleanupCron must not be null");
}
@Test
void setCleanupCronInvalid() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCleanupCron("test"))
.withMessage("cleanupCron must be valid");
.withMessage("cleanupCron must be valid");
}
@Test
@@ -523,7 +523,8 @@ class JdbcIndexedSessionRepositoryTests {
void getSessionNotFound() {
String sessionId = "testSessionId";
given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
isA(ResultSetExtractor.class))).willReturn(Collections.emptyList());
isA(ResultSetExtractor.class)))
.willReturn(Collections.emptyList());
JdbcSession session = this.repository.findById(sessionId);
@@ -538,7 +539,8 @@ class JdbcIndexedSessionRepositoryTests {
Session expired = this.repository.createSession();
expired.setLastAccessedTime(Instant.now().minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));
given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
isA(ResultSetExtractor.class))).willReturn(Collections.singletonList(expired));
isA(ResultSetExtractor.class)))
.willReturn(Collections.singletonList(expired));
JdbcSession session = this.repository.findById(expired.getId());
@@ -554,7 +556,8 @@ class JdbcIndexedSessionRepositoryTests {
Session saved = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);
saved.setAttribute("savedName", "savedValue");
given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
isA(ResultSetExtractor.class))).willReturn(Collections.singletonList(saved));
isA(ResultSetExtractor.class)))
.willReturn(Collections.singletonList(saved));
JdbcSession session = this.repository.findById(saved.getId());
@@ -589,10 +592,11 @@ class JdbcIndexedSessionRepositoryTests {
void findByIndexNameAndIndexValuePrincipalIndexNameNotFound() {
String principal = "username";
given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
isA(ResultSetExtractor.class))).willReturn(Collections.emptyList());
isA(ResultSetExtractor.class)))
.willReturn(Collections.emptyList());
Map<String, JdbcSession> sessions = this.repository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
assertThat(sessions).isEmpty();
verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class),
@@ -613,10 +617,11 @@ class JdbcIndexedSessionRepositoryTests {
saved2.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
saved.add(saved2);
given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
isA(ResultSetExtractor.class))).willReturn(saved);
isA(ResultSetExtractor.class)))
.willReturn(saved);
Map<String, JdbcSession> sessions = this.repository
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
assertThat(sessions).hasSize(2);
verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class),
@@ -671,7 +676,7 @@ class JdbcIndexedSessionRepositoryTests {
session.setAttribute("attribute3", "value4");
this.repository.save(session);
ArgumentCaptor<BatchPreparedStatementSetter> captor = ArgumentCaptor
.forClass(BatchPreparedStatementSetter.class);
.forClass(BatchPreparedStatementSetter.class);
verify(this.jdbcOperations).batchUpdate(matches("^UPDATE SPRING_SESSION_ATTRIBUTES\\s*SET.*"),
captor.capture());
assertThat(captor.getValue().getBatchSize()).isEqualTo(2);
@@ -704,7 +709,7 @@ class JdbcIndexedSessionRepositoryTests {
session.setAttribute("attribute3", "value4");
this.repository.save(session);
ArgumentCaptor<BatchPreparedStatementSetter> captor = ArgumentCaptor
.forClass(BatchPreparedStatementSetter.class);
.forClass(BatchPreparedStatementSetter.class);
verify(this.jdbcOperations).batchUpdate(matches("^UPDATE SPRING_SESSION_ATTRIBUTES\\s*SET.*"),
captor.capture());
assertThat(captor.getValue().getBatchSize()).isEqualTo(3);

View File

@@ -48,8 +48,9 @@ class SessionJdbcRuntimeHintsTests {
@Test
void aotFactoriesContainsRegistrar() {
boolean match = SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
.load(RuntimeHintsRegistrar.class).stream()
.anyMatch((registrar) -> registrar instanceof SessionJdbcRuntimeHints);
.load(RuntimeHintsRegistrar.class)
.stream()
.anyMatch((registrar) -> registrar instanceof SessionJdbcRuntimeHints);
assertThat(match).isTrue();
}
@@ -58,21 +59,21 @@ class SessionJdbcRuntimeHintsTests {
void jdbcSchemasHasHints(String schemaFileName) {
this.sessionJdbcRuntimeHints.registerHints(this.hints, getClass().getClassLoader());
assertThat(RuntimeHintsPredicates.resource().forResource("org/springframework/session/jdbc/" + schemaFileName))
.accepts(this.hints);
.accepts(this.hints);
}
private static Stream<String> getSchemaFileNames() throws IOException {
return Arrays
.stream(new PathMatchingResourcePatternResolver()
.getResources("classpath*:org/springframework/session/jdbc/schema-*.sql"))
.map(Resource::getFilename);
.stream(new PathMatchingResourcePatternResolver()
.getResources("classpath*:org/springframework/session/jdbc/schema-*.sql"))
.map(Resource::getFilename);
}
@Test
void dataSourceHasHints() {
this.sessionJdbcRuntimeHints.registerHints(this.hints, getClass().getClassLoader());
assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of("javax.sql.DataSource")))
.accepts(this.hints);
.accepts(this.hints);
}
}

View File

@@ -81,9 +81,10 @@ class JdbcHttpSessionConfigurationTests {
@Test
void noDataSourceConfiguration() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> registerAndRefresh(NoDataSourceConfiguration.class))
.withRootCauseInstanceOf(NoSuchBeanDefinitionException.class).havingRootCause()
.withMessageContaining("expected at least 1 bean which qualifies as autowire candidate");
.isThrownBy(() -> registerAndRefresh(NoDataSourceConfiguration.class))
.withRootCauseInstanceOf(NoSuchBeanDefinitionException.class)
.havingRootCause()
.withMessageContaining("expected at least 1 bean which qualifies as autowire candidate");
}
@Test
@@ -93,7 +94,7 @@ class JdbcHttpSessionConfigurationTests {
JdbcIndexedSessionRepository sessionRepository = this.context.getBean(JdbcIndexedSessionRepository.class);
assertThat(sessionRepository).isNotNull();
assertThat(sessionRepository).extracting("transactionOperations")
.hasFieldOrPropertyWithValue("propagationBehavior", TransactionDefinition.PROPAGATION_REQUIRES_NEW);
.hasFieldOrPropertyWithValue("propagationBehavior", TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
@Test
@@ -121,7 +122,7 @@ class JdbcHttpSessionConfigurationTests {
JdbcIndexedSessionRepository repository = this.context.getBean(JdbcIndexedSessionRepository.class);
assertThat(repository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -130,7 +131,7 @@ class JdbcHttpSessionConfigurationTests {
JdbcIndexedSessionRepository repository = this.context.getBean(JdbcIndexedSessionRepository.class);
assertThat(repository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -232,10 +233,10 @@ class JdbcHttpSessionConfigurationTests {
@Test
void multipleDataSourceConfiguration() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(
() -> registerAndRefresh(DataSourceConfiguration.class, MultipleDataSourceConfiguration.class))
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).havingRootCause()
.withMessageContaining("expected single matching bean but found 2");
.isThrownBy(() -> registerAndRefresh(DataSourceConfiguration.class, MultipleDataSourceConfiguration.class))
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class)
.havingRootCause()
.withMessageContaining("expected single matching bean but found 2");
}
@Test
@@ -287,7 +288,7 @@ class JdbcHttpSessionConfigurationTests {
@Test
void resolveTableNameByPropertyPlaceholder() {
this.context
.setEnvironment(new MockEnvironment().withProperty("session.jdbc.tableName", "custom_session_table"));
.setEnvironment(new MockEnvironment().withProperty("session.jdbc.tableName", "custom_session_table"));
registerAndRefresh(DataSourceConfiguration.class, CustomJdbcHttpSessionConfiguration.class);
JdbcHttpSessionConfiguration configuration = this.context.getBean(JdbcHttpSessionConfiguration.class);
assertThat(ReflectionTestUtils.getField(configuration, "tableName")).isEqualTo("custom_session_table");
@@ -298,7 +299,7 @@ class JdbcHttpSessionConfigurationTests {
registerAndRefresh(DataSourceConfiguration.class, SessionRepositoryCustomizerConfiguration.class);
JdbcIndexedSessionRepository sessionRepository = this.context.getBean(JdbcIndexedSessionRepository.class);
assertThat(sessionRepository).extracting("defaultMaxInactiveInterval")
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
@Test
@@ -559,7 +560,7 @@ class JdbcHttpSessionConfigurationTests {
@Order(1)
SessionRepositoryCustomizer<JdbcIndexedSessionRepository> sessionRepositoryCustomizerTwo() {
return (sessionRepository) -> sessionRepository
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
.setDefaultMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));
}
}

View File

@@ -65,7 +65,7 @@ class JdbcSchemaUtilsTests {
private static Stream<Resource> getSchemaFiles() throws IOException {
return Arrays.stream(new PathMatchingResourcePatternResolver()
.getResources("classpath*:org/springframework/session/jdbc/schema-*.sql"));
.getResources("classpath*:org/springframework/session/jdbc/schema-*.sql"));
}
}

View File

@@ -41,11 +41,12 @@ public class SessionConfig {
networkConfig.setPort(0);
networkConfig.getJoin().getAutoDetectionConfig().setEnabled(false);
AttributeConfig attributeConfig = new AttributeConfig()
.setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(PrincipalNameExtractor.class.getName());
.setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(PrincipalNameExtractor.class.getName());
config.getMapConfig(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME)
.addAttributeConfig(attributeConfig).addIndexConfig(
new IndexConfig(IndexType.HASH, HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE));
.addAttributeConfig(attributeConfig)
.addIndexConfig(
new IndexConfig(IndexType.HASH, HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE));
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setImplementation(new HazelcastSessionSerializer()).setTypeClass(MapSession.class);
config.getSerializationConfig().addSerializerConfig(serializerConfig);

View File

@@ -70,8 +70,8 @@ public class HomePage {
public List<Attribute> attributes() {
List<Attribute> rows = this.trs.stream() //
.map(Attribute::new) //
.collect(Collectors.toList());
.map(Attribute::new) //
.collect(Collectors.toList());
this.attributes.addAll(rows);

View File

@@ -49,7 +49,7 @@ class RedisSerializerTest {
assertThat(this.sessionRedisTemplate).isNotNull();
assertThat(this.sessionRedisTemplate.getDefaultSerializer()).isNotNull();
assertThat(this.sessionRedisTemplate.getDefaultSerializer())
.isInstanceOf(GenericJackson2JsonRedisSerializer.class);
.isInstanceOf(GenericJackson2JsonRedisSerializer.class);
}
@TestConfiguration

View File

@@ -71,7 +71,7 @@ class ApplicationTests {
"ws://localhost:" + this.port + "/sockjs");
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> wsSession.get().sendMessage(new TextMessage("a")));
.isThrownBy(() -> wsSession.get().sendMessage(new TextMessage("a")));
}
@TestConfiguration

View File

@@ -32,7 +32,7 @@ public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(User.withUsername("user").password("{noop}password").roles("USER").build());
.withUser(User.withUsername("user").password("{noop}password").roles("USER").build());
}
}

View File

@@ -42,11 +42,12 @@ public class SessionConfig {
networkConfig.setPort(0);
networkConfig.getJoin().getAutoDetectionConfig().setEnabled(false);
AttributeConfig attributeConfig = new AttributeConfig()
.setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(PrincipalNameExtractor.class.getName());
.setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(PrincipalNameExtractor.class.getName());
config.getMapConfig(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME)
.addAttributeConfig(attributeConfig).addIndexConfig(
new IndexConfig(IndexType.HASH, HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE));
.addAttributeConfig(attributeConfig)
.addIndexConfig(
new IndexConfig(IndexType.HASH, HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE));
return Hazelcast.newHazelcastInstance(config);
}

View File

@@ -35,7 +35,9 @@ public class Config {
@Bean
public EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder() // <2>
.setType(EmbeddedDatabaseType.H2).addScript("org/springframework/session/jdbc/schema-h2.sql").build();
.setType(EmbeddedDatabaseType.H2)
.addScript("org/springframework/session/jdbc/schema-h2.sql")
.build();
}
@Bean

View File

@@ -65,14 +65,18 @@ class RestMockMvcTests {
@BeforeEach
void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).alwaysDo(print())
.addFilters(this.sessionRepositoryFilter).apply(springSecurity()).build();
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
.alwaysDo(print())
.addFilters(this.sessionRepositoryFilter)
.apply(springSecurity())
.build();
}
@Test
void noSessionOnNoCredentials() throws Exception {
this.mvc.perform(get("/")).andExpect(header().doesNotExist("X-Auth-Token"))
.andExpect(status().isUnauthorized());
this.mvc.perform(get("/"))
.andExpect(header().doesNotExist("X-Auth-Token"))
.andExpect(status().isUnauthorized());
}
@WithMockUser

View File

@@ -60,8 +60,8 @@ class RestTests {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
assertThatExceptionOfType(HttpClientErrorException.class)
.isThrownBy(() -> getForUser(this.baseUrl + "/", headers, String.class))
.satisfies((e) -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
.isThrownBy(() -> getForUser(this.baseUrl + "/", headers, String.class))
.satisfies((e) -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
}
@Test

Some files were not shown because too many files have changed in this diff Show More