diff --git a/build.gradle b/build.gradle index 500976e..577f696 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ buildscript { dependencies { - classpath 'io.spring.gradle:spring-build-conventions:0.0.2.RELEASE' + classpath 'io.spring.gradle:spring-build-conventions:0.0.3.RELEASE' classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion" } repositories { diff --git a/docs/src/integration-test/java/docs/gemfire/indexing/HttpSessionGemFireCustomIndexingIntegrationTests.java b/docs/src/integration-test/java/docs/gemfire/indexing/HttpSessionGemFireCustomIndexingIntegrationTests.java index 15266e5..dfb72c6 100644 --- a/docs/src/integration-test/java/docs/gemfire/indexing/HttpSessionGemFireCustomIndexingIntegrationTests.java +++ b/docs/src/integration-test/java/docs/gemfire/indexing/HttpSessionGemFireCustomIndexingIntegrationTests.java @@ -25,7 +25,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.gemfire.config.annotation.PeerCacheApplication; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; import org.springframework.test.context.ContextConfiguration; @@ -35,9 +35,9 @@ import org.springframework.test.context.junit4.SpringRunner; * @author Rob Winch * @author John Blum */ -@SuppressWarnings("unused") @RunWith(SpringRunner.class) -@ContextConfiguration(classes = HttpSessionGemFireCustomIndexingIntegrationTests.TestConfiguration.class) +@ContextConfiguration +@SuppressWarnings("unused") public class HttpSessionGemFireCustomIndexingIntegrationTests { @Autowired @@ -46,7 +46,8 @@ public class HttpSessionGemFireCustomIndexingIntegrationTests { @Test public void findByIndexName() { - ExpiringSession session = this.sessionRepository.createSession(); + Session session = this.sessionRepository.createSession(); + String indexValue = "HttpSessionGemFireCustomIndexingIntegrationTests-findByIndexName"; // tag::findbyindexname-set[] @@ -58,13 +59,13 @@ public class HttpSessionGemFireCustomIndexingIntegrationTests { this.sessionRepository.save(session); // tag::findbyindexname-get[] - Map idToSessions = + Map idToSessions = this.sessionRepository.findByIndexNameAndIndexValue(indexName, indexValue); // end::findbyindexname-get[] assertThat(idToSessions.keySet()).containsOnly(session.getId()); - this.sessionRepository.delete(session.getId()); + this.sessionRepository.deleteById(session.getId()); } @PeerCacheApplication(name = "HttpSessionGemFireCustomIndexingIntegrationTests", logLevel = "error") diff --git a/docs/src/integration-test/java/docs/gemfire/indexing/HttpSessionGemFireIndexingIntegrationTests.java b/docs/src/integration-test/java/docs/gemfire/indexing/HttpSessionGemFireIndexingIntegrationTests.java index b4fbe25..a5006cb 100644 --- a/docs/src/integration-test/java/docs/gemfire/indexing/HttpSessionGemFireIndexingIntegrationTests.java +++ b/docs/src/integration-test/java/docs/gemfire/indexing/HttpSessionGemFireIndexingIntegrationTests.java @@ -30,8 +30,8 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; -import org.springframework.session.ExpiringSession; import org.springframework.session.FindByIndexNameSessionRepository; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; import org.springframework.test.context.ContextConfiguration; @@ -41,9 +41,9 @@ import org.springframework.test.context.junit4.SpringRunner; * @author Rob Winch * @author John Blum */ -@SuppressWarnings("unused") @RunWith(SpringRunner.class) -@ContextConfiguration(classes = HttpSessionGemFireIndexingIntegrationTests.TestConfiguration.class) +@ContextConfiguration +@SuppressWarnings("unused") public class HttpSessionGemFireIndexingIntegrationTests { @Autowired @@ -52,7 +52,8 @@ public class HttpSessionGemFireIndexingIntegrationTests { @Test public void findByIndexName() { - ExpiringSession session = this.sessionRepository.createSession(); + Session session = this.sessionRepository.createSession(); + String username = "HttpSessionGemFireIndexingIntegrationTests-findByIndexName-username"; // tag::findbyindexname-set[] @@ -64,20 +65,20 @@ public class HttpSessionGemFireIndexingIntegrationTests { this.sessionRepository.save(session); // tag::findbyindexname-get[] - Map idToSessions = + Map idToSessions = this.sessionRepository.findByIndexNameAndIndexValue(indexName, username); // end::findbyindexname-get[] assertThat(idToSessions.keySet()).containsOnly(session.getId()); - this.sessionRepository.delete(session.getId()); + this.sessionRepository.deleteById(session.getId()); } @Test @WithMockUser("HttpSessionGemFireIndexingIntegrationTests-findBySpringSecurityIndexName") public void findBySpringSecurityIndexName() { - ExpiringSession session = this.sessionRepository.createSession(); + Session session = this.sessionRepository.createSession(); // tag::findbyspringsecurityindexname-context[] SecurityContext securityContext = SecurityContextHolder.getContext(); @@ -91,13 +92,13 @@ public class HttpSessionGemFireIndexingIntegrationTests { // tag::findbyspringsecurityindexname-get[] String indexName = FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME; - Map idToSessions = + Map idToSessions = this.sessionRepository.findByIndexNameAndIndexValue(indexName, authentication.getName()); // end::findbyspringsecurityindexname-get[] assertThat(idToSessions.keySet()).containsOnly(session.getId()); - this.sessionRepository.delete(session.getId()); + this.sessionRepository.deleteById(session.getId()); } @PeerCacheApplication(name = "HttpSessionGemFireIndexingIntegrationTests", logLevel = "error") diff --git a/gradle.properties b/gradle.properties index b1b784d..400b9a8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,14 +3,14 @@ assertjVersion=3.8.0 junitVersion=4.12 mockitoVersion=2.8.9 multithreadedtcVersion=1.01 -pivotalGemFireVersion=9.0.4 +pivotalGemFireVersion=9.1.0 springVersion=5.0.0.RC2 springBootVersion=2.0.0.M2 -springDataGemFireVersion=2.0.0.M4 -springDataGeodeVersion=2.0.0.BUILD-SNAPSHOT -springDataReleaseTrainVersion=Kay-M4 +springDataGemFireVersion=2.0.0.RC2 +springDataGeodeVersion=2.0.0.RC2 +springDataReleaseTrainVersion=Kay-RC1 springIoVersion=Cairo-BUILD-SNAPSHOT -springSecurityVersion=5.0.0.M2 -springSessionVersion=2.0.0.M2 +springSecurityVersion=5.0.0.M3 +springSessionVersion=2.0.0.M3 springShellVersion=1.2.0.RELEASE version=2.0.0.BUILD-SNAPSHOT diff --git a/spring-session-data-geode/spring-session-data-geode.gradle b/spring-session-data-geode/spring-session-data-geode.gradle index 2cca6bb..b05d7c7 100644 --- a/spring-session-data-geode/spring-session-data-geode.gradle +++ b/spring-session-data-geode/spring-session-data-geode.gradle @@ -9,7 +9,7 @@ dependencies { compile "org.springframework:spring-context-support" compile "org.springframework:spring-jcl" compile "org.springframework.data:spring-data-geode:$springDataGeodeVersion" - compile "org.springframework.session:spring-session:$springSessionVersion" + compile "org.springframework.session:spring-session-core:$springSessionVersion" optional "org.springframework.security:spring-security-core" optional "org.springframework.security:spring-security-web" diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/AbstractGemFireIntegrationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/AbstractGemFireIntegrationTests.java index 2e1c3bd..6b87066 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/AbstractGemFireIntegrationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/AbstractGemFireIntegrationTests.java @@ -21,11 +21,13 @@ import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.net.Socket; +import java.time.Instant; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; -import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; import org.junit.Before; @@ -43,24 +45,26 @@ import org.apache.geode.cache.server.CacheServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.session.events.AbstractSessionEvent; /** * {@link AbstractGemFireIntegrationTests} is an abstract base class encapsulating common functionality - * for writing Spring Session GemFire integration tests. + * for writing Spring Session Data GemFire & Geode integration tests. * * @author John Blum * @since 1.1.0 * @see org.apache.geode.cache.Cache + * @see org.apache.geode.cache.ExpirationAttributes * @see org.apache.geode.cache.GemFireCache * @see org.apache.geode.cache.Region * @see org.apache.geode.cache.client.ClientCache * @see org.apache.geode.cache.query.Index * @see org.apache.geode.cache.server.CacheServer - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session */ +@SuppressWarnings("unused") public abstract class AbstractGemFireIntegrationTests { protected static final boolean DEFAULT_ENABLE_QUERY_DEBUGGING = false; @@ -95,6 +99,7 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ protected static File createDirectory(String pathname) { + File directory = new File(WORKING_DIRECTORY, pathname); assertThat(directory.isDirectory() || directory.mkdirs()) @@ -107,9 +112,11 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ protected static List createJavaProcessCommandLine(Class type, String... args) { - List commandLine = new ArrayList(); + + List commandLine = new ArrayList<>(); String javaHome = System.getProperty("java.home"); + String javaExe = new File(new File(javaHome, "bin"), "java").getAbsolutePath(); commandLine.add(javaExe); @@ -130,29 +137,13 @@ public abstract class AbstractGemFireIntegrationTests { } /* (non-Javadoc) */ - protected static List extractJvmArguments(final String... args) { - List jvmArgs = new ArrayList(args.length); - - for (String arg : args) { - if (arg.startsWith("-")) { - jvmArgs.add(arg); - } - } - - return jvmArgs; + protected static List extractJvmArguments(String... args) { + return Arrays.stream(args).filter(arg -> arg.startsWith("-")).collect(Collectors.toList()); } /* (non-Javadoc) */ - protected static List extractProgramArguments(final String... args) { - List jvmArgs = new ArrayList(args.length); - - for (String arg : args) { - if (!arg.startsWith("-")) { - jvmArgs.add(arg); - } - } - - return jvmArgs; + protected static List extractProgramArguments(String... args) { + return Arrays.stream(args).filter(arg -> !arg.startsWith("-")).collect(Collectors.toList()); } /* (non-Javadoc) */ @@ -177,10 +168,13 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ protected static boolean waitForCacheServerToStart(final String host, final int port, long duration) { + return waitOnCondition(new Condition() { + AtomicBoolean connected = new AtomicBoolean(false); public boolean evaluate() { + Socket socket = null; try { @@ -211,15 +205,10 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ protected static boolean waitForClientCacheToClose(long duration) { try { - final ClientCache clientCache = ClientCacheFactory.getAnyInstance(); + ClientCache clientCache = ClientCacheFactory.getAnyInstance(); clientCache.close(); - - waitOnCondition(new Condition() { - public boolean evaluate() { - return clientCache.isClosed(); - } - }, duration); + waitOnCondition(clientCache::isClosed, duration); return clientCache.isClosed(); } @@ -237,7 +226,8 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ @SuppressWarnings("all") protected static boolean waitForProcessToStart(Process process, File directory, long duration) { - final File processControl = new File(directory, DEFAULT_PROCESS_CONTROL_FILENAME); + + File processControl = new File(directory, DEFAULT_PROCESS_CONTROL_FILENAME); waitOnCondition(new Condition() { public boolean evaluate() { @@ -255,6 +245,7 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ protected static int waitForProcessToStop(Process process, File directory, long duration) { + long timeout = (System.currentTimeMillis() + duration); try { @@ -279,6 +270,7 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ @SuppressWarnings("all") protected static boolean waitOnCondition(Condition condition, long duration) { + long timeout = (System.currentTimeMillis() + duration); try { @@ -296,7 +288,9 @@ public abstract class AbstractGemFireIntegrationTests { } /* (non-Javadoc) */ + @SuppressWarnings("all") protected static File writeProcessControlFile(File path) throws IOException { + assertThat(path != null && path.isDirectory()).isTrue(); File processControl = new File(path, DEFAULT_PROCESS_CONTROL_FILENAME); @@ -309,7 +303,7 @@ public abstract class AbstractGemFireIntegrationTests { } /* (non-Javadoc) */ - protected void assertValidSession(ExpiringSession session) { + protected void assertValidSession(Session session) { assertThat(session).isNotNull(); assertThat(session.getId()).isNotEmpty(); assertThat(session.isExpired()).isFalse(); @@ -357,60 +351,59 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ protected List listRegions(GemFireCache gemfireCache) { - Set> regions = gemfireCache.rootRegions(); - - List regionList = new ArrayList(regions.size()); - - for (Region region : regions) { - regionList.add(region.getFullPath()); - } - - return regionList; + return gemfireCache.rootRegions().stream().map(Region::getFullPath).collect(Collectors.toList()); } /* (non-Javadoc) */ @SuppressWarnings("unchecked") - protected T createSession() { - T expiringSession = (T) this.gemfireSessionRepository.createSession(); - assertThat(expiringSession).isNotNull(); - return expiringSession; + protected T createSession() { + + T session = (T) this.gemfireSessionRepository.createSession(); + + assertThat(session).isNotNull(); + + return session; } /* (non-Javadoc) */ @SuppressWarnings("unchecked") - protected T createSession(String principalName) { + protected T createSession(String principalName) { + GemFireOperationsSessionRepository.GemFireSession session = createSession(); + session.setPrincipalName(principalName); + return (T) session; } /* (non-Javadoc) */ - protected T delete(T session) { + @SuppressWarnings("all") + protected T delete(T session) { this.gemfireSessionRepository.delete(session); return session; } /* (non-Javadoc) */ - protected T expire(T session) { - session.setLastAccessedTime(0L); + protected T expire(T session) { + session.setLastAccessedTime(Instant.ofEpochMilli(0L)); return session; } /* (non-Javadoc) */ @SuppressWarnings("unchecked") - protected T get(String sessionId) { - return (T) this.gemfireSessionRepository.getSession(sessionId); + protected T get(String sessionId) { + return (T) this.gemfireSessionRepository.findById(sessionId); } /* (non-Javadoc) */ - protected T save(T session) { + protected T save(T session) { this.gemfireSessionRepository.save(session); return session; } /* (non-Javadoc) */ - protected T touch(T session) { - session.setLastAccessedTime(System.currentTimeMillis()); + protected T touch(T session) { + session.setLastAccessedTime(Instant.now()); return session; } @@ -428,8 +421,11 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ @SuppressWarnings("unchecked") public T getSessionEvent() { + T sessionEvent = (T) this.sessionEvent; + this.sessionEvent = null; + return sessionEvent; } @@ -440,11 +436,8 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ public T waitForSessionEvent(long duration) { - waitOnCondition(new Condition() { - public boolean evaluate() { - return (SessionEventListener.this.sessionEvent != null); - } - }, duration); + + waitOnCondition(() -> (SessionEventListener.this.sessionEvent != null), duration); return getSessionEvent(); } diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerGemFireOperationsSessionRepositoryIntegrationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerGemFireOperationsSessionRepositoryIntegrationTests.java index e63ad75..d6294f8 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerGemFireOperationsSessionRepositoryIntegrationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerGemFireOperationsSessionRepositoryIntegrationTests.java @@ -23,6 +23,8 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.Instant; import java.util.Collections; import java.util.Date; import java.util.Properties; @@ -54,7 +56,7 @@ import org.springframework.data.gemfire.client.ClientCacheFactoryBean; import org.springframework.data.gemfire.client.PoolFactoryBean; import org.springframework.data.gemfire.server.CacheServerFactoryBean; import org.springframework.data.gemfire.support.ConnectionEndpoint; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.session.events.AbstractSessionEvent; @@ -77,7 +79,7 @@ import org.springframework.util.SocketUtils; * @see org.junit.Test * @see org.junit.runner.RunWith * @see org.springframework.context.ConfigurableApplicationContext - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests * @see org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession * @see org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration @@ -142,7 +144,9 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests public static void stopGemFireServer() { if (gemfireServer != null) { + gemfireServer.destroy(); + System.err.printf("GemFire Server [exit code = %1$d]%n", waitForProcessToStop(gemfireServer, processWorkingDirectory)); } @@ -159,12 +163,12 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests assertThat(GemFireUtils.isClient(gemfireCache)).isTrue(); - Region springSessionGemFireRegion = + Region springSessionGemFireRegion = gemfireCache.getRegion(SPRING_SESSION_GEMFIRE_REGION_NAME); assertThat(springSessionGemFireRegion).isNotNull(); - RegionAttributes springSessionGemFireRegionAttributes = + RegionAttributes springSessionGemFireRegionAttributes = springSessionGemFireRegion.getAttributes(); assertThat(springSessionGemFireRegionAttributes).isNotNull(); @@ -179,20 +183,20 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests @Test public void createSessionFiresSessionCreatedEvent() { - long beforeOrAtCreationTime = System.currentTimeMillis(); + Instant beforeOrAtCreationTime = Instant.now(); - ExpiringSession expectedSession = save(createSession()); + Session expectedSession = save(createSession()); AbstractSessionEvent sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); - ExpiringSession createdSession = sessionEvent.getSession(); + Session createdSession = sessionEvent.getSession(); assertThat(createdSession.getId()).isEqualTo(expectedSession.getId()); - assertThat(createdSession.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); + assertThat(createdSession.getCreationTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); assertThat(createdSession.getLastAccessedTime()).isEqualTo(createdSession.getCreationTime()); - assertThat(createdSession.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); + assertThat(createdSession.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS)); createdSession.setAttribute("attrOne", 1); @@ -202,21 +206,21 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests assertThat(sessionEvent).isNull(); - this.gemfireSessionRepository.delete(expectedSession.getId()); + this.gemfireSessionRepository.deleteById(expectedSession.getId()); } @Test public void getExistingNonExpiredSessionBeforeAndAfterExpiration() { - ExpiringSession expectedSession = save(touch(createSession())); + Session expectedSession = save(touch(createSession())); AbstractSessionEvent sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); - assertThat(sessionEvent.getSession()).isEqualTo(expectedSession); + assertThat(sessionEvent.getSession()).isEqualTo(expectedSession); assertThat(this.sessionEventListener.getSessionEvent()).isNull(); - ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); + Session savedSession = this.gemfireSessionRepository.findById(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); @@ -226,7 +230,7 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests assertThat(sessionEvent).isInstanceOf(SessionExpiredEvent.class); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSession.getId()); - ExpiringSession expiredSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); + Session expiredSession = this.gemfireSessionRepository.findById(expectedSession.getId()); assertThat(expiredSession).isNull(); } @@ -234,21 +238,21 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests @Test public void deleteExistingNonExpiredSessionFiresSessionDeletedEventAndReturnsNullOnGet() { - ExpiringSession expectedSession = save(touch(createSession())); + Session expectedSession = save(touch(createSession())); AbstractSessionEvent sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); - assertThat(sessionEvent.getSession()).isEqualTo(expectedSession); + assertThat(sessionEvent.getSession()).isEqualTo(expectedSession); - this.gemfireSessionRepository.delete(expectedSession.getId()); + this.gemfireSessionRepository.deleteById(expectedSession.getId()); sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionDeletedEvent.class); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSession.getId()); - ExpiringSession deletedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); + Session deletedSession = this.gemfireSessionRepository.findById(expectedSession.getId()); assertThat(deletedSession).isNull(); } @@ -256,6 +260,7 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, clientRegionShortcut = ClientRegionShortcut.CACHING_PROXY, maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) + @SuppressWarnings("unused") static class SpringSessionDataGemFireClientConfiguration { @Bean @@ -264,13 +269,17 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests } Properties gemfireProperties() { + Properties gemfireProperties = new Properties(); + gemfireProperties.setProperty("log-level", GEMFIRE_LOG_LEVEL); + return gemfireProperties; } @Bean ClientCacheFactoryBean gemfireCache() { + ClientCacheFactoryBean clientCacheFactory = new ClientCacheFactoryBean(); clientCacheFactory.setClose(true); @@ -305,6 +314,7 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests // used for debugging purposes @SuppressWarnings("resource") public static void main(String[] args) { + ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext( SpringSessionDataGemFireClientConfiguration.class); @@ -321,6 +331,7 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) + @SuppressWarnings("unused") static class SpringSessionDataGemFireServerConfiguration { static final String SERVER_HOSTNAME = "localhost"; diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerHttpSessionAttributesDeltaIntegrationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerHttpSessionAttributesDeltaIntegrationTests.java index 9a620f4..bad5608 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerHttpSessionAttributesDeltaIntegrationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerHttpSessionAttributesDeltaIntegrationTests.java @@ -47,7 +47,7 @@ import org.springframework.data.gemfire.client.ClientCacheFactoryBean; import org.springframework.data.gemfire.client.PoolFactoryBean; import org.springframework.data.gemfire.server.CacheServerFactoryBean; import org.springframework.data.gemfire.support.ConnectionEndpoint; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @@ -63,7 +63,7 @@ import org.springframework.util.SocketUtils; * @see org.junit.Test * @see org.junit.runner.RunWith * @see org.springframework.context.ConfigurableApplicationContext - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests * @see org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession * @see org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration @@ -132,7 +132,7 @@ public class ClientServerHttpSessionAttributesDeltaIntegrationTests extends Abst @Test public void sessionCreationAndAccessIsSuccessful() { - ExpiringSession session = save(touch(createSession())); + Session session = save(touch(createSession())); assertThat(session).isNotNull(); assertThat(session.isExpired()).isFalse(); @@ -142,7 +142,7 @@ public class ClientServerHttpSessionAttributesDeltaIntegrationTests extends Abst save(touch(session)); - ExpiringSession loadedSession = get(session.getId()); + Session loadedSession = get(session.getId()); assertThat(loadedSession).isNotNull(); assertThat(loadedSession.isExpired()).isFalse(); @@ -158,7 +158,7 @@ public class ClientServerHttpSessionAttributesDeltaIntegrationTests extends Abst save(touch(loadedSession)); - ExpiringSession reloadedSession = get(loadedSession.getId()); + Session reloadedSession = get(loadedSession.getId()); assertThat(reloadedSession).isNotNull(); assertThat(reloadedSession.isExpired()).isFalse(); @@ -170,6 +170,7 @@ public class ClientServerHttpSessionAttributesDeltaIntegrationTests extends Abst } @EnableGemFireHttpSession + @SuppressWarnings("unused") static class SpringSessionDataGemFireClientConfiguration { @Bean @@ -234,6 +235,7 @@ public class ClientServerHttpSessionAttributesDeltaIntegrationTests extends Abst } @EnableGemFireHttpSession(maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) + @SuppressWarnings("unused") static class SpringSessionDataGemFireServerConfiguration { static final String SERVER_HOSTNAME = "localhost"; diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerProxyRegionSessionOperationsIntegrationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerProxyRegionSessionOperationsIntegrationTests.java index 215b298..fa9a3dc 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerProxyRegionSessionOperationsIntegrationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerProxyRegionSessionOperationsIntegrationTests.java @@ -48,7 +48,7 @@ import org.springframework.data.gemfire.client.ClientCacheFactoryBean; import org.springframework.data.gemfire.client.PoolFactoryBean; import org.springframework.data.gemfire.server.CacheServerFactoryBean; import org.springframework.data.gemfire.support.ConnectionEndpoint; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; import org.springframework.session.events.AbstractSessionEvent; import org.springframework.session.events.SessionCreatedEvent; @@ -126,7 +126,7 @@ public class ClientServerProxyRegionSessionOperationsIntegrationTests extends Ab @Test public void createReadUpdateExpireRecreateDeleteRecreateSessionResultsCorrectSessionCreatedEvents() { - ExpiringSession session = save(touch(createSession())); + Session session = save(touch(createSession())); assertValidSession(session); @@ -136,12 +136,12 @@ public class ClientServerProxyRegionSessionOperationsIntegrationTests extends Ab assertThat(sessionEvent.getSessionId()).isEqualTo(session.getId()); // GET - ExpiringSession loadedSession = get(session.getId()); + Session loadedSession = get(session.getId()); assertThat(loadedSession).isNotNull(); assertThat(loadedSession.getId()).isEqualTo(session.getId()); assertThat(loadedSession.getCreationTime()).isEqualTo(session.getCreationTime()); - assertThat(loadedSession.getLastAccessedTime()).isGreaterThanOrEqualTo((session.getLastAccessedTime())); + assertThat(loadedSession.getLastAccessedTime().compareTo(session.getLastAccessedTime())).isGreaterThanOrEqualTo(0); sessionEvent = this.sessionEventListener.waitForSessionEvent(500); @@ -190,6 +190,7 @@ public class ClientServerProxyRegionSessionOperationsIntegrationTests extends Ab } @EnableGemFireHttpSession + @SuppressWarnings("unused") static class SpringSessionDataGemFireClientConfiguration { @Bean @@ -259,6 +260,7 @@ public class ClientServerProxyRegionSessionOperationsIntegrationTests extends Ab } @EnableGemFireHttpSession(maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) + @SuppressWarnings("unused") static class SpringSessionDataGemFireServerConfiguration { static final String SERVER_HOSTNAME = "localhost"; diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryIntegrationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryIntegrationTests.java index e062d46..e210436 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryIntegrationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryIntegrationTests.java @@ -22,7 +22,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Properties; import java.util.UUID; import org.junit.Before; @@ -39,14 +38,13 @@ import org.apache.geode.pdx.PdxReader; import org.apache.geode.pdx.PdxSerializable; import org.apache.geode.pdx.PdxWriter; -import org.springframework.context.annotation.Bean; -import org.springframework.data.gemfire.CacheFactoryBean; +import org.springframework.data.gemfire.config.annotation.PeerCacheApplication; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.session.ExpiringSession; import org.springframework.session.FindByIndexNameSessionRepository; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -108,29 +106,29 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract assertThat(this.gemfireSessionRepository.getMaxInactiveIntervalInSeconds()) .isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); - Region sessionRegion = this.gemfireCache.getRegion(SPRING_SESSION_GEMFIRE_REGION_NAME); + Region sessionRegion = this.gemfireCache.getRegion(SPRING_SESSION_GEMFIRE_REGION_NAME); assertRegion(sessionRegion, SPRING_SESSION_GEMFIRE_REGION_NAME, DataPolicy.PARTITION); assertEntryIdleTimeout(sessionRegion, ExpirationAction.INVALIDATE, MAX_INACTIVE_INTERVAL_IN_SECONDS); } - protected Map doFindByIndexNameAndIndexValue( + protected Map doFindByIndexNameAndIndexValue( String indexName, String indexValue) { return this.gemfireSessionRepository.findByIndexNameAndIndexValue(indexName, indexValue); } - protected Map doFindByPrincipalName(String principalName) { + protected Map doFindByPrincipalName(String principalName) { return doFindByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName); } - @SuppressWarnings({ "unchecked" }) - protected Map doFindByPrincipalName(String regionName, + @SuppressWarnings({ "unchecked", "unused" }) + protected Map doFindByPrincipalName(String regionName, String principalName) { try { - Region region = this.gemfireCache.getRegion(regionName); + Region region = this.gemfireCache.getRegion(regionName); assertThat(region).isNotNull(); @@ -141,12 +139,12 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract Query query = queryService.newQuery(queryString); - SelectResults results = - (SelectResults) query.execute(new Object[] { principalName }); + SelectResults results = + (SelectResults) query.execute(new Object[] { principalName }); - Map sessions = new HashMap(results.size()); + Map sessions = new HashMap<>(results.size()); - for (ExpiringSession session : results.asList()) { + for (Session session : results.asList()) { sessions.put(session.getId(), session); } @@ -162,7 +160,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract return true; } - protected ExpiringSession setAttribute(ExpiringSession session, String attributeName, + protected Session setAttribute(Session session, String attributeName, Object attributeValue) { session.setAttribute(attributeName, attributeValue); @@ -173,28 +171,28 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void findSessionsByIndexedSessionAttributeNameValues() { - ExpiringSession johnBlumSession = save(touch(setAttribute( + Session johnBlumSession = save(touch(setAttribute( createSession("johnBlum"), "vip", "yes"))); - ExpiringSession robWinchSession = save(touch(setAttribute( + Session robWinchSession = save(touch(setAttribute( createSession("robWinch"), "vip", "yes"))); - ExpiringSession jonDoeSession = save(touch(setAttribute( + Session jonDoeSession = save(touch(setAttribute( createSession("jonDoe"), "vip", "no"))); - ExpiringSession pieDoeSession = save(touch(setAttribute( + Session pieDoeSession = save(touch(setAttribute( createSession("pieDoe"), "viper", "true"))); - ExpiringSession sourDoeSession = save(touch(createSession("sourDoe"))); + Session sourDoeSession = save(touch(createSession("sourDoe"))); - assertThat(this.get(johnBlumSession.getId())).isEqualTo(johnBlumSession); + assertThat(this.get(johnBlumSession.getId())).isEqualTo(johnBlumSession); assertThat(johnBlumSession.getAttribute("vip")).isEqualTo("yes"); - assertThat(this.get(robWinchSession.getId())).isEqualTo(robWinchSession); + assertThat(this.get(robWinchSession.getId())).isEqualTo(robWinchSession); assertThat(robWinchSession.getAttribute("vip")).isEqualTo("yes"); - assertThat(this.get(jonDoeSession.getId())).isEqualTo(jonDoeSession); + assertThat(this.get(jonDoeSession.getId())).isEqualTo(jonDoeSession); assertThat(jonDoeSession.getAttribute("vip")).isEqualTo("no"); - assertThat(this.get(pieDoeSession.getId())).isEqualTo(pieDoeSession); + assertThat(this.get(pieDoeSession.getId())).isEqualTo(pieDoeSession); assertThat(pieDoeSession.getAttributeNames().contains("vip")).isFalse(); - assertThat(this.get(sourDoeSession.getId())).isEqualTo(sourDoeSession); + assertThat(this.get(sourDoeSession.getId())).isEqualTo(sourDoeSession); assertThat(sourDoeSession.getAttributeNames().contains("vip")).isFalse(); - Map vipSessions = doFindByIndexNameAndIndexValue("vip", "yes"); + Map vipSessions = doFindByIndexNameAndIndexValue("vip", "yes"); assertThat(vipSessions).isNotNull(); assertThat(vipSessions.size()).isEqualTo(2); @@ -204,7 +202,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract assertThat(vipSessions.containsKey(pieDoeSession.getId())); assertThat(vipSessions.containsKey(sourDoeSession.getId())); - Map nonVipSessions = doFindByIndexNameAndIndexValue( + Map nonVipSessions = doFindByIndexNameAndIndexValue( "vip", "no"); assertThat(nonVipSessions).isNotNull(); @@ -215,7 +213,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract assertThat(nonVipSessions.containsKey(pieDoeSession.getId())); assertThat(nonVipSessions.containsKey(sourDoeSession.getId())); - Map noSessions = doFindByIndexNameAndIndexValue( + Map noSessions = doFindByIndexNameAndIndexValue( "nonExistingAttribute", "test"); assertThat(noSessions).isNotNull(); @@ -225,19 +223,19 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void findSessionsByPrincipalName() { - ExpiringSession sessionOne = save(touch(createSession("robWinch"))); - ExpiringSession sessionTwo = save(touch(createSession("johnBlum"))); - ExpiringSession sessionThree = save(touch(createSession("robWinch"))); - ExpiringSession sessionFour = save(touch(createSession("johnBlum"))); - ExpiringSession sessionFive = save(touch(createSession("robWinch"))); + Session sessionOne = save(touch(createSession("robWinch"))); + Session sessionTwo = save(touch(createSession("johnBlum"))); + Session sessionThree = save(touch(createSession("robWinch"))); + Session sessionFour = save(touch(createSession("johnBlum"))); + Session sessionFive = save(touch(createSession("robWinch"))); - assertThat(this.get(sessionOne.getId())).isEqualTo(sessionOne); - assertThat(this.get(sessionTwo.getId())).isEqualTo(sessionTwo); - assertThat(this.get(sessionThree.getId())).isEqualTo(sessionThree); - assertThat(this.get(sessionFour.getId())).isEqualTo(sessionFour); - assertThat(this.get(sessionFive.getId())).isEqualTo(sessionFive); + assertThat(this.get(sessionOne.getId())).isEqualTo(sessionOne); + assertThat(this.get(sessionTwo.getId())).isEqualTo(sessionTwo); + assertThat(this.get(sessionThree.getId())).isEqualTo(sessionThree); + assertThat(this.get(sessionFour.getId())).isEqualTo(sessionFour); + assertThat(this.get(sessionFive.getId())).isEqualTo(sessionFive); - Map johnBlumSessions = doFindByPrincipalName("johnBlum"); + Map johnBlumSessions = doFindByPrincipalName("johnBlum"); assertThat(johnBlumSessions).isNotNull(); assertThat(johnBlumSessions.size()).isEqualTo(2); @@ -247,7 +245,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract assertThat(johnBlumSessions.get(sessionTwo.getId())).isEqualTo(sessionTwo); assertThat(johnBlumSessions.get(sessionFour.getId())).isEqualTo(sessionFour); - Map robWinchSessions = doFindByPrincipalName("robWinch"); + Map robWinchSessions = doFindByPrincipalName("robWinch"); assertThat(robWinchSessions).isNotNull(); assertThat(robWinchSessions.size()).isEqualTo(3); @@ -261,13 +259,13 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void findSessionsBySecurityPrincipalName() { - ExpiringSession toSave = this.gemfireSessionRepository.createSession(); + Session toSave = this.gemfireSessionRepository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); save(toSave); - Map findByPrincipalName = doFindByPrincipalName(getSecurityName()); + Map findByPrincipalName = doFindByPrincipalName(getSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -276,7 +274,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void findSessionsByChangedSecurityPrincipalName() { - ExpiringSession toSave = this.gemfireSessionRepository.createSession(); + Session toSave = this.gemfireSessionRepository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); @@ -286,7 +284,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract save(toSave); - Map findByPrincipalName = doFindByPrincipalName(getSecurityName()); + Map findByPrincipalName = doFindByPrincipalName(getSecurityName()); assertThat(findByPrincipalName).isEmpty(); @@ -298,7 +296,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void findsNoSessionsByNonExistingPrincipal() { - Map nonExistingPrincipalSessions = doFindByPrincipalName("nonExistingPrincipalName"); + Map nonExistingPrincipalSessions = doFindByPrincipalName("nonExistingPrincipalName"); assertThat(nonExistingPrincipalSessions).isNotNull(); assertThat(nonExistingPrincipalSessions.isEmpty()).isTrue(); @@ -309,13 +307,13 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract String username = "doesNotFindAfterPrincipalRemoved"; - ExpiringSession session = save(touch(createSession(username))); + Session session = save(touch(createSession(username))); session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, null); save(session); - Map nonExistingPrincipalSessions = doFindByPrincipalName(username); + Map nonExistingPrincipalSessions = doFindByPrincipalName(username); assertThat(nonExistingPrincipalSessions).isNotNull(); assertThat(nonExistingPrincipalSessions.isEmpty()).isTrue(); @@ -324,7 +322,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void saveAndReadSessionWithAttributes() { - ExpiringSession expectedSession = this.gemfireSessionRepository.createSession(); + Session expectedSession = this.gemfireSessionRepository.createSession(); assertThat(expectedSession).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class); @@ -342,7 +340,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract this.gemfireSessionRepository.save(touch(expectedSession)); - ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); + Session savedSession = this.gemfireSessionRepository.findById(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); assertThat(savedSession).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class); @@ -367,29 +365,10 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract return this.changedContext.getAuthentication().getName(); } - @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) + @PeerCacheApplication(name = "GemFireOperationsSessionRepositoryIntegrationTests", logLevel = GEMFIRE_LOG_LEVEL) + @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, + maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) static class SpringSessionGemFireConfiguration { - - Properties gemfireProperties() { - - Properties gemfireProperties = new Properties(); - - gemfireProperties.setProperty("name", GemFireOperationsSessionRepositoryIntegrationTests.class.getName()); - gemfireProperties.setProperty("log-level", GEMFIRE_LOG_LEVEL); - - return gemfireProperties; - } - - @Bean - CacheFactoryBean gemfireCache() { - - CacheFactoryBean gemfireCache = new CacheFactoryBean(); - - gemfireCache.setClose(true); - gemfireCache.setProperties(gemfireProperties()); - - return gemfireCache; - } } public static class Person implements Comparable, PdxSerializable { @@ -406,7 +385,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract } private String validate(String value) { - Assert.hasText(value, String.format("The String value (%1$s) must be specified!", value)); + Assert.hasText(value, String.format("Value [%s] is required", value)); return value; } diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationTests.java index e37a435..7cd2c9e 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationTests.java @@ -51,7 +51,7 @@ import org.springframework.data.gemfire.client.ClientCacheFactoryBean; import org.springframework.data.gemfire.client.PoolFactoryBean; import org.springframework.data.gemfire.server.CacheServerFactoryBean; import org.springframework.data.gemfire.support.ConnectionEndpoint; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.session.events.AbstractSessionEvent; @@ -86,8 +86,8 @@ import org.springframework.util.SocketUtils; * @since 1.3.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationTests - .SpringSessionGemFireClientConfiguration.class) +@ContextConfiguration(classes = + MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationTests.SpringSessionGemFireClientConfiguration.class) @DirtiesContext @WebAppConfiguration public class MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationTests @@ -152,12 +152,12 @@ public class MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationT assertThat(GemFireUtils.isClient(gemfireCache)).isTrue(); - Region springSessionGemFireRegion = + Region springSessionGemFireRegion = gemfireCache.getRegion(SPRING_SESSION_GEMFIRE_REGION_NAME); assertThat(springSessionGemFireRegion).isNotNull(); - RegionAttributes springSessionGemFireRegionAttributes = + RegionAttributes springSessionGemFireRegionAttributes = springSessionGemFireRegion.getAttributes(); assertThat(springSessionGemFireRegionAttributes).isNotNull(); @@ -171,15 +171,15 @@ public class MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationT @Test public void getExistingNonExpiredSessionBeforeAndAfterExpiration() { - ExpiringSession expectedSession = save(touch(createSession())); + Session expectedSession = save(touch(createSession())); AbstractSessionEvent sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); - assertThat(sessionEvent.getSession()).isEqualTo(expectedSession); + assertThat(sessionEvent.getSession()).isEqualTo(expectedSession); assertThat(this.sessionEventListener.getSessionEvent()).isNull(); - ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); + Session savedSession = this.gemfireSessionRepository.findById(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); @@ -191,13 +191,14 @@ public class MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationT assertThat(sessionEvent).isInstanceOf(SessionExpiredEvent.class); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSession.getId()); - ExpiringSession expiredSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); + Session expiredSession = this.gemfireSessionRepository.findById(expectedSession.getId()); assertThat(expiredSession).isNull(); } @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, poolName = "serverPool", maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) + @SuppressWarnings("unused") static class SpringSessionGemFireClientConfiguration { @Bean @@ -292,7 +293,9 @@ public class MultiPoolClientServerGemFireOperationsSessionRepositoryIntegrationT } } - @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) + @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, + maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) + @SuppressWarnings("unused") static class SpringSessionGemFireServerConfiguration { static final int MAX_CONNECTIONS = 50; diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSessionEventsIntegrationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSessionEventsIntegrationTests.java index 040669a..234b180 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSessionEventsIntegrationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSessionEventsIntegrationTests.java @@ -18,7 +18,8 @@ package org.springframework.session.data.gemfire.config.annotation.web.http; import static org.assertj.core.api.Assertions.assertThat; -import java.util.Properties; +import java.time.Duration; +import java.time.Instant; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -34,9 +35,10 @@ import org.apache.geode.cache.RegionShortcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.data.gemfire.CacheFactoryBean; -import org.springframework.session.ExpiringSession; +import org.springframework.data.gemfire.config.annotation.PeerCacheApplication; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests; +import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.session.events.AbstractSessionEvent; import org.springframework.session.events.SessionCreatedEvent; @@ -44,19 +46,19 @@ import org.springframework.session.events.SessionDeletedEvent; import org.springframework.session.events.SessionExpiredEvent; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; /** - * The EnableGemFireHttpSessionEventsIntegrationTests class is a test suite of test cases - * testing the Session Event functionality and behavior of the - * GemFireOperationsSessionRepository and GemFire's configuration. + * Integration test suite of test cases testing the Session Event functionality and behavior + * of the {@link GemFireOperationsSessionRepository} and GemFire's configuration. * * @author John Blum * @since 1.1.0 * @see org.junit.Test * @see org.junit.runner.RunWith - * @see org.springframework.session.ExpiringSession + * @see org.apache.geode.cache.Region + * @see org.springframework.session.Session * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests * @see org.springframework.session.data.gemfire.GemFireOperationsSessionRepository * @see org.springframework.session.events.SessionCreatedEvent @@ -64,11 +66,10 @@ import org.springframework.test.context.web.WebAppConfiguration; * @see org.springframework.session.events.SessionExpiredEvent * @see org.springframework.test.annotation.DirtiesContext * @see org.springframework.test.context.ContextConfiguration - * @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner + * @see org.springframework.test.context.junit4.SpringRunner * @see org.springframework.test.context.web.WebAppConfiguration - * @see org.apache.geode.cache.Region */ -@RunWith(SpringJUnit4ClassRunner.class) +@RunWith(SpringRunner.class) @ContextConfiguration @DirtiesContext @WebAppConfiguration @@ -77,7 +78,7 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF private static final int MAX_INACTIVE_INTERVAL_IN_SECONDS = 1; private static final String GEMFIRE_LOG_LEVEL = "warning"; - private static final String SPRING_SESSION_GEMFIRE_REGION_NAME = "TestReplicatedSessions"; + private static final String SPRING_SESSION_DATA_GEMFIRE_REGION_NAME = "TestReplicatedSessions"; @Autowired private SessionEventListener sessionEventListener; @@ -90,9 +91,9 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF assertThat(this.gemfireSessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); assertThat(this.sessionEventListener).isNotNull(); - Region sessionRegion = this.gemfireCache.getRegion(SPRING_SESSION_GEMFIRE_REGION_NAME); + Region sessionRegion = this.gemfireCache.getRegion(SPRING_SESSION_DATA_GEMFIRE_REGION_NAME); - assertRegion(sessionRegion, SPRING_SESSION_GEMFIRE_REGION_NAME, DataPolicy.REPLICATE); + assertRegion(sessionRegion, SPRING_SESSION_DATA_GEMFIRE_REGION_NAME, DataPolicy.REPLICATE); assertEntryIdleTimeout(sessionRegion, ExpirationAction.INVALIDATE, MAX_INACTIVE_INTERVAL_IN_SECONDS); } @@ -104,33 +105,33 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF @Test public void sessionCreatedEvent() { - final long beforeOrAtCreationTime = System.currentTimeMillis(); + Instant beforeOrAtCreationTime = Instant.now(); - ExpiringSession expectedSession = save(createSession()); + Session expectedSession = save(createSession()); AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); - ExpiringSession createdSession = sessionEvent.getSession(); + Session createdSession = sessionEvent.getSession(); assertThat(createdSession).isEqualTo(expectedSession); assertThat(createdSession.getId()).isNotNull(); - assertThat(createdSession.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); + assertThat(createdSession.getCreationTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); assertThat(createdSession.getLastAccessedTime()).isEqualTo(createdSession.getCreationTime()); - assertThat(createdSession.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); + assertThat(createdSession.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS)); assertThat(createdSession.isExpired()).isFalse(); } @Test public void getExistingNonExpiredSession() { - ExpiringSession expectedSession = save(touch(createSession())); + Session expectedSession = save(touch(createSession())); assertThat(expectedSession.isExpired()).isFalse(); // NOTE though unlikely, a possible race condition exists between save and get... - ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); + Session savedSession = this.gemfireSessionRepository.findById(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); } @@ -138,56 +139,56 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF @Test public void getExistingExpiredSession() { - ExpiringSession expectedSession = save(expire(createSession())); + Session expectedSession = save(expire(createSession())); AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); - ExpiringSession createdSession = sessionEvent.getSession(); + Session createdSession = sessionEvent.getSession(); assertThat(createdSession).isEqualTo(expectedSession); assertThat(createdSession.isExpired()).isTrue(); - assertThat(this.gemfireSessionRepository.getSession(createdSession.getId())).isNull(); + assertThat(this.gemfireSessionRepository.findById(createdSession.getId())).isNull(); } @Test public void getNonExistingSession() { - assertThat(this.gemfireSessionRepository.getSession(UUID.randomUUID().toString())).isNull(); + assertThat(this.gemfireSessionRepository.findById(UUID.randomUUID().toString())).isNull(); } @Test public void deleteExistingNonExpiredSession() { - ExpiringSession expectedSession = save(touch(createSession())); - ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); + Session expectedSession = save(touch(createSession())); + Session savedSession = this.gemfireSessionRepository.findById(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); assertThat(savedSession.isExpired()).isFalse(); - this.gemfireSessionRepository.delete(savedSession.getId()); + this.gemfireSessionRepository.deleteById(savedSession.getId()); AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionDeletedEvent.class); assertThat(sessionEvent.getSessionId()).isEqualTo(savedSession.getId()); - ExpiringSession deletedSession = sessionEvent.getSession(); + Session deletedSession = sessionEvent.getSession(); assertThat(deletedSession).isEqualTo(savedSession); - assertThat(this.gemfireSessionRepository.getSession(deletedSession.getId())).isNull(); + assertThat(this.gemfireSessionRepository.findById(deletedSession.getId())).isNull(); } @Test public void deleteExistingExpiredSession() { - ExpiringSession expectedSession = save(createSession()); + Session expectedSession = save(createSession()); AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); - ExpiringSession createdSession = sessionEvent.getSession(); + Session createdSession = sessionEvent.getSession(); assertThat(createdSession).isEqualTo(expectedSession); @@ -196,19 +197,19 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF assertThat(sessionEvent).isInstanceOf(SessionExpiredEvent.class); - ExpiringSession expiredSession = sessionEvent.getSession(); + Session expiredSession = sessionEvent.getSession(); assertThat(expiredSession).isEqualTo(createdSession); assertThat(expiredSession.isExpired()).isTrue(); - this.gemfireSessionRepository.delete(expectedSession.getId()); + this.gemfireSessionRepository.deleteById(expectedSession.getId()); sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionDeletedEvent.class); - assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(expiredSession.getId()); - assertThat(this.gemfireSessionRepository.getSession(sessionEvent.getSessionId())).isNull(); + assertThat(this.gemfireSessionRepository.findById(sessionEvent.getSessionId())).isNull(); } @Test @@ -216,43 +217,24 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF String expectedSessionId = UUID.randomUUID().toString(); - assertThat(this.gemfireSessionRepository.getSession(expectedSessionId)).isNull(); + assertThat(this.gemfireSessionRepository.findById(expectedSessionId)).isNull(); - this.gemfireSessionRepository.delete(expectedSessionId); + this.gemfireSessionRepository.deleteById(expectedSessionId); AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionDeletedEvent.class); - assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); } - @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS, serverRegionShortcut = RegionShortcut.REPLICATE) + @PeerCacheApplication(name = "EnableGemFireHttpSessionEventsIntegrationTests", logLevel = GEMFIRE_LOG_LEVEL) + @EnableGemFireHttpSession(regionName = SPRING_SESSION_DATA_GEMFIRE_REGION_NAME, + maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS, + serverRegionShortcut = RegionShortcut.REPLICATE) + @SuppressWarnings("unused") static class SpringSessionGemFireConfiguration { - @Bean - Properties gemfireProperties() { - - Properties gemfireProperties = new Properties(); - - gemfireProperties.setProperty("name", EnableGemFireHttpSessionEventsIntegrationTests.class.getName()); - gemfireProperties.setProperty("mcast-port", "0"); - gemfireProperties.setProperty("log-level", GEMFIRE_LOG_LEVEL); - - return gemfireProperties; - } - - @Bean - CacheFactoryBean gemfireCache() { - - CacheFactoryBean gemfireCache = new CacheFactoryBean(); - - gemfireCache.setClose(true); - gemfireCache.setProperties(gemfireProperties()); - - return gemfireCache; - } - @Bean SessionEventListener sessionEventListener() { return new SessionEventListener(); diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionJavaConfigurationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionJavaConfigurationTests.java index 2209520..a2c3a52 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionJavaConfigurationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionJavaConfigurationTests.java @@ -18,8 +18,6 @@ package org.springframework.session.data.gemfire.config.annotation.web.http; import static org.assertj.core.api.Assertions.assertThat; -import java.util.Properties; - import org.junit.Test; import org.junit.runner.RunWith; @@ -32,9 +30,8 @@ import org.apache.geode.cache.query.Index; import org.apache.geode.cache.query.QueryService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.data.gemfire.CacheFactoryBean; -import org.springframework.session.ExpiringSession; +import org.springframework.data.gemfire.config.annotation.PeerCacheApplication; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests; import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.test.annotation.DirtiesContext; @@ -49,7 +46,7 @@ import org.springframework.test.context.web.WebAppConfiguration; * @author John Blum * @since 1.1.0 * @see org.junit.Test - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests * @see org.springframework.test.annotation.DirtiesContext * @see org.springframework.test.context.ContextConfiguration @@ -82,7 +79,7 @@ public class GemFireHttpSessionJavaConfigurationTests extends AbstractGemFireInt @Test public void gemfireCacheConfigurationIsValid() { - Region example = + Region example = assertCacheAndRegion(this.gemfireCache, "JavaExample", DataPolicy.REPLICATE); assertEntryIdleTimeout(example, ExpirationAction.INVALIDATE, 900); @@ -91,7 +88,7 @@ public class GemFireHttpSessionJavaConfigurationTests extends AbstractGemFireInt @Test public void verifyGemFireExampleCacheRegionPrincipalNameIndexWasCreatedSuccessfully() { - Region example = + Region example = assertCacheAndRegion(this.gemfireCache, "JavaExample", DataPolicy.REPLICATE); QueryService queryService = example.getRegionService().getQueryService(); @@ -106,7 +103,7 @@ public class GemFireHttpSessionJavaConfigurationTests extends AbstractGemFireInt @Test public void verifyGemFireExampleCacheRegionSessionAttributesIndexWasNotCreated() { - Region example = + Region example = assertCacheAndRegion(this.gemfireCache, "JavaExample", DataPolicy.REPLICATE); QueryService queryService = example.getRegionService().getQueryService(); @@ -118,38 +115,9 @@ public class GemFireHttpSessionJavaConfigurationTests extends AbstractGemFireInt assertThat(sessionAttributesIndex).isNull(); } - @EnableGemFireHttpSession(indexableSessionAttributes = {}, maxInactiveIntervalInSeconds = 900, - regionName = "JavaExample", serverRegionShortcut = RegionShortcut.REPLICATE) - public static class GemFireConfiguration { - - Properties gemfireProperties() { - - Properties gemfireProperties = new Properties(); - - gemfireProperties.setProperty("name", applicationName()); - gemfireProperties.setProperty("mcast-port", "0"); - gemfireProperties.setProperty("log-level", logLevel()); - - return gemfireProperties; - } - - String applicationName() { - return GemFireHttpSessionJavaConfigurationTests.class.getName(); - } - - String logLevel() { - return "warning"; - } - - @Bean - CacheFactoryBean gemfireCache() { - - CacheFactoryBean cacheFactory = new CacheFactoryBean(); - - cacheFactory.setClose(true); - cacheFactory.setProperties(gemfireProperties()); - - return cacheFactory; - } + @PeerCacheApplication(name = "GemFireHttpSessionJavaConfigurationTests", logLevel = "warning") + @EnableGemFireHttpSession(maxInactiveIntervalInSeconds = 900, regionName = "JavaExample", + serverRegionShortcut = RegionShortcut.REPLICATE) + static class GemFireConfiguration { } } diff --git a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionXmlConfigurationTests.java b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionXmlConfigurationTests.java index 156e71a..b217221 100644 --- a/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionXmlConfigurationTests.java +++ b/spring-session-data-geode/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionXmlConfigurationTests.java @@ -29,12 +29,12 @@ import org.apache.geode.cache.query.Index; import org.apache.geode.cache.query.QueryService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests; import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; /** @@ -44,26 +44,28 @@ import org.springframework.test.context.web.WebAppConfiguration; * @author John Blum * @since 1.1.0 * @see org.junit.Test - * @see org.springframework.session.ExpiringSession + * @see org.apache.geode.cache.Cache + * @see org.apache.geode.cache.Region + * @see org.apache.geode.cache.query.Index + * @see org.apache.geode.cache.query.QueryService + * @see org.springframework.session.Session * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests * @see org.springframework.test.annotation.DirtiesContext * @see org.springframework.test.context.ContextConfiguration - * @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner + * @see org.springframework.test.context.junit4.SpringRunner * @see org.springframework.test.context.web.WebAppConfiguration - * @see org.apache.geode.cache.Cache - * @see org.apache.geode.cache.Region */ -@RunWith(SpringJUnit4ClassRunner.class) +@RunWith(SpringRunner.class) @ContextConfiguration @DirtiesContext @WebAppConfiguration public class GemFireHttpSessionXmlConfigurationTests extends AbstractGemFireIntegrationTests { @Autowired + @SuppressWarnings("all") private Cache gemfireCache; - protected Region assertCacheAndRegion(Cache gemfireCache, - String regionName, DataPolicy dataPolicy) { + protected Region assertCacheAndRegion(Cache gemfireCache, String regionName, DataPolicy dataPolicy) { assertThat(GemFireUtils.isPeer(gemfireCache)).isTrue(); @@ -77,7 +79,7 @@ public class GemFireHttpSessionXmlConfigurationTests extends AbstractGemFireInte @Test public void gemfireCacheConfigurationIsValid() { - Region example = + Region example = assertCacheAndRegion(this.gemfireCache, "XmlExample", DataPolicy.NORMAL); assertEntryIdleTimeout(example, ExpirationAction.INVALIDATE, 3600); @@ -86,7 +88,7 @@ public class GemFireHttpSessionXmlConfigurationTests extends AbstractGemFireInte @Test public void verifyGemFireExampleCacheRegionPrincipalNameIndexWasCreatedSuccessfully() { - Region example = + Region example = assertCacheAndRegion(this.gemfireCache, "XmlExample", DataPolicy.NORMAL); QueryService queryService = example.getRegionService().getQueryService(); @@ -101,7 +103,7 @@ public class GemFireHttpSessionXmlConfigurationTests extends AbstractGemFireInte @Test public void verifyGemFireExampleCacheRegionSessionAttributesIndexWasCreatedSuccessfully() { - Region example = + Region example = assertCacheAndRegion(this.gemfireCache, "XmlExample", DataPolicy.NORMAL); QueryService queryService = example.getRegionService().getQueryService(); diff --git a/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepository.java b/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepository.java index 1aec4ac..1ffe6ac 100644 --- a/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepository.java +++ b/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepository.java @@ -19,20 +19,19 @@ package org.springframework.session.data.gemfire; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.Instant; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collections; -import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.TimeUnit; import org.apache.geode.DataSerializable; import org.apache.geode.DataSerializer; @@ -52,7 +51,6 @@ import org.springframework.data.gemfire.GemfireAccessor; import org.springframework.data.gemfire.GemfireOperations; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; -import org.springframework.session.ExpiringSession; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.Session; import org.springframework.session.SessionRepository; @@ -85,7 +83,6 @@ import org.apache.commons.logging.LogFactory; * @see org.springframework.context.ApplicationEventPublisherAware * @see org.springframework.data.gemfire.GemfireOperations * @see org.springframework.expression.Expression - * @see org.springframework.session.ExpiringSession * @see org.springframework.session.FindByIndexNameSessionRepository * @see org.springframework.session.Session * @see org.springframework.session.SessionRepository @@ -93,12 +90,11 @@ import org.apache.commons.logging.LogFactory; * @see org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession * @since 1.1.0 */ -public abstract class AbstractGemFireOperationsSessionRepository extends CacheListenerAdapter - implements ApplicationEventPublisherAware, FindByIndexNameSessionRepository, InitializingBean { - - private int maxInactiveIntervalInSeconds = GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS; +public abstract class AbstractGemFireOperationsSessionRepository extends CacheListenerAdapter + implements ApplicationEventPublisherAware, FindByIndexNameSessionRepository, InitializingBean { private ApplicationEventPublisher applicationEventPublisher = new ApplicationEventPublisher() { + public void publishEvent(ApplicationEvent event) { } @@ -106,32 +102,41 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi } }; - private final Set cachedSessionIds = new ConcurrentSkipListSet<>(); + private Duration maxInactiveInterval = + Duration.ofSeconds(GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS); private final GemfireOperations template; - protected final Log logger = newLogger(); + private final Log logger = newLogger(); + + private final Set cachedSessionIds = new ConcurrentSkipListSet<>(); private String fullyQualifiedRegionName; /** - * Constructs an instance of AbstractGemFireOperationsSessionRepository with a - * required GemfireOperations instance used to perform GemFire data access operations + * Constructs an instance of {@link AbstractGemFireOperationsSessionRepository} + * with a required {@link GemfireOperations} instance used to perform GemFire data access operations * and interactions supporting the SessionRepository operations. * - * @param template the GemfireOperations instance used to interact with GemFire. + * @param template {@link GemfireOperations} instance used to interact with GemFire; must not be {@literal null}. + * @throws IllegalArgumentException if {@link GemfireOperations} is {@literal null}. * @see org.springframework.data.gemfire.GemfireOperations */ public AbstractGemFireOperationsSessionRepository(GemfireOperations template) { + Assert.notNull(template, "GemfireOperations must not be null"); + this.template = template; } /** - * Used for testing purposes only to override the Log implementation with a mock. + * Constructs a new instance of {@link Log} using Apache Commons {@link LogFactory}. * - * @return an instance of Log constructed from Apache commons-logging LogFactory. + * Used in testing to override the {@link Log} implementation with a mock. + * + * @return an instance of {@link Log} constructed from Apache commons-logging {@link LogFactory}. * @see org.apache.commons.logging.LogFactory#getLog(Class) + * @see org.apache.commons.logging.Log */ Log newLogger() { return LogFactory.getLog(getClass()); @@ -142,19 +147,22 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * GemFire cache events. * * @param applicationEventPublisher the Spring ApplicationEventPublisher used to - * publish Session-based events. + * publish Session-based events; must not be {@literal null}. + * @throws IllegalArgumentException if {@link ApplicationEventPublisher} is {@literal null}. * @see org.springframework.context.ApplicationEventPublisher */ public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + Assert.notNull(applicationEventPublisher, "ApplicationEventPublisher must not be null"); + this.applicationEventPublisher = applicationEventPublisher; } /** - * Gets the ApplicationEventPublisher used to publish Session events corresponding to - * GemFire cache events. + * Returns a reference to the {@link ApplicationEventPublisher} used to publish {@link Session} events + * corresponding to GemFire/Geode cache events. * - * @return the Spring ApplicationEventPublisher used to publish Session-based events. + * @return the Spring {@link ApplicationEventPublisher} used to publish {@link Session} events. * @see org.springframework.context.ApplicationEventPublisher */ protected ApplicationEventPublisher getApplicationEventPublisher() { @@ -162,45 +170,79 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi } /** - * Gets the fully-qualified name of the GemFire cache {@link Region} used to store and - * manage Session data. + * Returns the fully-qualified name of the cache {@link Region} used to store and manage {@link Session} state. * - * @return a String indicating the fully qualified name of the GemFire cache - * {@link Region} used to store and manage Session data. + * @return a {@link String} containing the fully qualified name of the cache {@link Region} + * used to store and manage {@link Session} data. */ protected String getFullyQualifiedRegionName() { return this.fullyQualifiedRegionName; } /** - * Sets the maximum interval in seconds in which a Session can remain inactive before - * it is considered expired. + * Return a reference to the {@link Log} used to log messages. * - * @param maxInactiveIntervalInSeconds an integer value specifying the maximum - * interval in seconds that a Session can remain inactive before it is considered - * expired. + * @return a reference to the {@link Log} used to log messages. + * @see org.apache.commons.logging.Log + */ + protected Log getLogger() { + return this.logger; + } + + /** + * Sets the {@link Duration maximum interval} in which a {@link Session} can remain inactive + * before the {@link Session} is considered expired. + * + * @param maxInactiveInterval {@link Duration} specifying the maximum interval that a {@link Session} + * can remain inactive before the {@link Session} is considered expired. + * @see java.time.Duration + */ + public void setMaxInactiveInterval(Duration maxInactiveInterval) { + this.maxInactiveInterval = maxInactiveInterval; + } + + /** + * Returns the {@link Duration maximum interval} in which a {@link Session} can remain inactive + * before the {@link Session} is considered expired. + * + * @return a {@link Duration} specifying the maximum interval that a {@link Session} can remain inactive + * before the {@link Session} is considered expired. + * @see java.time.Duration + */ + public Duration getMaxInactiveInterval() { + return this.maxInactiveInterval; + } + + /** + * Sets the maximum interval in seconds in which a {@link Session} can remain inactive + * before the {@link Session} is considered expired. + * + * @param maxInactiveIntervalInSeconds an integer value specifying the maximum interval in seconds + * that a {@link Session} can remain inactive before the {@link Session }is considered expired. + * @see #setMaxInactiveInterval(Duration) */ public void setMaxInactiveIntervalInSeconds(int maxInactiveIntervalInSeconds) { - this.maxInactiveIntervalInSeconds = maxInactiveIntervalInSeconds; + setMaxInactiveInterval(Duration.ofSeconds(maxInactiveIntervalInSeconds)); } /** - * Gets the maximum interval in seconds in which a Session can remain inactive before - * it is considered expired. + * Returns the maximum interval in seconds in which a {@link Session} can remain inactive + * before the {@link Session} is considered expired. * - * @return an integer value specifying the maximum interval in seconds that a Session - * can remain inactive before it is considered expired. + * @return an integer value specifying the maximum interval in seconds that a {@link Session} can remain inactive + * before the {@link Session} is considered expired. + * @see #getMaxInactiveInterval() */ public int getMaxInactiveIntervalInSeconds() { - return this.maxInactiveIntervalInSeconds; + return Optional.ofNullable(getMaxInactiveInterval()).map(Duration::getSeconds) + .map(Long::intValue).orElse(0); } /** - * Gets a reference to the GemfireOperations (template) used to perform data access - * operations and other interactions on the GemFire cache {@link Region} backing this - * SessionRepository. + * Gets a reference to the {@link GemfireOperations template} used to perform data access operations + * and other interactions on the cache {@link Region} backing this {@link SessionRepository}. * - * @return a reference to the GemfireOperations used to interact with GemFire. + * @return a reference to the {@link GemfireOperations template} used to interact with GemFire/Geode. * @see org.springframework.data.gemfire.GemfireOperations */ public GemfireOperations getTemplate() { @@ -209,12 +251,13 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /** * Callback method during Spring bean initialization that will capture the fully-qualified name - * of the GemFire cache {@link Region} used to manage Session state and register this SessionRepository - * as a GemFire {@link org.apache.geode.cache.CacheListener}. + * of the cache {@link Region} used to manage {@link Session} state and register this {@link SessionRepository} + * as a GemFire/Geode {@link org.apache.geode.cache.CacheListener}. * - * Additionally, this method registers GemFire {@link Instantiator}s for the {@link GemFireSession} - * and {@link GemFireSessionAttributes} types to optimize GemFire's instantiation logic on deserialization - * using the data serialization framework when accessing the {@link Session}'s state stored in GemFire. + * Additionally, this method registers GemFire/Geode {@link Instantiator Instantiators} + * for the {@link GemFireSession} and {@link GemFireSessionAttributes} types to optimize GemFire/Geode's + * instantiation logic on deserialization using the data serialization framework when accessing the stored + * {@link Session} state. * * @throws Exception if an error occurs during the initialization process. */ @@ -224,7 +267,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi Assert.isInstanceOf(GemfireAccessor.class, template); - Region region = ((GemfireAccessor) template).getRegion(); + Region region = ((GemfireAccessor) template).getRegion(); this.fullyQualifiedRegionName = region.getFullPath(); @@ -236,7 +279,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ boolean isCreate(EntryEvent event) { - return (isCreate(event.getOperation()) && isNotUpdate(event) && isExpiringSessionOrNull(event.getNewValue())); + return (isCreate(event.getOperation()) && isNotUpdate(event) && isSessionOrNull(event.getNewValue())); } /* (non-Javadoc) */ @@ -244,19 +287,6 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi return (operation.isCreate() && !Operation.LOCAL_LOAD_CREATE.equals(operation)); } - /** - * Used to determine whether the developer is storing (HTTP) Sessions with other, arbitrary application - * domain objects in the same GemFire cache {@link Region}; crazier things have happened! - * - * @param obj {@link Object} to evaluate. - * @return a boolean value indicating whether the {@link Object} from the entry event is indeed - * a {@link ExpiringSession}. - * @see org.springframework.session.ExpiringSession - */ - private boolean isExpiringSessionOrNull(Object obj) { - return (obj instanceof ExpiringSession || obj == null); - } - /* (non-Javadoc) */ private boolean isNotUpdate(EntryEvent event) { return (isNotProxyRegion() || !this.cachedSessionIds.contains(ObjectUtils.nullSafeHashCode(event.getKey()))); @@ -272,17 +302,31 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi return GemFireUtils.isProxy(((GemfireAccessor) getTemplate()).getRegion()); } + /** + * Used to determine whether the developer is storing (HTTP) Sessions with other, arbitrary application + * domain objects in the same GemFire cache {@link Region}; crazier things have happened! + * + * @param obj {@link Object} to evaluate. + * @return a boolean value indicating whether the {@link Object} from the entry event is indeed + * a {@link Session}. + * @see org.springframework.session.Session + */ + private boolean isSessionOrNull(Object obj) { + return (obj instanceof Session || obj == null); + } + boolean forget(Object sessionId) { return this.cachedSessionIds.remove(ObjectUtils.nullSafeHashCode(sessionId)); } + @SuppressWarnings("all") boolean remember(Object sessionId) { return (isProxyRegion() && this.cachedSessionIds.add(ObjectUtils.nullSafeHashCode(sessionId))); } /* (non-Javadoc) */ - ExpiringSession toExpiringSession(Object obj) { - return (obj instanceof ExpiringSession ? (ExpiringSession) obj : null); + Session toSession(Object obj) { + return (obj instanceof Session ? (Session) obj : null); } /** @@ -290,12 +334,12 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * * @param event {@link EntryEvent} containing the details of the cache {@link Region} operation. * @see org.apache.geode.cache.EntryEvent - * @see #handleCreated(String, ExpiringSession) + * @see #handleCreated(String, Session) */ @Override - public void afterCreate(EntryEvent event) { + public void afterCreate(EntryEvent event) { if (isCreate(event)) { - handleCreated(event.getKey().toString(), toExpiringSession(event.getNewValue())); + handleCreated(event.getKey().toString(), toSession(event.getNewValue())); } } @@ -305,11 +349,11 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * * @param event an EntryEvent containing the details of the cache operation. * @see org.apache.geode.cache.EntryEvent - * @see #handleDestroyed(String, ExpiringSession) + * @see #handleDestroyed(String, Session) */ @Override - public void afterDestroy(EntryEvent event) { - handleDestroyed(event.getKey().toString(), toExpiringSession(event.getOldValue())); + public void afterDestroy(EntryEvent event) { + handleDestroyed(event.getKey().toString(), toSession(event.getOldValue())); } /** @@ -318,11 +362,11 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * * @param event an EntryEvent containing the details of the cache operation. * @see org.apache.geode.cache.EntryEvent - * @see #handleExpired(String, ExpiringSession) + * @see #handleExpired(String, Session) */ @Override - public void afterInvalidate(EntryEvent event) { - handleExpired(event.getKey().toString(), toExpiringSession(event.getOldValue())); + public void afterInvalidate(EntryEvent event) { + handleExpired(event.getKey().toString(), toSession(event.getOldValue())); } /** @@ -330,11 +374,11 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * * @param session {@link Session} to delete. * @return {@literal null}. - * @see org.springframework.session.Session - * @see #delete(String) + * @see org.springframework.session.Session#getId() + * @see #deleteById(String) */ - protected ExpiringSession delete(Session session) { - delete(session.getId()); + protected Session delete(Session session) { + deleteById(session.getId()); return null; } @@ -344,15 +388,13 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * @param sessionId a String indicating the ID of the Session. * @param session a reference to the Session triggering the event. * @see org.springframework.session.events.SessionCreatedEvent - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session + * @see #newSessionCreatedEvent(Session, String) * @see #publishEvent(ApplicationEvent) */ - protected void handleCreated(String sessionId, ExpiringSession session) { - + protected void handleCreated(String sessionId, Session session) { remember(sessionId); - - publishEvent(session != null ? new SessionCreatedEvent(this, session) - : new SessionCreatedEvent(this, sessionId)); + publishEvent(newSessionCreatedEvent(session, sessionId)); } /** @@ -361,15 +403,14 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * @param sessionId a String indicating the ID of the Session. * @param session a reference to the Session triggering the event. * @see org.springframework.session.events.SessionDeletedEvent - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session + * @see #newSessionDeletedEvent(Session, String) * @see #publishEvent(ApplicationEvent) + * @see #forget(Object) */ - protected void handleDeleted(String sessionId, ExpiringSession session) { - + protected void handleDeleted(String sessionId, Session session) { forget(sessionId); - - publishEvent(session != null ? new SessionDeletedEvent(this, session) - : new SessionDeletedEvent(this, sessionId)); + publishEvent(newSessionDeletedEvent(session, sessionId)); } /** @@ -378,15 +419,14 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * @param sessionId a String indicating the ID of the Session. * @param session a reference to the Session triggering the event. * @see org.springframework.session.events.SessionDestroyedEvent - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session + * @see #newSessionDestroyedEvent(Session, String) * @see #publishEvent(ApplicationEvent) + * @see #forget(Object) */ - protected void handleDestroyed(String sessionId, ExpiringSession session) { - + protected void handleDestroyed(String sessionId, Session session) { forget(sessionId); - - publishEvent(session != null ? new SessionDestroyedEvent(this, session) - : new SessionDestroyedEvent(this, sessionId)); + publishEvent(newSessionDestroyedEvent(session, sessionId)); } /** @@ -395,14 +435,41 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * @param sessionId a String indicating the ID of the Session. * @param session a reference to the Session triggering the event. * @see org.springframework.session.events.SessionExpiredEvent - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session + * @see #newSessionExpiredEvent(Session, String) * @see #publishEvent(ApplicationEvent) + * @see #forget(Object) */ - protected void handleExpired(String sessionId, ExpiringSession session) { - + protected void handleExpired(String sessionId, Session session) { forget(sessionId); + publishEvent(newSessionExpiredEvent(session, sessionId)); + } - publishEvent(session != null ? new SessionExpiredEvent(this, session) + /* (non-Javadoc) */ + private SessionCreatedEvent newSessionCreatedEvent(Session session, String sessionId) { + + return (session != null ? new SessionCreatedEvent(this, session) + : new SessionCreatedEvent(this, sessionId)); + } + + /* (non-Javadoc) */ + private SessionDeletedEvent newSessionDeletedEvent(Session session, String sessionId) { + + return (session != null ? new SessionDeletedEvent(this, session) + : new SessionDeletedEvent(this, sessionId)); + } + + /* (non-Javadoc) */ + private SessionDestroyedEvent newSessionDestroyedEvent(Session session, String sessionId) { + + return (session != null ? new SessionDestroyedEvent(this, session) + : new SessionDestroyedEvent(this, sessionId)); + } + + /* (non-Javadoc) */ + private SessionExpiredEvent newSessionExpiredEvent(Session session, String sessionId) { + + return (session != null ? new SessionExpiredEvent(this, session) : new SessionExpiredEvent(this, sessionId)); } @@ -418,96 +485,116 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi getApplicationEventPublisher().publishEvent(event); } catch (Throwable t) { - this.logger.error(String.format("Error occurred publishing event [%s]", event), t); + getLogger().error(String.format("Error occurred publishing event [%s]", event), t); } } /** - * Updates the {@link ExpiringSession#setLastAccessedTime(long)} property of the {@link ExpiringSession}. + * Updates the {@link Session#setLastAccessedTime(Instant)} property of the {@link Session}. * - * @param {@link Class} sub-type of the {@link ExpiringSession}. - * @param expiringSession {@link ExpiringSession} to touch. - * @return the {@link ExpiringSession}. - * @see org.springframework.session.ExpiringSession#setLastAccessedTime(long) + * @param {@link Class} sub-type of the {@link Session}. + * @param session {@link Session} to touch. + * @return the {@link Session}. + * @see org.springframework.session.Session#setLastAccessedTime(Instant) */ - protected T touch(T expiringSession) { - expiringSession.setLastAccessedTime(System.currentTimeMillis()); - return expiringSession; + protected T touch(T session) { + + session.setLastAccessedTime(Instant.now()); + + return session; } /** - * GemFireSession is a GemFire representation model of a Spring {@link ExpiringSession} - * that stores and manages Session state information in GemFire. This class implements - * GemFire's {@link DataSerializable} interface to better handle replication of Session - * state information across the GemFire cluster. + * {@link GemFireSession} is a GemFire model for a Spring {@link Session} that stores and manages {@link Session} + * state in GemFire. This class implements GemFire's {@link DataSerializable} interface to better handle + * replication of {@link Session} state across the GemFire cluster. + * + * @see java.lang.Comparable + * @see org.apache.geode.DataSerializable + * @see org.apache.geode.Delta + * @see org.springframework.session.Session */ @SuppressWarnings("serial") - public static class GemFireSession - implements Comparable, DataSerializable, Delta, ExpiringSession { + public static class GemFireSession implements Comparable, DataSerializable, Delta, Session { protected static final boolean DEFAULT_ALLOW_JAVA_SERIALIZATION = true; - protected static final DateFormat TO_STRING_DATE_FORMAT = new SimpleDateFormat("YYYY-MM-dd-HH-mm-ss"); + private static final Duration DEFAULT_MAX_INACTIVE_INTERVAL = Duration.ZERO; protected static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; private transient boolean delta = false; - private int maxInactiveIntervalInSeconds; - - private long creationTime; - private long lastAccessedTime; + private Duration maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL; private transient final GemFireSessionAttributes sessionAttributes = new GemFireSessionAttributes(this); + private Instant creationTime; + private Instant lastAccessedTime; + private transient final SpelExpressionParser parser = new SpelExpressionParser(); private String id; /* (non-Javadoc) */ protected GemFireSession() { - this(UUID.randomUUID().toString()); + this(generateId()); } /* (non-Javadoc) */ protected GemFireSession(String id) { this.id = validateId(id); - this.creationTime = System.currentTimeMillis(); + this.creationTime = Instant.now(); this.lastAccessedTime = this.creationTime; } /* (non-Javadoc) */ - protected GemFireSession(ExpiringSession session) { + protected GemFireSession(Session session) { - Assert.notNull(session, "The ExpiringSession to copy cannot be null"); + Assert.notNull(session, "The Session to copy cannot be null"); this.id = session.getId(); this.creationTime = session.getCreationTime(); this.lastAccessedTime = session.getLastAccessedTime(); - this.maxInactiveIntervalInSeconds = session.getMaxInactiveIntervalInSeconds(); + this.maxInactiveInterval = session.getMaxInactiveInterval(); this.sessionAttributes.from(session); } /* (non-Javadoc) */ - public static GemFireSession create(int maxInactiveIntervalInSeconds) { - GemFireSession session = new GemFireSession(); - session.setMaxInactiveIntervalInSeconds(maxInactiveIntervalInSeconds); - return session; - } - - public static GemFireSession copy(ExpiringSession session) { + public static GemFireSession copy(Session session) { return new GemFireSession(session); } /* (non-Javadoc) */ - public static GemFireSession from(ExpiringSession session) { - return (session instanceof GemFireSession ? (GemFireSession) session : copy(session)); + public static GemFireSession create(Duration maxInactiveInterval) { + + GemFireSession session = new GemFireSession(); + + session.setMaxInactiveInterval(maxInactiveInterval); + + return session; } /* (non-Javadoc) */ - private String validateId(String id) { - Assert.hasText(id, "ID must be specified"); - return id; + public static GemFireSession from(Session session) { + return (session instanceof GemFireSession ? (GemFireSession) session : copy(session)); + } + + /** + * Randomly generates a unique identifier (ID) from {@link UUID} to be used as the {@link Session} ID. + * + * @return a new unique identifier (ID). + * @see java.util.UUID#randomUUID() + */ + private static String generateId() { + return UUID.randomUUID().toString(); + } + + /* (non-Javadoc) */ + private static String validateId(String id) { + + return Optional.ofNullable(id).filter(StringUtils::hasText) + .orElseThrow(() -> new IllegalArgumentException("ID is required")); } /* (non-Javadoc) */ @@ -515,13 +602,21 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi return DEFAULT_ALLOW_JAVA_SERIALIZATION; } + @Override + public synchronized String changeSessionId() { + + this.id = generateId(); + + return getId(); + } + /* (non-Javadoc) */ public synchronized String getId() { return this.id; } /* (non-Javadoc) */ - public synchronized long getCreationTime() { + public synchronized Instant getCreationTime() { return this.creationTime; } @@ -553,38 +648,44 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public synchronized boolean isExpired() { - long lastAccessedTime = getLastAccessedTime(); - long maxInactiveIntervalInSeconds = getMaxInactiveIntervalInSeconds(); + Instant lastAccessedTime = getLastAccessedTime(); - return (maxInactiveIntervalInSeconds >= 0 - && (idleTimeout(maxInactiveIntervalInSeconds) >= lastAccessedTime)); + Duration maxInactiveInterval = getMaxInactiveInterval(); + + return (isExpirationEnabled(maxInactiveInterval) + && Instant.now().minus(maxInactiveInterval).isAfter(lastAccessedTime)); } /* (non-Javadoc) */ - private long idleTimeout(long maxInactiveIntervalInSeconds) { - return (System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(maxInactiveIntervalInSeconds)); + private boolean isExpirationDisabled(Duration duration) { + return (duration == null || duration.isNegative() || duration.isZero()); } /* (non-Javadoc) */ - public synchronized void setLastAccessedTime(long lastAccessedTime) { - this.delta |= (this.lastAccessedTime != lastAccessedTime); + private boolean isExpirationEnabled(Duration duration) { + return !isExpirationDisabled(duration); + } + + /* (non-Javadoc) */ + public synchronized void setLastAccessedTime(Instant lastAccessedTime) { + this.delta |= !ObjectUtils.nullSafeEquals(this.lastAccessedTime, lastAccessedTime); this.lastAccessedTime = lastAccessedTime; } /* (non-Javadoc) */ - public synchronized long getLastAccessedTime() { + public synchronized Instant getLastAccessedTime() { return this.lastAccessedTime; } /* (non-Javadoc) */ - public synchronized void setMaxInactiveIntervalInSeconds(int maxInactiveIntervalInSeconds) { - this.delta |= (this.maxInactiveIntervalInSeconds != maxInactiveIntervalInSeconds); - this.maxInactiveIntervalInSeconds = maxInactiveIntervalInSeconds; + public synchronized void setMaxInactiveInterval(Duration maxInactiveIntervalInSeconds) { + this.delta |= !ObjectUtils.nullSafeEquals(this.maxInactiveInterval, maxInactiveIntervalInSeconds); + this.maxInactiveInterval = maxInactiveIntervalInSeconds; } /* (non-Javadoc) */ - public synchronized int getMaxInactiveIntervalInSeconds() { - return this.maxInactiveIntervalInSeconds; + public synchronized Duration getMaxInactiveInterval() { + return Optional.ofNullable(this.maxInactiveInterval).orElse(DEFAULT_MAX_INACTIVE_INTERVAL); } /* (non-Javadoc) */ @@ -598,10 +699,13 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi String principalName = getAttribute(PRINCIPAL_NAME_INDEX_NAME); if (principalName == null) { + Object authentication = getAttribute(SPRING_SECURITY_CONTEXT); if (authentication != null) { + Expression expression = this.parser.parseExpression("authentication?.name"); + principalName = expression.getValue(authentication, String.class); } } @@ -613,9 +717,9 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public synchronized void toData(DataOutput out) throws IOException { out.writeUTF(getId()); - out.writeLong(getCreationTime()); - out.writeLong(getLastAccessedTime()); - out.writeInt(getMaxInactiveIntervalInSeconds()); + out.writeLong(getCreationTime().toEpochMilli()); + out.writeLong(getLastAccessedTime().toEpochMilli()); + out.writeLong(getMaxInactiveInterval().getSeconds()); String principalName = getPrincipalName(); @@ -641,9 +745,9 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public synchronized void fromData(DataInput in) throws ClassNotFoundException, IOException { this.id = in.readUTF(); - this.creationTime = in.readLong(); - setLastAccessedTime(in.readLong()); - setMaxInactiveIntervalInSeconds(in.readInt()); + this.creationTime = Instant.ofEpochMilli(in.readLong()); + setLastAccessedTime(Instant.ofEpochMilli(in.readLong())); + setMaxInactiveInterval(Duration.ofSeconds(in.readLong())); int principalNameLength = in.readInt(); @@ -668,24 +772,24 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public synchronized void toDelta(DataOutput out) throws IOException { - out.writeLong(getLastAccessedTime()); - out.writeInt(getMaxInactiveIntervalInSeconds()); - this.sessionAttributes.toDelta(out); + out.writeLong(getLastAccessedTime().toEpochMilli()); + out.writeLong(getMaxInactiveInterval().getSeconds()); + getAttributes().toDelta(out); this.delta = false; } /* (non-Javadoc) */ public synchronized void fromDelta(DataInput in) throws IOException { - setLastAccessedTime(in.readLong()); - setMaxInactiveIntervalInSeconds(in.readInt()); - this.sessionAttributes.fromDelta(in); + setLastAccessedTime(Instant.ofEpochMilli(in.readLong())); + setMaxInactiveInterval(Duration.ofSeconds(in.readLong())); + getAttributes().fromDelta(in); this.delta = false; } /* (non-Javadoc) */ @SuppressWarnings("all") - public int compareTo(ExpiringSession session) { - return (Long.valueOf(getCreationTime()).compareTo(session.getCreationTime())); + public int compareTo(Session session) { + return getCreationTime().compareTo(session.getCreationTime()); } /* (non-Javadoc) */ @@ -721,14 +825,9 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public synchronized String toString() { return String.format("{ @type = %1$s, id = %2$s, creationTime = %3$s, lastAccessedTime = %4$s" - + ", maxInactiveIntervalInSeconds = %5$s, principalName = %6$s }", - getClass().getName(), getId(), toString(getCreationTime()), toString(getLastAccessedTime()), - getMaxInactiveIntervalInSeconds(), getPrincipalName()); - } - - /* (non-Javadoc) */ - private String toString(long timestamp) { - return TO_STRING_DATE_FORMAT.format(new Date(timestamp)); + + ", maxInactiveInterval = %5$s, principalName = %6$s }", + getClass().getName(), getId(), getCreationTime(), getLastAccessedTime(), + getMaxInactiveInterval(), getPrincipalName()); } } @@ -771,8 +870,8 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi protected static final boolean DEFAULT_ALLOW_JAVA_SERIALIZATION = true; - private transient final Map sessionAttributes = new HashMap(); - private transient final Map sessionAttributeDeltas = new HashMap(); + private transient final Map sessionAttributes = new HashMap<>(); + private transient final Map sessionAttributeDeltas = new HashMap<>(); private transient final Object lock; @@ -824,7 +923,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public Set getAttributeNames() { synchronized (this.lock) { - return Collections.unmodifiableSet(new HashSet(this.sessionAttributes.keySet())); + return Collections.unmodifiableSet(new HashSet<>(this.sessionAttributes.keySet())); } } @@ -839,6 +938,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public Set> entrySet() { return new AbstractSet>() { + @Override public Iterator> iterator() { return Collections.unmodifiableMap(GemFireSessionAttributes.this.sessionAttributes) @@ -856,9 +956,8 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public void from(Session session) { synchronized (this.lock) { - for (String attributeName : session.getAttributeNames()) { - setAttribute(attributeName, session.getAttribute(attributeName)); - } + session.getAttributeNames().forEach(attributeName -> + setAttribute(attributeName, session.getAttribute(attributeName))); } } @@ -866,9 +965,8 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public void from(GemFireSessionAttributes sessionAttributes) { synchronized (this.lock) { - for (String attributeName : sessionAttributes.getAttributeNames()) { - setAttribute(attributeName, sessionAttributes.getAttribute(attributeName)); - } + sessionAttributes.getAttributeNames().forEach(attributeName -> + setAttribute(attributeName, sessionAttributes.getAttribute(attributeName))); } } @@ -876,6 +974,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public void toData(DataOutput out) throws IOException { synchronized (this.lock) { + Set attributeNames = getAttributeNames(); out.writeInt(attributeNames.size()); @@ -896,6 +995,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public void fromData(DataInput in) throws IOException, ClassNotFoundException { synchronized (this.lock) { + for (int count = in.readInt(); count > 0; count--) { setAttribute(in.readUTF(), readObject(in)); } @@ -940,16 +1040,16 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi try { int count = in.readInt(); - Map deltas = new HashMap(count); + Map deltas = new HashMap<>(count); while (count-- > 0) { deltas.put(in.readUTF(), readObject(in)); } - for (Map.Entry entry : deltas.entrySet()) { - setAttribute(entry.getKey(), entry.getValue()); - this.sessionAttributeDeltas.remove(entry.getKey()); - } + deltas.forEach((key, value) -> { + setAttribute(key, value); + this.sessionAttributeDeltas.remove(key); + }); } catch (ClassNotFoundException e) { throw new InvalidDeltaException("class type in data not found", e); diff --git a/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepository.java b/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepository.java index 096a0c6..d91175a 100644 --- a/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepository.java +++ b/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepository.java @@ -16,13 +16,14 @@ package org.springframework.session.data.gemfire; +import java.time.Duration; import java.util.HashMap; import java.util.Map; import org.apache.geode.cache.query.SelectResults; import org.springframework.data.gemfire.GemfireOperations; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.SessionRepository; /** @@ -31,14 +32,15 @@ import org.springframework.session.SessionRepository; * * @author John Blum * @see org.springframework.data.gemfire.GemfireOperations - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session + * @see org.springframework.session.SessionRepository * @see org.springframework.session.data.gemfire.AbstractGemFireOperationsSessionRepository * @since 1.1.0 */ public class GemFireOperationsSessionRepository extends AbstractGemFireOperationsSessionRepository { // GemFire OQL query used to lookup Sessions by arbitrary attributes. - protected static final String FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY = + protected static final String FIND_SESSIONS_BY_INDEX_NAME_INDEX_VALUE_QUERY = "SELECT s FROM %1$s s WHERE s.attributes['%2$s'] = $1"; // GemFire OQL query used to look up Sessions by principal name. @@ -68,17 +70,17 @@ public class GemFireOperationsSessionRepository extends AbstractGemFireOperation * @param indexValue value of the indexed Session attribute to search on (e.g. * username). * @return a mapping of Session ID to Session instances. - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session * @see java.util.Map * @see #prepareQuery(String) */ - public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { + public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { - SelectResults results = getTemplate().find(prepareQuery(indexName), indexValue); + SelectResults results = getTemplate().find(prepareQuery(indexName), indexValue); - Map sessions = new HashMap(results.size()); + Map sessions = new HashMap<>(results.size()); - for (ExpiringSession session : results.asList()) { + for (Session session : results.asList()) { sessions.put(session.getId(), session); } @@ -97,34 +99,34 @@ public class GemFireOperationsSessionRepository extends AbstractGemFireOperation return (PRINCIPAL_NAME_INDEX_NAME.equals(indexName) ? String.format(FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY, getFullyQualifiedRegionName()) - : String.format(FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY, getFullyQualifiedRegionName(), indexName)); + : String.format(FIND_SESSIONS_BY_INDEX_NAME_INDEX_VALUE_QUERY, getFullyQualifiedRegionName(), indexName)); } /** - * Constructs a new {@link ExpiringSession} instance backed by GemFire. + * Constructs a new {@link Session} instance backed by GemFire. * - * @return an instance of {@link ExpiringSession} backed by GemFire. - * @see AbstractGemFireOperationsSessionRepository.GemFireSession#create(int) - * @see org.springframework.session.ExpiringSession + * @return an instance of {@link Session} backed by GemFire. + * @see AbstractGemFireOperationsSessionRepository.GemFireSession#create(Duration) + * @see org.springframework.session.Session * @see #getMaxInactiveIntervalInSeconds() */ - public ExpiringSession createSession() { - return GemFireSession.create(getMaxInactiveIntervalInSeconds()); + public Session createSession() { + return GemFireSession.create(getMaxInactiveInterval()); } /** - * Gets a copy of an existing, non-expired {@link ExpiringSession} by ID. If the + * Gets a copy of an existing, non-expired {@link Session} by ID. If the * Session is expired, then it is deleted. * * @param sessionId a String indicating the ID of the Session to get. - * @return an existing {@link ExpiringSession} by ID or null if not Session exists. - * @see AbstractGemFireOperationsSessionRepository.GemFireSession#from(ExpiringSession) - * @see org.springframework.session.ExpiringSession - * @see #delete(String) + * @return an existing {@link Session} by ID or null if not Session exists. + * @see AbstractGemFireOperationsSessionRepository.GemFireSession#from(Session) + * @see org.springframework.session.Session + * @see #deleteById(String) */ - public ExpiringSession getSession(String sessionId) { + public Session findById(String sessionId) { - ExpiringSession storedSession = getTemplate().get(sessionId); + Session storedSession = getTemplate().get(sessionId); if (storedSession != null) { storedSession = storedSession.isExpired() @@ -136,25 +138,25 @@ public class GemFireOperationsSessionRepository extends AbstractGemFireOperation } /** - * Saves the specified {@link ExpiringSession} to GemFire. + * Saves the specified {@link Session} to GemFire. * - * @param session the {@link ExpiringSession} to save. + * @param session the {@link Session} to save. * @see org.springframework.data.gemfire.GemfireOperations#put(Object, Object) - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session */ - public void save(ExpiringSession session) { + public void save(Session session) { getTemplate().put(session.getId(), GemFireSession.from(session)); } /** - * Deletes (removes) any existing {@link ExpiringSession} from GemFire. This operation + * Deletes (removes) any existing {@link Session} from GemFire. This operation * also results in a SessionDeletedEvent. * * @param sessionId a String indicating the ID of the Session to remove from GemFire. * @see org.springframework.data.gemfire.GemfireOperations#remove(Object) - * @see #handleDeleted(String, ExpiringSession) + * @see #handleDeleted(String, Session) */ - public void delete(String sessionId) { - handleDeleted(sessionId, getTemplate().remove(sessionId)); + public void deleteById(String sessionId) { + handleDeleted(sessionId, getTemplate().remove(sessionId)); } } diff --git a/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSession.java b/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSession.java index 557d2f5..7d06972 100644 --- a/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSession.java +++ b/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSession.java @@ -29,6 +29,7 @@ import org.apache.geode.cache.client.ClientRegionShortcut; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; +import org.springframework.session.Session; import org.springframework.session.web.http.SessionRepositoryFilter; /** @@ -149,11 +150,11 @@ public @interface EnableGemFireHttpSession { String[] indexableSessionAttributes() default {}; /** - * Defines the maximum interval in seconds that a Session can remain inactive before - * it is considered expired. Defaults to 1800 seconds, or 30 minutes. + * Defines the maximum interval in seconds that a {@link Session} can remain inactive + * before it is considered expired. Defaults to 1800 seconds, or 30 minutes. * - * @return an integer value defining the maximum inactive interval in seconds for - * declaring a Session expired. + * @return an integer value defining the maximum inactive interval in seconds + * declaring the {@link Session} expired. */ int maxInactiveIntervalInSeconds() default 1800; diff --git a/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.java b/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.java index cc466b9..a242fb8 100644 --- a/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.java +++ b/spring-session-data-geode/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.java @@ -42,7 +42,7 @@ import org.springframework.data.gemfire.IndexFactoryBean; import org.springframework.data.gemfire.IndexType; import org.springframework.data.gemfire.RegionAttributesFactoryBean; import org.springframework.data.gemfire.config.xml.GemfireConstants; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration; import org.springframework.session.data.gemfire.AbstractGemFireOperationsSessionRepository.GemFireSession; import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; @@ -53,8 +53,8 @@ import org.springframework.util.StringUtils; /** * The {@link GemFireHttpSessionConfiguration} class is a Spring {@link Configuration @Configuration} class - * used to configure and initialize Pivotal GemFire/Apache Geode as a clustered, replicated and distributed - * {@link javax.servlet.http.HttpSession} provider implementation in Spring {@link ExpiringSession}. + * used to configure and initialize Pivotal GemFire/Apache Geode as a clustered, distributed and replicated + * {@link javax.servlet.http.HttpSession} provider implementation in Spring {@link Session}. * * @author John Blum * @see org.apache.geode.cache.ExpirationAttributes @@ -67,14 +67,15 @@ import org.springframework.util.StringUtils; * @see org.springframework.beans.factory.BeanClassLoaderAware * @see org.springframework.context.annotation.Bean * @see org.springframework.context.annotation.Configuration + * @see org.springframework.context.annotation.DependsOn * @see org.springframework.context.annotation.ImportAware + * @see org.springframework.core.annotation.AnnotationAttributes * @see org.springframework.core.type.AnnotationMetadata * @see org.springframework.data.gemfire.GemfireOperations * @see org.springframework.data.gemfire.GemfireTemplate * @see org.springframework.data.gemfire.IndexFactoryBean - * @see org.springframework.data.gemfire.IndexType * @see org.springframework.data.gemfire.RegionAttributesFactoryBean - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session * @see org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration * @see org.springframework.session.data.gemfire.GemFireOperationsSessionRepository * @see org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession @@ -221,11 +222,11 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat } /** - * Gets the maximum interval in seconds in which a Session can remain inactive before - * it is considered expired. + * Gets the maximum interval in seconds in which a {@link Session} can remain inactive + * before it is considered expired. * - * @return an integer value specifying the maximum interval in seconds that a Session - * can remain inactive before it is considered expired. + * @return an integer value specifying the maximum interval in seconds that a {@link Session} can remain inactive + * before it is considered expired. * @see EnableGemFireHttpSession#maxInactiveIntervalInSeconds() */ protected int getMaxInactiveIntervalInSeconds() { @@ -251,10 +252,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see Pool#getName() */ protected String getPoolName() { - - return Optional.ofNullable(this.poolName) - .filter(StringUtils::hasText) - .orElse(DEFAULT_GEMFIRE_POOL_NAME); + return Optional.ofNullable(this.poolName).filter(StringUtils::hasText).orElse(DEFAULT_GEMFIRE_POOL_NAME); } /** @@ -300,9 +298,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see EnableGemFireHttpSession#regionName() */ protected String getSpringSessionGemFireRegionName() { - - return Optional.ofNullable(this.springSessionGemFireRegionName) - .filter(StringUtils::hasText) + return Optional.ofNullable(this.springSessionGemFireRegionName).filter(StringUtils::hasText) .orElse(DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); } @@ -319,22 +315,21 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat AnnotationAttributes.fromMap(importMetadata.getAnnotationAttributes( EnableGemFireHttpSession.class.getName())); - setClientRegionShortcut(ClientRegionShortcut.class.cast(enableGemFireHttpSessionAttributes - .getEnum("clientRegionShortcut"))); + setClientRegionShortcut(ClientRegionShortcut.class.cast( + enableGemFireHttpSessionAttributes.getEnum("clientRegionShortcut"))); - setIndexableSessionAttributes(enableGemFireHttpSessionAttributes - .getStringArray("indexableSessionAttributes")); + setIndexableSessionAttributes( + enableGemFireHttpSessionAttributes.getStringArray("indexableSessionAttributes")); - setMaxInactiveIntervalInSeconds(enableGemFireHttpSessionAttributes - .getNumber("maxInactiveIntervalInSeconds").intValue()); + setMaxInactiveIntervalInSeconds( + enableGemFireHttpSessionAttributes.getNumber("maxInactiveIntervalInSeconds").intValue()); setPoolName(enableGemFireHttpSessionAttributes.getString("poolName")); - setServerRegionShortcut(RegionShortcut.class.cast(enableGemFireHttpSessionAttributes - .getEnum("serverRegionShortcut"))); + setServerRegionShortcut(RegionShortcut.class.cast( + enableGemFireHttpSessionAttributes.getEnum("serverRegionShortcut"))); - setSpringSessionGemFireRegionName(enableGemFireHttpSessionAttributes - .getString("regionName")); + setSpringSessionGemFireRegionName(enableGemFireHttpSessionAttributes.getString("regionName")); } /** @@ -362,7 +357,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * Defines a Spring GemfireTemplate bean used to interact with GemFire's (Client)Cache * {@link Region} storing Sessions. * - * @param gemFireCache reference to the single GemFire cache instance used by the + * @param gemfireCache reference to the single GemFire cache instance used by the * {@link GemfireTemplate} to perform GemFire cache data access operations. * @return a {@link GemfireTemplate} used to interact with GemFire's (Client)Cache * {@link Region} storing Sessions. @@ -371,8 +366,8 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat */ @Bean @DependsOn(DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME) - public GemfireTemplate sessionRegionTemplate(GemFireCache gemFireCache) { - return new GemfireTemplate(gemFireCache.getRegion(getSpringSessionGemFireRegionName())); + public GemfireTemplate sessionRegionTemplate(GemFireCache gemfireCache) { + return new GemfireTemplate(gemfireCache.getRegion(getSpringSessionGemFireRegionName())); } /** @@ -391,11 +386,11 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see #getServerRegionShortcut() */ @Bean(name = DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME) - public GemFireCacheTypeAwareRegionFactoryBean sessionRegion(GemFireCache gemfireCache, - @Qualifier("sessionRegionAttributes") RegionAttributes sessionRegionAttributes) { + public GemFireCacheTypeAwareRegionFactoryBean sessionRegion(GemFireCache gemfireCache, + @Qualifier("sessionRegionAttributes") RegionAttributes sessionRegionAttributes) { - GemFireCacheTypeAwareRegionFactoryBean sessionRegion = - new GemFireCacheTypeAwareRegionFactoryBean(); + GemFireCacheTypeAwareRegionFactoryBean sessionRegion = + new GemFireCacheTypeAwareRegionFactoryBean<>(); sessionRegion.setClientRegionShortcut(getClientRegionShortcut()); sessionRegion.setGemfireCache(gemfireCache); @@ -432,8 +427,8 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat if (isExpirationAllowed(gemfireCache)) { regionAttributes.setStatisticsEnabled(true); - regionAttributes.setEntryIdleTimeout(new ExpirationAttributes( - Math.max(getMaxInactiveIntervalInSeconds(), 0), ExpirationAction.INVALIDATE)); + regionAttributes.setEntryIdleTimeout( + new ExpirationAttributes(Math.max(getMaxInactiveIntervalInSeconds(), 0), ExpirationAction.INVALIDATE)); } return regionAttributes; diff --git a/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepositoryTest.java b/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepositoryTest.java index 780ac08..5d4ac28 100644 --- a/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepositoryTest.java +++ b/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepositoryTest.java @@ -19,7 +19,6 @@ package org.springframework.session.data.gemfire; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -42,6 +41,8 @@ import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; @@ -71,7 +72,6 @@ import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.gemfire.GemfireOperations; import org.springframework.data.gemfire.GemfireTemplate; -import org.springframework.session.ExpiringSession; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.Session; import org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration; @@ -95,7 +95,7 @@ import org.apache.commons.logging.Log; * @see org.mockito.junit.MockitoJUnitRunner * @see org.mockito.Spy * @see org.springframework.data.gemfire.GemfireOperations - * @see org.springframework.session.ExpiringSession + * @see org.springframework.session.Session * @see org.springframework.session.Session * @see org.springframework.session.data.gemfire.AbstractGemFireOperationsSessionRepository * @see org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration @@ -111,14 +111,16 @@ public class AbstractGemFireOperationsSessionRepositoryTest { private AbstractGemFireOperationsSessionRepository sessionRepository; @Mock - private ExpiringSession mockExpiringSession; + private Session mockExpiringSession; @Mock private Log mockLog; @Before public void setup() { + this.sessionRepository = spy(new TestGemFireOperationsSessionRepository(new GemfireTemplate()) { + @Override Log newLogger() { return AbstractGemFireOperationsSessionRepositoryTest.this.mockLog; @@ -126,14 +128,18 @@ public class AbstractGemFireOperationsSessionRepositoryTest { }); } - protected static Set asSet(E... elements) { - Set set = new HashSet(elements.length); + private static Set asSet(E... elements) { + + Set set = new HashSet<>(elements.length); + Collections.addAll(set, elements); + return set; } @SuppressWarnings("unchecked") protected EntryEvent mockEntryEvent(Operation operation, K key, V oldValue, V newValue) { + EntryEvent mockEntryEvent = mock(EntryEvent.class); given(mockEntryEvent.getOperation()).willReturn(operation); @@ -146,7 +152,9 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @SuppressWarnings("unchecked") protected Region mockRegion(String name, DataPolicy dataPolicy) { + Region mockRegion = mock(Region.class, name); + RegionAttributes mockRegionAttributes = mock(RegionAttributes.class); given(mockRegion.getAttributes()).willReturn(mockRegionAttributes); @@ -155,22 +163,22 @@ public class AbstractGemFireOperationsSessionRepositoryTest { return mockRegion; } - protected ExpiringSession mockSession(String sessionId, long creationAndLastAccessedTime, - int maxInactiveIntervalInSeconds) { + protected Session mockSession(String sessionId, long creationAndLastAccessedTime, + long maxInactiveIntervalInSeconds) { return mockSession(sessionId, creationAndLastAccessedTime, creationAndLastAccessedTime, maxInactiveIntervalInSeconds); } - protected ExpiringSession mockSession(String sessionId, long creationTime, long lastAccessedTime, - int maxInactiveIntervalInSeconds) { + protected Session mockSession(String sessionId, long creationTime, long lastAccessedTime, + long maxInactiveIntervalInSeconds) { - ExpiringSession mockSession = mock(ExpiringSession.class, sessionId); + Session mockSession = mock(Session.class, sessionId); given(mockSession.getId()).willReturn(sessionId); - given(mockSession.getCreationTime()).willReturn(creationTime); - given(mockSession.getLastAccessedTime()).willReturn(lastAccessedTime); - given(mockSession.getMaxInactiveIntervalInSeconds()).willReturn(maxInactiveIntervalInSeconds); + given(mockSession.getCreationTime()).willReturn(Instant.ofEpochMilli(creationTime)); + given(mockSession.getLastAccessedTime()).willReturn(Instant.ofEpochMilli(lastAccessedTime)); + given(mockSession.getMaxInactiveInterval()).willReturn(Duration.ofSeconds(maxInactiveIntervalInSeconds)); return mockSession; } @@ -199,9 +207,12 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void gemfireOperationsSessionRepositoryIsProperlyConstructedAndInitialized() throws Exception { + ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - AttributesMutator mockAttributesMutator = mock(AttributesMutator.class); - Region mockRegion = mock(Region.class); + + AttributesMutator mockAttributesMutator = mock(AttributesMutator.class); + + Region mockRegion = mock(Region.class); given(mockRegion.getFullPath()).willReturn("/Example"); given(mockRegion.getAttributesMutator()).willReturn(mockAttributesMutator); @@ -235,6 +246,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void maxInactiveIntervalInSecondsAllowsNegativeValuesAndExtremelyLargeValues() { + assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()) .isEqualTo(GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS); @@ -257,9 +269,9 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void isCreateWithCreateOperationReturnsTrue() { - EntryEvent mockEvent = - this.mockEntryEvent(Operation.CREATE, "123", null, - this.mockExpiringSession); + + EntryEvent mockEvent = + this.mockEntryEvent(Operation.CREATE, "123", null, this.mockExpiringSession); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.EMPTY)); @@ -273,8 +285,9 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void isCreateWithCreateOperationAndNonProxyRegionReturnsTrue() { - EntryEvent mockEvent = - this.mockEntryEvent(Operation.CREATE, "123", null, null); + + EntryEvent mockEvent = + this.mockEntryEvent(Operation.CREATE, "123", null, null); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.NORMAL)); @@ -290,9 +303,9 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void isCreateWithLocalLoadCreateOperationReturnsFalse() { - EntryEvent mockEvent = - this.mockEntryEvent(Operation.LOCAL_LOAD_CREATE, "123", null, - this.mockExpiringSession); + + EntryEvent mockEvent = + this.mockEntryEvent(Operation.LOCAL_LOAD_CREATE, "123", null, this.mockExpiringSession); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.EMPTY)); @@ -306,9 +319,9 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void isCreateWithUpdateOperationReturnsFalse() { - EntryEvent mockEvent = - this.mockEntryEvent(Operation.UPDATE, "123", null, - this.mockExpiringSession); + + EntryEvent mockEvent = + this.mockEntryEvent(Operation.UPDATE, "123", null, this.mockExpiringSession); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.EMPTY)); @@ -322,9 +335,9 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void isCreateWithRememberedSessionIdReturnsFalse() { - EntryEvent mockEvent = - this.mockEntryEvent(Operation.CREATE, "123", null, - this.mockExpiringSession); + + EntryEvent mockEvent = + this.mockEntryEvent(Operation.CREATE, "123", null, this.mockExpiringSession); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.EMPTY)); @@ -340,9 +353,9 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void isCreateWithTombstoneReturnsFalse() { + EntryEvent mockEvent = - this.mockEntryEvent(Operation.CREATE, "123", null, - new Tombstone()); + this.mockEntryEvent(Operation.CREATE, "123", null, new Tombstone()); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.EMPTY)); @@ -357,32 +370,32 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void afterCreateWithSessionPublishesSessionCreatedEvent() { - final String sessionId = "abc123"; - final ExpiringSession mockSession = mock(ExpiringSession.class); + + String sessionId = "abc123"; + Session mockSession = mock(Session.class); given(mockSession.getId()).willReturn(sessionId); ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionCreatedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionCreatedEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isEqualTo(mockSession); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isEqualTo(mockSession); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - EntryEvent mockEntryEvent = - this.mockEntryEvent(Operation.CREATE, sessionId, null, mockSession); + EntryEvent mockEntryEvent = + this.mockEntryEvent(Operation.CREATE, sessionId, null, mockSession); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.EMPTY)); @@ -403,29 +416,29 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void afterCreateWithSessionIdPublishesSessionCreatedEvent() { - final String sessionId = "abc123"; + + String sessionId = "abc123"; ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionCreatedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionCreatedEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isNull(); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - EntryEvent mockEntryEvent = - this.mockEntryEvent(Operation.CREATE, sessionId, null, null); + EntryEvent mockEntryEvent = + this.mockEntryEvent(Operation.CREATE, sessionId, null, null); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.EMPTY)); @@ -449,13 +462,14 @@ public class AbstractGemFireOperationsSessionRepositoryTest { TestGemFireOperationsSessionRepository sessionRepository = new TestGemFireOperationsSessionRepository(new GemfireTemplate(mockRegion)) { + @Override - protected void handleCreated(String sessionId, ExpiringSession session) { + protected void handleCreated(String sessionId, Session session) { fail("handleCreated(..) should not have been called"); } }; - EntryEvent mockEntryEvent = + EntryEvent mockEntryEvent = mockEntryEvent(Operation.DESTROY, null, null, null); sessionRepository.afterCreate(mockEntryEvent); @@ -469,18 +483,20 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void afterCreateForModificationDoesNotPublishSessionCreatedEvent() { + Region mockRegion = mockRegion("Example", DataPolicy.EMPTY); TestGemFireOperationsSessionRepository sessionRepository = new TestGemFireOperationsSessionRepository(new GemfireTemplate(mockRegion)) { + @Override - protected void handleCreated(String sessionId, ExpiringSession session) { + protected void handleCreated(String sessionId, Session session) { fail("handleCreated(..) should not have been called"); } }; - EntryEvent mockEntryEvent = - this.mockEntryEvent(Operation.CREATE, "123", null, null); + EntryEvent mockEntryEvent = + this.mockEntryEvent(Operation.CREATE, "123", null, null); sessionRepository.remember("123"); sessionRepository.afterCreate(mockEntryEvent); @@ -494,19 +510,21 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void afterCreateForNonSessionTypeDoesNotPublishSessionCreatedEvent() { + Region mockRegion = mockRegion("Example", DataPolicy.EMPTY); TestGemFireOperationsSessionRepository sessionRepository = new TestGemFireOperationsSessionRepository(new GemfireTemplate(mockRegion)) { + @Override - protected void handleCreated(String sessionId, ExpiringSession session) { + protected void handleCreated(String sessionId, Session session) { fail("handleCreated(..) should not have been called"); } }; EntryEvent mockEntryEvent = mockEntryEvent(Operation.CREATE, null, null, new Tombstone()); - sessionRepository.afterCreate((EntryEvent) mockEntryEvent); + sessionRepository.afterCreate((EntryEvent) mockEntryEvent); verify(mockEntryEvent, times(1)).getOperation(); verify(mockEntryEvent, times(1)).getKey(); @@ -517,32 +535,33 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void afterDestroyWithSessionPublishesSessionDestroyedEvent() { - final String sessionId = "def456"; - final ExpiringSession mockSession = mock(ExpiringSession.class); + + String sessionId = "def456"; + + Session mockSession = mock(Session.class); given(mockSession.getId()).willReturn(sessionId); ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionDestroyedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionDestroyedEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isEqualTo(mockSession); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isEqualTo(mockSession); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - EntryEvent mockEntryEvent = - this.mockEntryEvent(Operation.DESTROY, sessionId, mockSession, null); + EntryEvent mockEntryEvent = + this.mockEntryEvent(Operation.DESTROY, sessionId, mockSession, null); this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); this.sessionRepository.afterDestroy(mockEntryEvent); @@ -560,29 +579,29 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void afterDestroyWithSessionIdPublishesSessionDestroyedEvent() { - final String sessionId = "def456"; + + String sessionId = "def456"; ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionDestroyedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionDestroyedEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isNull(); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - EntryEvent mockEntryEvent = - this.mockEntryEvent(Operation.DESTROY, sessionId, null, null); + EntryEvent mockEntryEvent = + this.mockEntryEvent(Operation.DESTROY, sessionId, null, null); this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); this.sessionRepository.afterDestroy(mockEntryEvent); @@ -599,31 +618,31 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void afterDestroyWithNonSessionTypePublishesSessionDestroyedEventWithSessionId() { - final String sessionId = "def456"; + + String sessionId = "def456"; ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionDestroyedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionDestroyedEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isNull(); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mockEntryEvent(Operation.DESTROY, sessionId, new Tombstone(), null); this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - this.sessionRepository.afterDestroy((EntryEvent) mockEntryEvent); + this.sessionRepository.afterDestroy((EntryEvent) mockEntryEvent); assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); @@ -637,32 +656,33 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void afterInvalidateWithSessionPublishesSessionExpiredEvent() { - final String sessionId = "ghi789"; - final ExpiringSession mockSession = mock(ExpiringSession.class); + + String sessionId = "ghi789"; + + Session mockSession = mock(Session.class); given(mockSession.getId()).willReturn(sessionId); ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionExpiredEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionExpiredEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isEqualTo(mockSession); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isEqualTo(mockSession); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - EntryEvent mockEntryEvent = - this.mockEntryEvent(Operation.INVALIDATE, sessionId, mockSession, null); + EntryEvent mockEntryEvent = + this.mockEntryEvent(Operation.INVALIDATE, sessionId, mockSession, null); this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); this.sessionRepository.afterInvalidate(mockEntryEvent); @@ -679,29 +699,29 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void afterInvalidateWithSessionIdPublishesSessionExpiredEvent() { - final String sessionId = "ghi789"; + + String sessionId = "ghi789"; ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionExpiredEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionExpiredEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isNull(); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - EntryEvent mockEntryEvent = - this.mockEntryEvent(Operation.INVALIDATE, sessionId, null, null); + EntryEvent mockEntryEvent = + this.mockEntryEvent(Operation.INVALIDATE, sessionId, null, null); this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); this.sessionRepository.afterInvalidate(mockEntryEvent); @@ -718,25 +738,25 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void afterInvalidateWithNonSessionTypePublishesSessionExpiredEventWithSessionId() { - final String sessionId = "ghi789"; + + String sessionId = "ghi789"; ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionExpiredEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionExpiredEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isNull(); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); @@ -745,7 +765,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { given(mockEntryEvent.getOldValue()).willReturn(new Tombstone()); this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - this.sessionRepository.afterInvalidate((EntryEvent) mockEntryEvent); + this.sessionRepository.afterInvalidate((EntryEvent) mockEntryEvent); assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); @@ -758,8 +778,10 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionCreateCreateExpireRecreatePublishesSessionEventsCreateExpireCreate() { - final String sessionId = "123456789"; - final ExpiringSession mockSession = mock(ExpiringSession.class); + + String sessionId = "123456789"; + + Session mockSession = mock(Session.class); given(mockSession.getId()).willReturn(sessionId); @@ -781,18 +803,18 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(sessionEvent.getSource()) .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isEqualTo(mockSession); + assertThat(sessionEvent.getSession()).isEqualTo(mockSession); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - EntryEvent mockCreateEvent = - this.mockEntryEvent(Operation.CREATE, sessionId, null, mockSession); + EntryEvent mockCreateEvent = + this.mockEntryEvent(Operation.CREATE, sessionId, null, mockSession); - EntryEvent mockExpireEvent = - this.mockEntryEvent(Operation.INVALIDATE, sessionId, mockSession, null); + EntryEvent mockExpireEvent = + this.mockEntryEvent(Operation.INVALIDATE, sessionId, mockSession, null); withRegion(this.sessionRepository, mockRegion("Example", DataPolicy.EMPTY)); @@ -821,40 +843,42 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void deleteSessionCallsDeleteSessionId() { + Session mockSession = mock(Session.class); - doNothing().when(this.sessionRepository).delete(anyString()); + doNothing().when(this.sessionRepository).deleteById(anyString()); given(mockSession.getId()).willReturn("2"); assertThat(this.sessionRepository.delete(mockSession)).isNull(); - verify(this.sessionRepository, times(1)).delete(eq("2")); + verify(this.sessionRepository, times(1)).deleteById(eq("2")); } @Test public void handleDeletedWithSessionPublishesSessionDeletedEvent() { - final String sessionId = "abc123"; - final ExpiringSession mockSession = mock(ExpiringSession.class); + + String sessionId = "abc123"; + + Session mockSession = mock(Session.class); given(mockSession.getId()).willReturn(sessionId); ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isEqualTo(mockSession); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isEqualTo(mockSession); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); @@ -869,25 +893,24 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void handleDeletedWithSessionIdPublishesSessionDeletedEvent() { - final String sessionId = "abc123"; + + String sessionId = "abc123"; ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - willAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); - assertThat(sessionEvent.getSource()) - .isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isNull(); - assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); + + return null; }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); @@ -895,8 +918,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); - verify(mockApplicationEventPublisher, times(1)) - .publishEvent(isA(SessionDeletedEvent.class)); + verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); } @Test @@ -921,39 +943,42 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void touchSetsLastAccessedTime() { - ExpiringSession mockSession = mock(ExpiringSession.class); + + Session mockSession = mock(Session.class); assertThat(this.sessionRepository.touch(mockSession)).isSameAs(mockSession); - verify(mockSession, times(1)).setLastAccessedTime(anyLong()); + verify(mockSession, times(1)).setLastAccessedTime(any(Instant.class)); } @Test public void constructGemFireSessionWithDefaultInitialization() { - long beforeOrAtCreationTime = System.currentTimeMillis(); + + Instant beforeOrAtCreationTime = Instant.now(); AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession(); assertThat(session.getId()).isNotNull(); - assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); - assertThat(session.getLastAccessedTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(0); + assertThat(session.getCreationTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); + assertThat(session.getLastAccessedTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ZERO); assertThat(session.getAttributeNames()).isNotNull(); assertThat(session.getAttributeNames()).isEmpty(); } @Test public void constructGemFireSessionWithId() { - long beforeOrAtCreationTime = System.currentTimeMillis(); + + Instant beforeOrAtCreationTime = Instant.now(); AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); assertThat(session.getId()).isEqualTo("1"); - assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); - assertThat(session.getLastAccessedTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(0); + assertThat(session.getCreationTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); + assertThat(session.getLastAccessedTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ZERO); assertThat(session.getAttributeNames()).isNotNull(); assertThat(session.getAttributeNames()).isEmpty(); } @@ -964,7 +989,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { new AbstractGemFireOperationsSessionRepository.GemFireSession(" "); } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessage("ID must be specified"); + assertThat(expected).hasMessage("ID is required"); assertThat(expected).hasNoCause(); throw expected; @@ -973,11 +998,14 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void constructGemFireSessionWithSession() { - long expectedCreationTime = 1L; - long expectedLastAccessTime = 2L; - ExpiringSession mockSession = - mockSession("2", expectedCreationTime, expectedLastAccessTime, MAX_INACTIVE_INTERVAL_IN_SECONDS); + Instant expectedCreationTime = Instant.ofEpochMilli(1L); + Instant expectedLastAccessTime = Instant.ofEpochMilli(2L); + + Duration expectedMaxInactiveInterval = Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); + + Session mockSession = mockSession("2", expectedCreationTime.toEpochMilli(), + expectedLastAccessTime.toEpochMilli(), MAX_INACTIVE_INTERVAL_IN_SECONDS); Set expectedAttributedNames = asSet("attrOne", "attrTwo"); @@ -991,7 +1019,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(gemfireSession.getId()).isEqualTo("2"); assertThat(gemfireSession.getCreationTime()).isEqualTo(expectedCreationTime); assertThat(gemfireSession.getLastAccessedTime()).isEqualTo(expectedLastAccessTime); - assertThat(gemfireSession.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); + assertThat(gemfireSession.getMaxInactiveInterval()).isEqualTo(expectedMaxInactiveInterval); assertThat(gemfireSession.getAttributeNames()).isEqualTo(expectedAttributedNames); assertThat(gemfireSession.getAttribute("attrOne")).isEqualTo("testOne"); assertThat(gemfireSession.getAttribute("attrTwo")).isEqualTo("testTwo"); @@ -999,7 +1027,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { verify(mockSession, times(1)).getId(); verify(mockSession, times(1)).getCreationTime(); verify(mockSession, times(1)).getLastAccessedTime(); - verify(mockSession, times(1)).getMaxInactiveIntervalInSeconds(); + verify(mockSession, times(1)).getMaxInactiveInterval(); verify(mockSession, times(1)).getAttributeNames(); verify(mockSession, times(1)).getAttribute(eq("attrOne")); verify(mockSession, times(1)).getAttribute(eq("attrTwo")); @@ -1008,10 +1036,10 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test(expected = IllegalArgumentException.class) public void constructGemFireSessionWithNullSession() { try { - new AbstractGemFireOperationsSessionRepository.GemFireSession((ExpiringSession) null); + new AbstractGemFireOperationsSessionRepository.GemFireSession((Session) null); } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessage("The ExpiringSession to copy cannot be null"); + assertThat(expected).hasMessage("The Session to copy cannot be null"); assertThat(expected).hasNoCause(); throw expected; @@ -1020,29 +1048,35 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void createNewGemFireSession() { - long beforeOrAtCreationTime = System.currentTimeMillis(); + + Instant beforeOrAtCreationTime = Instant.now(); + + Duration maxInactiveInterval = Duration.ofSeconds(120L); AbstractGemFireOperationsSessionRepository.GemFireSession session = - AbstractGemFireOperationsSessionRepository.GemFireSession.create(120); + AbstractGemFireOperationsSessionRepository.GemFireSession.create(maxInactiveInterval); assertThat(session).isNotNull(); assertThat(session.getId()).isNotNull(); - assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); + assertThat(session.getCreationTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); assertThat(session.getLastAccessedTime()).isEqualTo(session.getCreationTime()); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(120); + assertThat(session.getMaxInactiveInterval()).isEqualTo(maxInactiveInterval); assertThat(session.getAttributeNames()).isNotNull(); assertThat(session.getAttributeNames().isEmpty()).isTrue(); } @Test public void fromExistingSession() { - long expectedCreationTime = 1L; - long expectedLastAccessedTime = 2L; - ExpiringSession mockSession = mockSession("4", expectedCreationTime, expectedLastAccessedTime, - MAX_INACTIVE_INTERVAL_IN_SECONDS); + Instant expectedCreationTime = Instant.ofEpochMilli(1L); + Instant expectedLastAccessedTime = Instant.ofEpochMilli(2L); - given(mockSession.getAttributeNames()).willReturn(Collections.emptySet()); + Duration expectedMaxInactiveInterval = Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); + + Session mockSession = mockSession("4", expectedCreationTime.toEpochMilli(), + expectedLastAccessedTime.toEpochMilli(), MAX_INACTIVE_INTERVAL_IN_SECONDS); + + given(mockSession.getAttributeNames()).willReturn(Collections.emptySet()); AbstractGemFireOperationsSessionRepository.GemFireSession gemfireSession = AbstractGemFireOperationsSessionRepository.GemFireSession.from(mockSession); @@ -1051,22 +1085,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(gemfireSession.getId()).isEqualTo("4"); assertThat(gemfireSession.getCreationTime()).isEqualTo(expectedCreationTime); assertThat(gemfireSession.getLastAccessedTime()).isEqualTo(expectedLastAccessedTime); - assertThat(gemfireSession.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); + assertThat(gemfireSession.getMaxInactiveInterval()).isEqualTo(expectedMaxInactiveInterval); assertThat(gemfireSession.getAttributeNames()).isNotNull(); assertThat(gemfireSession.getAttributeNames().isEmpty()).isTrue(); verify(mockSession, times(1)).getId(); verify(mockSession, times(1)).getCreationTime(); verify(mockSession, times(1)).getLastAccessedTime(); - verify(mockSession, times(1)).getMaxInactiveIntervalInSeconds(); + verify(mockSession, times(1)).getMaxInactiveInterval(); verify(mockSession, times(1)).getAttributeNames(); verify(mockSession, never()).getAttribute(anyString()); } @Test public void fromExistingGemFireSessionIsGemFireSession() { + AbstractGemFireOperationsSessionRepository.GemFireSession gemfireSession = - AbstractGemFireOperationsSessionRepository.GemFireSession.create(300); + AbstractGemFireOperationsSessionRepository.GemFireSession.create(Duration.ofSeconds(300)); AbstractGemFireOperationsSessionRepository.GemFireSession fromGemFireSession = AbstractGemFireOperationsSessionRepository.GemFireSession.from(gemfireSession); @@ -1076,11 +1111,12 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void setGetAndRemoveAttribute() { + AbstractGemFireOperationsSessionRepository.GemFireSession session = - AbstractGemFireOperationsSessionRepository.GemFireSession.create(60); + AbstractGemFireOperationsSessionRepository.GemFireSession.create(Duration.ofSeconds(60)); assertThat(session).isNotNull(); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(60); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(60)); assertThat(session.getAttributeNames().isEmpty()).isTrue(); session.setAttribute("attrOne", "testOne"); @@ -1110,27 +1146,43 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void isExpiredIsFalseWhenMaxInactiveIntervalIsNegative() { - final int expectedMaxInactiveIntervalInSeconds = -1; + + Duration expectedMaxInactiveIntervalInSeconds = Duration.ofSeconds(-1); AbstractGemFireOperationsSessionRepository.GemFireSession session = AbstractGemFireOperationsSessionRepository.GemFireSession.create(expectedMaxInactiveIntervalInSeconds); assertThat(session).isNotNull(); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); + assertThat(session.getMaxInactiveInterval()).isEqualTo(expectedMaxInactiveIntervalInSeconds); + assertThat(session.isExpired()).isFalse(); + } + + @Test + public void isExpiredIsFalseWhenMaxInactiveIntervalIsZero() { + + Duration expectedMaxInactiveIntervalInSeconds = Duration.ZERO; + + AbstractGemFireOperationsSessionRepository.GemFireSession session = + AbstractGemFireOperationsSessionRepository.GemFireSession.create(expectedMaxInactiveIntervalInSeconds); + + assertThat(session).isNotNull(); + assertThat(session.getMaxInactiveInterval()).isEqualTo(expectedMaxInactiveIntervalInSeconds); assertThat(session.isExpired()).isFalse(); } @Test public void isExpiredIsFalseWhenSessionIsActive() { - final int expectedMaxInactiveIntervalInSeconds = (int) TimeUnit.HOURS.toSeconds(2); + + long expectedMaxInactiveIntervalInSeconds = TimeUnit.HOURS.toSeconds(2); AbstractGemFireOperationsSessionRepository.GemFireSession session = - AbstractGemFireOperationsSessionRepository.GemFireSession.create(expectedMaxInactiveIntervalInSeconds); + AbstractGemFireOperationsSessionRepository.GemFireSession.create( + Duration.ofSeconds(expectedMaxInactiveIntervalInSeconds)); assertThat(session).isNotNull(); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(expectedMaxInactiveIntervalInSeconds)); - final long now = System.currentTimeMillis(); + Instant now = Instant.now(); session.setLastAccessedTime(now); @@ -1140,15 +1192,17 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void isExpiredIsTrueWhenSessionIsInactive() { - final int expectedMaxInactiveIntervalInSeconds = 60; + + int expectedMaxInactiveIntervalInSeconds = 60; AbstractGemFireOperationsSessionRepository.GemFireSession session = - AbstractGemFireOperationsSessionRepository.GemFireSession.create(expectedMaxInactiveIntervalInSeconds); + AbstractGemFireOperationsSessionRepository.GemFireSession.create( + Duration.ofSeconds(expectedMaxInactiveIntervalInSeconds)); assertThat(session).isNotNull(); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(expectedMaxInactiveIntervalInSeconds)); - final long twoHoursAgo = (System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2)); + Instant twoHoursAgo = Instant.ofEpochMilli(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2)); session.setLastAccessedTime(twoHoursAgo); @@ -1158,8 +1212,9 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void setAndGetPrincipalName() { + AbstractGemFireOperationsSessionRepository.GemFireSession session = - AbstractGemFireOperationsSessionRepository.GemFireSession.create(0); + AbstractGemFireOperationsSessionRepository.GemFireSession.create(Duration.ZERO); assertThat(session).isNotNull(); assertThat(session.getPrincipalName()).isNull(); @@ -1167,17 +1222,13 @@ public class AbstractGemFireOperationsSessionRepositoryTest { session.setPrincipalName("jblum"); assertThat(session.getPrincipalName()).isEqualTo("jblum"); - assertThat(session.getAttributeNames()) - .isEqualTo(asSet(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)); - assertThat(session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)) - .isEqualTo("jblum"); + assertThat(session.getAttributeNames()).isEqualTo(asSet(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)); + assertThat(session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)).isEqualTo("jblum"); session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "rwinch"); - assertThat(session.getAttributeNames()) - .isEqualTo(asSet(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)); - assertThat(session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)) - .isEqualTo("rwinch"); + assertThat(session.getAttributeNames()).isEqualTo(asSet(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)); + assertThat(session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)).isEqualTo("rwinch"); assertThat(session.getPrincipalName()).isEqualTo("rwinch"); session.removeAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); @@ -1187,19 +1238,20 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionToData() throws Exception { + @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession("1") { + @Override void writeObject(Object obj, DataOutput out) throws IOException { - assertThat(obj) - .isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes.class); + assertThat(obj).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes.class); assertThat(out).isNotNull(); } }; - session.setLastAccessedTime(123L); - session.setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); + session.setLastAccessedTime(Instant.ofEpochMilli(123L)); + session.setMaxInactiveInterval(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS)); session.setPrincipalName("jblum"); DataOutput mockDataOutput = mock(DataOutput.class); @@ -1207,35 +1259,38 @@ public class AbstractGemFireOperationsSessionRepositoryTest { session.toData(mockDataOutput); verify(mockDataOutput, times(1)).writeUTF(eq("1")); - verify(mockDataOutput, times(1)).writeLong(eq(session.getCreationTime())); - verify(mockDataOutput, times(1)).writeLong(eq(session.getLastAccessedTime())); - verify(mockDataOutput, times(1)) - .writeInt(eq(session.getMaxInactiveIntervalInSeconds())); + verify(mockDataOutput, times(1)).writeLong(eq(session.getCreationTime().toEpochMilli())); + verify(mockDataOutput, times(1)).writeLong(eq(session.getLastAccessedTime().toEpochMilli())); + verify(mockDataOutput, times(1)).writeLong(eq(session.getMaxInactiveInterval().getSeconds())); verify(mockDataOutput, times(1)).writeInt(eq("jblum".length())); verify(mockDataOutput, times(1)).writeUTF(eq(session.getPrincipalName())); } @Test public void sessionFromData() throws Exception { + long expectedCreationTime = 1L; long expectedLastAccessedTime = 2L; + long expectedMaxInactiveIntervalInSeconds = TimeUnit.HOURS.toSeconds(6); - int expectedMaxInactiveIntervalInSeconds = (int) TimeUnit.HOURS.toSeconds(6); - - final String expectedPrincipalName = "jblum"; + String expectedPrincipalName = "jblum"; + String expectedSessionId = "2"; DataInput mockDataInput = mock(DataInput.class); - given(mockDataInput.readUTF()).willReturn("2").willReturn(expectedPrincipalName); - given(mockDataInput.readLong()).willReturn(expectedCreationTime).willReturn(expectedLastAccessedTime); - given(mockDataInput.readInt()).willReturn(expectedMaxInactiveIntervalInSeconds); + given(mockDataInput.readUTF()).willReturn(expectedSessionId).willReturn(expectedPrincipalName); + given(mockDataInput.readLong()).willReturn(expectedCreationTime).willReturn(expectedLastAccessedTime) + .willReturn(expectedMaxInactiveIntervalInSeconds); + given(mockDataInput.readInt()).willReturn(expectedPrincipalName.length()); @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession("1") { + @Override @SuppressWarnings("unchecked") T readObject(DataInput in) throws ClassNotFoundException, IOException { + assertThat(in).isNotNull(); AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = @@ -1253,44 +1308,44 @@ public class AbstractGemFireOperationsSessionRepositoryTest { Set expectedAttributeNames = asSet("attrOne", "attrTwo", FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); - assertThat(session.getId()).isEqualTo("2"); - assertThat(session.getCreationTime()).isEqualTo(expectedCreationTime); - assertThat(session.getLastAccessedTime()).isEqualTo(expectedLastAccessedTime); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); + assertThat(session.getId()).isEqualTo(expectedSessionId); + assertThat(session.getCreationTime()).isEqualTo(Instant.ofEpochMilli(expectedCreationTime)); + assertThat(session.getLastAccessedTime()).isEqualTo(Instant.ofEpochMilli(expectedLastAccessedTime)); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(expectedMaxInactiveIntervalInSeconds)); assertThat(session.getPrincipalName()).isEqualTo(expectedPrincipalName); - assertThat(session.getAttributeNames().size()).isEqualTo(3); - assertThat(session.getAttributeNames().containsAll(expectedAttributeNames)).isTrue(); + assertThat(session.getAttributeNames()).hasSize(3); + assertThat(session.getAttributeNames()).containsAll(expectedAttributeNames); assertThat(session.getAttribute("attrOne")).isEqualTo("testOne"); assertThat(session.getAttribute("attrTwo")).isEqualTo("testTwo"); assertThat(session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)) .isEqualTo(expectedPrincipalName); verify(mockDataInput, times(2)).readUTF(); - verify(mockDataInput, times(2)).readLong(); - verify(mockDataInput, times(2)).readInt(); + verify(mockDataInput, times(3)).readLong(); + verify(mockDataInput, times(1)).readInt(); } @Test public void sessionToDataThenFromDataWhenPrincipalNameIsNullGetsHandledProperly() throws ClassNotFoundException, IOException { - final long beforeOrAtCreationTime = System.currentTimeMillis(); + Instant beforeOrAtCreationTime = Instant.now(); @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSession expectedSession = new AbstractGemFireOperationsSessionRepository.GemFireSession("123") { + @Override void writeObject(Object obj, DataOutput out) throws IOException { - assertThat(obj) - .isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes.class); + assertThat(obj).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes.class); assertThat(out).isNotNull(); } }; assertThat(expectedSession.getId()).isEqualTo("123"); - assertThat(expectedSession.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); - assertThat(expectedSession.getLastAccessedTime()).isGreaterThanOrEqualTo(expectedSession.getCreationTime()); - assertThat(expectedSession.getMaxInactiveIntervalInSeconds()).isEqualTo(0); + assertThat(expectedSession.getCreationTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); + assertThat(expectedSession.getLastAccessedTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); + assertThat(expectedSession.getMaxInactiveInterval()).isEqualTo(Duration.ZERO); assertThat(expectedSession.getPrincipalName()).isNull(); ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); @@ -1312,8 +1367,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(deserializedSession).isEqualTo(expectedSession); assertThat(deserializedSession.getCreationTime()).isEqualTo(expectedSession.getCreationTime()); assertThat(deserializedSession.getLastAccessedTime()).isEqualTo(expectedSession.getLastAccessedTime()); - assertThat(deserializedSession.getMaxInactiveIntervalInSeconds()) - .isEqualTo(expectedSession.getMaxInactiveIntervalInSeconds()); + assertThat(deserializedSession.getMaxInactiveInterval()).isEqualTo(expectedSession.getMaxInactiveInterval()); assertThat(deserializedSession.getPrincipalName()).isNull(); } @@ -1324,6 +1378,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void hasDeltaWhenSessionAttributesChangeIsTrue() { + AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession(); @@ -1336,7 +1391,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void hasDeltaWhenSessionLastAccessedTimeIsUpdatedIsTrue() { - long expectedLastAccessTime = 1L; + + Instant expectedLastAccessTime = Instant.ofEpochMilli(1L); AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession(); @@ -1357,32 +1413,35 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void hasDeltaWhenSessionMaxInactiveIntervalInSecondsIsUpdatedIsTrue() { - int expectedMaxInactiveIntervalInSeconds = 300; + + Duration expectedMaxInactiveIntervalInSeconds = Duration.ofSeconds(300L); AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession(); - assertThat(session.getMaxInactiveIntervalInSeconds()).isNotEqualTo(expectedMaxInactiveIntervalInSeconds); + assertThat(session.getMaxInactiveInterval()).isNotEqualTo(expectedMaxInactiveIntervalInSeconds); assertThat(session.hasDelta()).isFalse(); - session.setMaxInactiveIntervalInSeconds(expectedMaxInactiveIntervalInSeconds); + session.setMaxInactiveInterval(expectedMaxInactiveIntervalInSeconds); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); + assertThat(session.getMaxInactiveInterval()).isEqualTo(expectedMaxInactiveIntervalInSeconds); assertThat(session.hasDelta()).isTrue(); - session.setMaxInactiveIntervalInSeconds(expectedMaxInactiveIntervalInSeconds); + session.setMaxInactiveInterval(expectedMaxInactiveIntervalInSeconds); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); + assertThat(session.getMaxInactiveInterval()).isEqualTo(expectedMaxInactiveIntervalInSeconds); assertThat(session.hasDelta()).isTrue(); } @Test public void sessionToDelta() throws Exception { - final DataOutput mockDataOutput = mock(DataOutput.class); + + DataOutput mockDataOutput = mock(DataOutput.class); @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession() { + @Override void writeObject(Object obj, DataOutput out) throws IOException { assertThat(String.valueOf(obj)).isEqualTo("test"); @@ -1390,8 +1449,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { } }; - session.setLastAccessedTime(1L); - session.setMaxInactiveIntervalInSeconds(300); + session.setLastAccessedTime(Instant.ofEpochMilli(1L)); + session.setMaxInactiveInterval(Duration.ofSeconds(300L)); session.setAttribute("attrOne", "test"); assertThat(session.hasDelta()).isTrue(); @@ -1401,21 +1460,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(session.hasDelta()).isFalse(); verify(mockDataOutput, times(1)).writeLong(eq(1L)); - verify(mockDataOutput, times(1)).writeInt(eq(300)); + verify(mockDataOutput, times(1)).writeLong(eq(300L)); verify(mockDataOutput, times(1)).writeInt(eq(1)); verify(mockDataOutput, times(1)).writeUTF(eq("attrOne")); } @Test public void sessionFromDelta() throws Exception { - final DataInput mockDataInput = mock(DataInput.class); - given(mockDataInput.readLong()).willReturn(1L); - given(mockDataInput.readInt()).willReturn(600).willReturn(0); + DataInput mockDataInput = mock(DataInput.class); + + given(mockDataInput.readLong()).willReturn(1L).willReturn(600L); + given(mockDataInput.readInt()).willReturn(0); @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession() { + @Override @SuppressWarnings("unchecked") T readObject(DataInput in) throws ClassNotFoundException, IOException { @@ -1427,28 +1488,29 @@ public class AbstractGemFireOperationsSessionRepositoryTest { session.fromDelta(mockDataInput); assertThat(session.hasDelta()).isFalse(); - assertThat(session.getLastAccessedTime()).isEqualTo(1L); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(600); + assertThat(session.getLastAccessedTime()).isEqualTo(Instant.ofEpochMilli(1L)); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(600L)); assertThat(session.getAttributeNames().isEmpty()).isTrue(); - verify(mockDataInput, times(1)).readLong(); - verify(mockDataInput, times(2)).readInt(); + verify(mockDataInput, times(2)).readLong(); + verify(mockDataInput, times(1)).readInt(); verify(mockDataInput, never()).readUTF(); } @Test public void sessionComparisons() { - long twoHoursAgo = (System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2)); + + Instant twoHoursAgo = Instant.now().minusMillis(TimeUnit.HOURS.toMillis(2)); AbstractGemFireOperationsSessionRepository.GemFireSession sessionOne = new AbstractGemFireOperationsSessionRepository.GemFireSession( - mockSession("1", twoHoursAgo, MAX_INACTIVE_INTERVAL_IN_SECONDS)); + mockSession("1", twoHoursAgo.toEpochMilli(), MAX_INACTIVE_INTERVAL_IN_SECONDS)); AbstractGemFireOperationsSessionRepository.GemFireSession sessionTwo = new AbstractGemFireOperationsSessionRepository.GemFireSession("2"); assertThat(sessionOne.getCreationTime()).isEqualTo(twoHoursAgo); - assertThat(sessionTwo.getCreationTime()).isGreaterThan(twoHoursAgo); + assertThat(sessionTwo.getCreationTime().isAfter(twoHoursAgo)).isTrue(); assertThat(sessionOne.compareTo(sessionTwo)).isLessThan(0); assertThat(sessionOne.compareTo(sessionOne)).isEqualTo(0); assertThat(sessionTwo.compareTo(sessionOne)).isGreaterThan(0); @@ -1456,30 +1518,31 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionEqualsDifferentSessionBasedOnId() { + AbstractGemFireOperationsSessionRepository.GemFireSession sessionOne = new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); - sessionOne.setLastAccessedTime(12345L); - sessionOne.setMaxInactiveIntervalInSeconds(120); + sessionOne.setLastAccessedTime(Instant.ofEpochSecond(12345L)); + sessionOne.setMaxInactiveInterval(Duration.ofSeconds(120L)); sessionOne.setPrincipalName("jblum"); AbstractGemFireOperationsSessionRepository.GemFireSession sessionTwo = new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); - sessionTwo.setLastAccessedTime(67890L); - sessionTwo.setMaxInactiveIntervalInSeconds(300); + sessionTwo.setLastAccessedTime(Instant.ofEpochSecond(67890L)); + sessionTwo.setMaxInactiveInterval(Duration.ofSeconds(300L)); sessionTwo.setPrincipalName("rwinch"); assertThat(sessionOne.getId().equals(sessionTwo.getId())).isTrue(); assertThat(sessionOne.getLastAccessedTime() == sessionTwo.getLastAccessedTime()).isFalse(); - assertThat(sessionOne.getMaxInactiveIntervalInSeconds() == sessionTwo.getMaxInactiveIntervalInSeconds()) - .isFalse(); + assertThat(sessionOne.getMaxInactiveInterval() == sessionTwo.getMaxInactiveInterval()).isFalse(); assertThat(sessionOne.getPrincipalName().equals(sessionTwo.getPrincipalName())).isFalse(); assertThat(sessionOne.equals(sessionTwo)).isTrue(); } @Test public void sessionHashCodeIsNotEqualToStringIdHashCode() { + AbstractGemFireOperationsSessionRepository.GemFireSession session = new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); @@ -1489,6 +1552,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesFromSession() { + Session mockSession = mock(Session.class); given(mockSession.getAttributeNames()).willReturn(asSet("attrOne", "attrTwo")); @@ -1514,6 +1578,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesFromSessionAttributes() { + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes source = new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); @@ -1535,11 +1600,13 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesToData() throws Exception { - final DataOutput mockDataOutput = mock(DataOutput.class); + + DataOutput mockDataOutput = mock(DataOutput.class); @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes() { + private int count = 0; @Override @@ -1561,7 +1628,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesFromData() throws Exception { - final DataInput mockDataInput = mock(DataInput.class); + + DataInput mockDataInput = mock(DataInput.class); given(mockDataInput.readInt()).willReturn(2); given(mockDataInput.readUTF()).willReturn("attrOne").willReturn("attrTwo"); @@ -1569,6 +1637,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes() { + private int count = 0; @Override @@ -1599,6 +1668,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesHasDeltaIsTrue() { + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); @@ -1612,17 +1682,18 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesToDelta() throws Exception { - final DataOutput mockDataOutput = mock(DataOutput.class); + + DataOutput mockDataOutput = mock(DataOutput.class); @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes() { + private int count = 0; @Override void writeObject(Object obj, DataOutput out) throws IOException { - assertThat(Arrays.asList("testOne", "testTwo", "testThree").get(count++)) - .isEqualTo(String.valueOf(obj)); + assertThat(Arrays.asList("testOne", "testTwo", "testThree").get(count++)).isEqualTo(String.valueOf(obj)); assertThat(out).isSameAs(mockDataOutput); } }; @@ -1663,7 +1734,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesFromDelta() throws Exception { - final DataInput mockDataInput = mock(DataInput.class); + + DataInput mockDataInput = mock(DataInput.class); given(mockDataInput.readInt()).willReturn(2); given(mockDataInput.readUTF()).willReturn("attrOne").willReturn("attrTwo"); @@ -1671,6 +1743,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @SuppressWarnings("serial") AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes() { + private int count = 0; @Override @@ -1728,6 +1801,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesEntrySetIteratesAttributeNameValues() { + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); @@ -1781,34 +1855,37 @@ public class AbstractGemFireOperationsSessionRepositoryTest { TestFramework.runOnce(new ThreadSafeSessionTest()); } + @SuppressWarnings("unused") protected static final class ThreadSafeSessionTest extends MultithreadedTestCase { - private final long beforeOrAtCreationTime = System.currentTimeMillis(); - private AbstractGemFireOperationsSessionRepository.GemFireSession session; - private volatile long expectedCreationTime; + private final Instant beforeOrAtCreationTime = Instant.now(); + + private volatile Instant expectedCreationTime; @Override public void initialize() { + this.session = new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); assertThat(this.session).isNotNull(); assertThat(this.session.getId()).isEqualTo("1"); - assertThat(this.session.getCreationTime()).isGreaterThanOrEqualTo(this.beforeOrAtCreationTime); + assertThat(this.session.getCreationTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); assertThat(this.session.getLastAccessedTime()).isEqualTo(this.session.getCreationTime()); - assertThat(this.session.getMaxInactiveIntervalInSeconds()).isEqualTo(0); + assertThat(this.session.getMaxInactiveInterval()).isEqualTo(Duration.ZERO); assertThat(this.session.getPrincipalName()).isNull(); - assertThat(this.session.getAttributeNames().isEmpty()).isTrue(); + assertThat(this.session.getAttributeNames()).isEmpty(); this.expectedCreationTime = this.session.getCreationTime(); - this.session.setLastAccessedTime(0L); - this.session.setMaxInactiveIntervalInSeconds(60); + this.session.setLastAccessedTime(Instant.MIN); + this.session.setMaxInactiveInterval(Duration.ofSeconds(60L)); this.session.setPrincipalName("jblum"); } public void thread1() { + assertTick(0); Thread.currentThread().setName("HTTP Request Processing Thread 1"); @@ -1816,17 +1893,16 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(this.session).isNotNull(); assertThat(this.session.getId()).isEqualTo("1"); assertThat(this.session.getCreationTime()).isEqualTo(this.expectedCreationTime); - assertThat(this.session.getLastAccessedTime()).isEqualTo(0L); - assertThat(this.session.getMaxInactiveIntervalInSeconds()).isEqualTo(60); + assertThat(this.session.getLastAccessedTime()).isEqualTo(Instant.MIN); + assertThat(this.session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(60L)); assertThat(this.session.getPrincipalName()).isEqualTo("jblum"); - assertThat(this.session.getAttributeNames().size()).isEqualTo(1); - assertThat(this.session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)) - .isEqualTo("jblum"); + assertThat(this.session.getAttributeNames()).hasSize(1); + assertThat(this.session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME)).isEqualTo("jblum"); this.session.setAttribute("tennis", "ping"); this.session.setAttribute("junk", "test"); - this.session.setLastAccessedTime(1L); - this.session.setMaxInactiveIntervalInSeconds(120); + this.session.setLastAccessedTime(Instant.ofEpochSecond(1L)); + this.session.setMaxInactiveInterval(Duration.ofSeconds(120L)); this.session.setPrincipalName("rwinch"); waitForTick(2); @@ -1834,11 +1910,11 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(this.session).isNotNull(); assertThat(this.session.getId()).isEqualTo("1"); assertThat(this.session.getCreationTime()).isEqualTo(this.expectedCreationTime); - assertThat(this.session.getLastAccessedTime()).isEqualTo(2L); - assertThat(this.session.getMaxInactiveIntervalInSeconds()).isEqualTo(180); - assertThat(this.session.getPrincipalName()).isEqualTo("ogierke"); - assertThat(this.session.getAttributeNames().size()).isEqualTo(3); - assertThat(this.session.getAttributeNames().containsAll(asSet("tennis", "greeting"))).isTrue(); + assertThat(this.session.getLastAccessedTime()).isEqualTo(Instant.ofEpochSecond(2L)); + assertThat(this.session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(180L)); + assertThat(this.session.getPrincipalName()).isEqualTo("rwinch"); + assertThat(this.session.getAttributeNames()).hasSize(3); + assertThat(this.session.getAttributeNames()).containsAll(asSet("tennis", "greeting")); assertThat(this.session.getAttributeNames().contains("junk")).isFalse(); assertThat(this.session.getAttribute("junk")).isNull(); assertThat(this.session.getAttribute("tennis")).isEqualTo("pong"); @@ -1846,6 +1922,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { } public void thread2() { + assertTick(0); Thread.currentThread().setName("HTTP Request Processing Thread 2"); @@ -1856,20 +1933,20 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(this.session).isNotNull(); assertThat(this.session.getId()).isEqualTo("1"); assertThat(this.session.getCreationTime()).isEqualTo(this.expectedCreationTime); - assertThat(this.session.getLastAccessedTime()).isEqualTo(1L); - assertThat(this.session.getMaxInactiveIntervalInSeconds()).isEqualTo(120); + assertThat(this.session.getLastAccessedTime()).isEqualTo(Instant.ofEpochSecond(1L)); + assertThat(this.session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(120L)); assertThat(this.session.getPrincipalName()).isEqualTo("rwinch"); - assertThat(this.session.getAttributeNames().size()).isEqualTo(3); - assertThat(this.session.getAttributeNames().containsAll(asSet("tennis", "junk"))).isTrue(); + assertThat(this.session.getAttributeNames()).hasSize(3); + assertThat(this.session.getAttributeNames()).containsAll(asSet("tennis", "junk")); assertThat(this.session.getAttribute("junk")).isEqualTo("test"); assertThat(this.session.getAttribute("tennis")).isEqualTo("ping"); this.session.setAttribute("tennis", "pong"); this.session.setAttribute("greeting", "hello"); this.session.removeAttribute("junk"); - this.session.setLastAccessedTime(2L); - this.session.setMaxInactiveIntervalInSeconds(180); - this.session.setPrincipalName("ogierke"); + this.session.setLastAccessedTime(Instant.ofEpochSecond(2L)); + this.session.setMaxInactiveInterval(Duration.ofSeconds(180L)); + this.session.setPrincipalName("rwinch"); } @Override @@ -1878,33 +1955,33 @@ public class AbstractGemFireOperationsSessionRepositoryTest { } } - static class Tombstone { - } - static class TestGemFireOperationsSessionRepository extends AbstractGemFireOperationsSessionRepository { TestGemFireOperationsSessionRepository(GemfireOperations gemfireOperations) { super(gemfireOperations); } - public ExpiringSession createSession() { + public Session createSession() { throw new UnsupportedOperationException("Not Implemented"); } - public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { + public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { throw new UnsupportedOperationException("Not Implemented"); } - public ExpiringSession getSession(String id) { + public Session findById(String id) { throw new UnsupportedOperationException("Not Implemented"); } - public void save(ExpiringSession session) { + public void save(Session session) { throw new UnsupportedOperationException("Not Implemented"); } - public void delete(String id) { + public void deleteById(String id) { throw new UnsupportedOperationException("Not Implemented"); } } + + static class Tombstone { + } } diff --git a/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryTest.java b/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryTest.java index b31ccf8..fa26511 100644 --- a/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryTest.java +++ b/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryTest.java @@ -28,6 +28,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import java.time.Duration; +import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.Map; @@ -38,9 +40,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; import org.apache.geode.cache.AttributesMutator; import org.apache.geode.cache.Region; @@ -50,14 +50,13 @@ import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.gemfire.GemfireAccessor; import org.springframework.data.gemfire.GemfireOperations; -import org.springframework.session.ExpiringSession; import org.springframework.session.FindByIndexNameSessionRepository; +import org.springframework.session.Session; import org.springframework.session.events.AbstractSessionEvent; import org.springframework.session.events.SessionDeletedEvent; /** - * The GemFireOperationsSessionRepositoryTest class is a test suite of test cases testing - * the contract and functionality of the GemFireOperationsSessionRepository class. + * Unit tests for {@link GemFireOperationsSessionRepository}. * * @author John Blum * @since 1.1.0 @@ -66,9 +65,13 @@ import org.springframework.session.events.SessionDeletedEvent; * @see org.mockito.Mock * @see org.mockito.Mockito * @see org.mockito.junit.MockitoJUnitRunner - * @see org.springframework.data.gemfire.GemfireOperations - * @see org.springframework.session.data.gemfire.GemFireOperationsSessionRepository * @see org.apache.geode.cache.Region + * @see org.springframework.data.gemfire.GemfireAccessor + * @see org.springframework.data.gemfire.GemfireOperations + * @see org.springframework.session.FindByIndexNameSessionRepository + * @see org.springframework.session.Session + * @see org.springframework.session.events.AbstractSessionEvent + * @see org.springframework.session.data.gemfire.GemFireOperationsSessionRepository */ @RunWith(MockitoJUnitRunner.class) public class GemFireOperationsSessionRepositoryTest { @@ -79,7 +82,7 @@ public class GemFireOperationsSessionRepositoryTest { private ApplicationEventPublisher mockApplicationEventPublisher; @Mock - private AttributesMutator mockAttributesMutator; + private AttributesMutator mockAttributesMutator; @Mock private GemfireOperationsAccessor mockTemplate; @@ -87,13 +90,14 @@ public class GemFireOperationsSessionRepositoryTest { private GemFireOperationsSessionRepository sessionRepository; @Mock - private Region mockRegion; + private Region mockRegion; @Before public void setup() throws Exception { + given(this.mockRegion.getAttributesMutator()).willReturn(this.mockAttributesMutator); given(this.mockRegion.getFullPath()).willReturn("/Example"); - given(this.mockTemplate.getRegion()).willReturn(this.mockRegion); + given(this.mockTemplate.getRegion()).willReturn(this.mockRegion); this.sessionRepository = new GemFireOperationsSessionRepository(this.mockTemplate); this.sessionRepository.setApplicationEventPublisher(this.mockApplicationEventPublisher); @@ -115,23 +119,24 @@ public class GemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void findByIndexNameValueFindsMatchingSession() { - ExpiringSession mockSession = mock(ExpiringSession.class, "MockSession"); + + Session mockSession = mock(Session.class, "MockSession"); given(mockSession.getId()).willReturn("1"); SelectResults mockSelectResults = mock(SelectResults.class); - given(mockSelectResults.asList()).willReturn(Collections.singletonList(mockSession)); + given(mockSelectResults.asList()).willReturn(Collections.singletonList(mockSession)); String indexName = "vip"; String indexValue = "rwinch"; - String expectedQql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY, + String expectedQql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_INDEX_VALUE_QUERY, this.sessionRepository.getFullyQualifiedRegionName(), indexName); given(this.mockTemplate.find(eq(expectedQql), eq(indexValue))).willReturn(mockSelectResults); - Map sessions = + Map sessions = this.sessionRepository.findByIndexNameAndIndexValue(indexName, indexValue); assertThat(sessions).isNotNull(); @@ -146,9 +151,10 @@ public class GemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void findByPrincipalNameFindsMatchingSessions() throws Exception { - ExpiringSession mockSessionOne = mock(ExpiringSession.class, "MockSessionOne"); - ExpiringSession mockSessionTwo = mock(ExpiringSession.class, "MockSessionTwo"); - ExpiringSession mockSessionThree = mock(ExpiringSession.class, "MockSessionThree"); + + Session mockSessionOne = mock(Session.class, "MockSessionOne"); + Session mockSessionTwo = mock(Session.class, "MockSessionTwo"); + Session mockSessionThree = mock(Session.class, "MockSessionThree"); given(mockSessionOne.getId()).willReturn("1"); given(mockSessionTwo.getId()).willReturn("2"); @@ -156,8 +162,7 @@ public class GemFireOperationsSessionRepositoryTest { SelectResults mockSelectResults = mock(SelectResults.class); - given(mockSelectResults.asList()) - .willReturn(Arrays.asList(mockSessionOne, mockSessionTwo, mockSessionThree)); + given(mockSelectResults.asList()).willReturn(Arrays.asList(mockSessionOne, mockSessionTwo, mockSessionThree)); String principalName = "jblum"; @@ -166,7 +171,7 @@ public class GemFireOperationsSessionRepositoryTest { given(this.mockTemplate.find(eq(expectedOql), eq(principalName))).willReturn(mockSelectResults); - Map sessions = this.sessionRepository.findByIndexNameAndIndexValue( + Map sessions = this.sessionRepository.findByIndexNameAndIndexValue( FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName); assertThat(sessions).isNotNull(); @@ -185,6 +190,7 @@ public class GemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings("unchecked") public void findByPrincipalNameReturnsNoMatchingSessions() { + SelectResults mockSelectResults = mock(SelectResults.class); given(mockSelectResults.asList()).willReturn(Collections.emptyList()); @@ -196,7 +202,7 @@ public class GemFireOperationsSessionRepositoryTest { given(this.mockTemplate.find(eq(expectedOql), eq(principalName))).willReturn(mockSelectResults); - Map sessions = this.sessionRepository.findByIndexNameAndIndexValue( + Map sessions = this.sessionRepository.findByIndexNameAndIndexValue( FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName); assertThat(sessions).isNotNull(); @@ -208,6 +214,7 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void prepareQueryReturnsPrincipalNameOql() { + String actualQql = this.sessionRepository.prepareQuery(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); @@ -219,9 +226,10 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void prepareQueryReturnsIndexNameValueOql() { + String attributeName = "testAttributeName"; String actualOql = this.sessionRepository.prepareQuery(attributeName); - String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY, + String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_INDEX_VALUE_QUERY, this.sessionRepository.getFullyQualifiedRegionName(), attributeName); assertThat(actualOql).isEqualTo(expectedOql); @@ -229,47 +237,48 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void createProperlyInitializedSession() { - long beforeOrAtCreationTime = System.currentTimeMillis(); - ExpiringSession session = this.sessionRepository.createSession(); + Instant beforeOrAtCreationTime = Instant.now(); + + Session session = this.sessionRepository.createSession(); assertThat(session).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class); assertThat(session.getId()).isNotNull(); - assertThat(session.getAttributeNames().isEmpty()).isTrue(); - assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); - assertThat(session.getLastAccessedTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); + assertThat(session.getAttributeNames()).isEmpty(); + assertThat(session.getCreationTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); + assertThat(session.getLastAccessedTime().compareTo(beforeOrAtCreationTime)).isGreaterThanOrEqualTo(0); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS)); } @Test public void getSessionDeletesMatchingExpiredSessionById() { - final String expectedSessionId = "1"; - final ExpiringSession mockSession = mock(ExpiringSession.class); + String expectedSessionId = "1"; + + Session mockSession = mock(Session.class); given(mockSession.isExpired()).willReturn(true); given(mockSession.getId()).willReturn(expectedSessionId); given(this.mockTemplate.get(eq(expectedSessionId))).willReturn(mockSession); given(this.mockTemplate.remove(eq(expectedSessionId))).willReturn(mockSession); - willAnswer(new Answer() { - public Void answer(final InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); - assertThat(sessionEvent.getSource()) - .isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isSameAs(mockSession); - assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()) + .isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isSameAs(mockSession); + assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); + + return null; }).given(this.mockApplicationEventPublisher).publishEvent(any(ApplicationEvent.class)); - assertThat(this.sessionRepository.getSession(expectedSessionId)).isNull(); + assertThat(this.sessionRepository.findById(expectedSessionId)).isNull(); verify(this.mockTemplate, times(1)).get(eq(expectedSessionId)); verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId)); @@ -281,12 +290,13 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void getSessionFindsMatchingNonExpiredSessionById() { + String expectedId = "1"; - long expectedCreationTime = System.currentTimeMillis(); - long currentLastAccessedTime = (expectedCreationTime + TimeUnit.MINUTES.toMillis(5)); + Instant expectedCreationTime = Instant.now(); + Instant currentLastAccessedTime = expectedCreationTime.plusMillis(TimeUnit.MINUTES.toMillis(5)); - ExpiringSession mockSession = mock(ExpiringSession.class); + Session mockSession = mock(Session.class); given(mockSession.isExpired()).willReturn(false); given(mockSession.getId()).willReturn(expectedId); @@ -296,13 +306,13 @@ public class GemFireOperationsSessionRepositoryTest { given(mockSession.getAttribute(eq("attrOne"))).willReturn("test"); given(this.mockTemplate.get(eq(expectedId))).willReturn(mockSession); - ExpiringSession actualSession = this.sessionRepository.getSession(expectedId); + Session actualSession = this.sessionRepository.findById(expectedId); assertThat(actualSession).isNotSameAs(mockSession); assertThat(actualSession.getId()).isEqualTo(expectedId); assertThat(actualSession.getCreationTime()).isEqualTo(expectedCreationTime); assertThat(actualSession.getLastAccessedTime()).isNotEqualTo(currentLastAccessedTime); - assertThat(actualSession.getLastAccessedTime()).isGreaterThanOrEqualTo(expectedCreationTime); + assertThat(actualSession.getLastAccessedTime().compareTo(expectedCreationTime)).isGreaterThanOrEqualTo(0); assertThat(actualSession.getAttributeNames()).isEqualTo(Collections.singleton("attrOne")); assertThat(String.valueOf(actualSession.getAttribute("attrOne"))).isEqualTo("test"); @@ -318,49 +328,48 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void getSessionReturnsNull() { given(this.mockTemplate.get(anyString())).willReturn(null); - assertThat(this.sessionRepository.getSession("1")).isNull(); + assertThat(this.sessionRepository.findById("1")).isNull(); } @Test public void saveStoresSession() { - final String expectedSessionId = "1"; - final long expectedCreationTime = System.currentTimeMillis(); - final long expectedLastAccessTime = (expectedCreationTime + TimeUnit.MINUTES.toMillis(5)); + String expectedSessionId = "1"; - ExpiringSession mockSession = mock(ExpiringSession.class); + Instant expectedCreationTime = Instant.now(); + Instant expectedLastAccessTime = expectedCreationTime.plusMillis(TimeUnit.MINUTES.toMillis(5L)); + + Duration expectedMaxInactiveInterval = Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); + + Session mockSession = mock(Session.class); given(mockSession.getId()).willReturn(expectedSessionId); given(mockSession.getCreationTime()).willReturn(expectedCreationTime); given(mockSession.getLastAccessedTime()).willReturn(expectedLastAccessTime); - given(mockSession.getMaxInactiveIntervalInSeconds()) - .willReturn(MAX_INACTIVE_INTERVAL_IN_SECONDS); - given(mockSession.getAttributeNames()).willReturn(Collections.emptySet()); + given(mockSession.getMaxInactiveInterval()).willReturn(expectedMaxInactiveInterval); + given(mockSession.getAttributeNames()).willReturn(Collections.emptySet()); given(this.mockTemplate.put(eq(expectedSessionId), - isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class))) - .willAnswer(new Answer() { - public ExpiringSession answer(InvocationOnMock invocation) throws Throwable { - ExpiringSession session = invocation.getArgument(1); + isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class))).willAnswer(invocation -> { - assertThat(session).isNotNull(); - assertThat(session.getId()).isEqualTo(expectedSessionId); - assertThat(session.getCreationTime()).isEqualTo(expectedCreationTime); - assertThat(session.getLastAccessedTime()).isEqualTo(expectedLastAccessTime); - assertThat(session.getMaxInactiveIntervalInSeconds()) - .isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); - assertThat(session.getAttributeNames().isEmpty()).isTrue(); + Session session = invocation.getArgument(1); - return null; - } - }); + assertThat(session).isNotNull(); + assertThat(session.getId()).isEqualTo(expectedSessionId); + assertThat(session.getCreationTime()).isEqualTo(expectedCreationTime); + assertThat(session.getLastAccessedTime()).isEqualTo(expectedLastAccessTime); + assertThat(session.getMaxInactiveInterval()).isEqualTo(expectedMaxInactiveInterval); + assertThat(session.getAttributeNames().isEmpty()).isTrue(); + + return null; + }); this.sessionRepository.save(mockSession); verify(mockSession, times(2)).getId(); verify(mockSession, times(1)).getCreationTime(); verify(mockSession, times(1)).getLastAccessedTime(); - verify(mockSession, times(1)).getMaxInactiveIntervalInSeconds(); + verify(mockSession, times(1)).getMaxInactiveInterval(); verify(mockSession, times(1)).getAttributeNames(); verify(this.mockTemplate, times(1)).put(eq(expectedSessionId), isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class)); @@ -368,31 +377,30 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void deleteRemovesExistingSessionAndHandlesDelete() { - final String expectedSessionId = "1"; - final ExpiringSession mockSession = mock(ExpiringSession.class); + String expectedSessionId = "1"; + + Session mockSession = mock(Session.class); given(mockSession.getId()).willReturn(expectedSessionId); given(this.mockTemplate.remove(eq(expectedSessionId))).willReturn(mockSession); - willAnswer(new Answer() { - public Void answer(final InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); - assertThat(sessionEvent.getSource()) - .isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isSameAs(mockSession); - assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isSameAs(mockSession); + assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); + + return null; }).given(this.mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class)); - this.sessionRepository.delete(expectedSessionId); + this.sessionRepository.deleteById(expectedSessionId); verify(mockSession, times(1)).getId(); verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId)); @@ -402,28 +410,27 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void deleteRemovesNonExistingSessionAndHandlesDelete() { - final String expectedSessionId = "1"; + + String expectedSessionId = "1"; given(this.mockTemplate.remove(anyString())).willReturn(null); - willAnswer(new Answer() { - public Void answer(final InvocationOnMock invocation) throws Throwable { - ApplicationEvent applicationEvent = invocation.getArgument(0); + willAnswer(invocation -> { - assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); + ApplicationEvent applicationEvent = invocation.getArgument(0); - AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; + assertThat(applicationEvent).isInstanceOf(SessionDeletedEvent.class); - assertThat(sessionEvent.getSource()). - isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); - assertThat(sessionEvent.getSession()).isNull(); - assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); + AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - return null; - } + assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); + assertThat(sessionEvent.getSession()).isNull(); + assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); + + return null; }).given(this.mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class)); - this.sessionRepository.delete(expectedSessionId); + this.sessionRepository.deleteById(expectedSessionId); verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId)); verify(this.mockApplicationEventPublisher, times(1)) diff --git a/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfigurationTest.java b/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfigurationTest.java index c8a4c71..77aee9f 100644 --- a/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfigurationTest.java +++ b/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfigurationTest.java @@ -45,7 +45,7 @@ import org.springframework.core.type.AnnotationMetadata; import org.springframework.data.gemfire.GemfireOperations; import org.springframework.data.gemfire.GemfireTemplate; import org.springframework.data.gemfire.RegionAttributesFactoryBean; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; import org.springframework.session.data.gemfire.config.annotation.web.http.support.GemFireCacheTypeAwareRegionFactoryBean; @@ -87,7 +87,8 @@ public class GemFireHttpSessionConfigurationTest { } } - protected T[] toArray(T... array) { + @SafeVarargs + private static T[] toArray(T... array) { return array; } @@ -97,7 +98,9 @@ public class GemFireHttpSessionConfigurationTest { } @Test + @SuppressWarnings("all") public void setAndGetBeanClassLoader() { + assertThat(this.gemfireConfiguration.getBeanClassLoader()).isNull(); this.gemfireConfiguration.setBeanClassLoader(Thread.currentThread().getContextClassLoader()); @@ -112,6 +115,7 @@ public class GemFireHttpSessionConfigurationTest { @Test public void setAndGetClientRegionShortcut() { + assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT); @@ -128,6 +132,7 @@ public class GemFireHttpSessionConfigurationTest { @Test public void setAndGetMaxInactiveIntervalInSeconds() { + assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS); @@ -150,6 +155,7 @@ public class GemFireHttpSessionConfigurationTest { @Test public void setAndGetPoolName() { + assertThat(this.gemfireConfiguration.getPoolName()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_GEMFIRE_POOL_NAME); @@ -175,6 +181,7 @@ public class GemFireHttpSessionConfigurationTest { @Test public void setAndGetServerRegionShortcut() { + assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT); @@ -191,6 +198,7 @@ public class GemFireHttpSessionConfigurationTest { @Test public void setAndGetSpringSessionGemFireRegionName() { + assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); @@ -216,9 +224,10 @@ public class GemFireHttpSessionConfigurationTest { @Test public void setsImportMetadata() { + AnnotationMetadata mockAnnotationMetadata = mock(AnnotationMetadata.class); - Map annotationAttributes = new HashMap(4); + Map annotationAttributes = new HashMap<>(4); annotationAttributes.put("clientRegionShortcut", ClientRegionShortcut.CACHING_PROXY); annotationAttributes.put("indexableSessionAttributes", toArray("one", "two", "three")); @@ -244,6 +253,7 @@ public class GemFireHttpSessionConfigurationTest { @Test public void createsAndInitializesSessionRepositoryBean() { + GemfireOperations mockGemfireOperations = mock(GemfireOperations.class); this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(120); @@ -259,7 +269,9 @@ public class GemFireHttpSessionConfigurationTest { @Test @SuppressWarnings("unchecked") public void createsAndInitializesSessionRegionTemplateBean() { + GemFireCache mockGemFireCache = mock(GemFireCache.class); + Region mockRegion = mock(Region.class); given(mockGemFireCache.getRegion(eq("Example"))).willReturn(mockRegion); @@ -278,15 +290,17 @@ public class GemFireHttpSessionConfigurationTest { @Test @SuppressWarnings("unchecked") public void createsAndInitializesSessionRegionBean() { + GemFireCache mockGemFireCache = mock(GemFireCache.class); - RegionAttributes mockRegionAttributes = mock(RegionAttributes.class); + + RegionAttributes mockRegionAttributes = mock(RegionAttributes.class); this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY); this.gemfireConfiguration.setPoolName("TestPool"); this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PERSISTENT); this.gemfireConfiguration.setSpringSessionGemFireRegionName("TestRegion"); - GemFireCacheTypeAwareRegionFactoryBean sessionRegionFactoryBean = + GemFireCacheTypeAwareRegionFactoryBean sessionRegionFactoryBean = this.gemfireConfiguration.sessionRegion(mockGemFireCache, mockRegionAttributes); assertThat(sessionRegionFactoryBean).isNotNull(); @@ -295,7 +309,7 @@ public class GemFireHttpSessionConfigurationTest { assertThat(this.getField(sessionRegionFactoryBean, "gemfireCache")) .isEqualTo(mockGemFireCache); assertThat(this.getField(sessionRegionFactoryBean, "poolName")).isEqualTo("TestPool"); - assertThat(this.>getField(sessionRegionFactoryBean, + assertThat(this.>getField(sessionRegionFactoryBean, "regionAttributes")).isEqualTo(mockRegionAttributes); assertThat(this.getField(sessionRegionFactoryBean, "regionName")).isEqualTo("TestRegion"); assertThat(this.getField(sessionRegionFactoryBean, "serverRegionShortcut")) @@ -308,6 +322,7 @@ public class GemFireHttpSessionConfigurationTest { @Test @SuppressWarnings("unchecked") public void createsAndInitializesSessionRegionAttributesWithExpiration() throws Exception { + Cache mockCache = mock(Cache.class); this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(300); @@ -320,7 +335,7 @@ public class GemFireHttpSessionConfigurationTest { regionAttributesFactory.afterPropertiesSet(); - RegionAttributes sessionRegionAttributes = regionAttributesFactory.getObject(); + RegionAttributes sessionRegionAttributes = regionAttributesFactory.getObject(); assertThat(sessionRegionAttributes).isNotNull(); assertThat(sessionRegionAttributes.getKeyConstraint()).isEqualTo( @@ -338,6 +353,7 @@ public class GemFireHttpSessionConfigurationTest { @Test @SuppressWarnings("unchecked") public void createsAndInitializesSessionRegionAttributesWithoutExpiration() throws Exception { + ClientCache mockClientCache = mock(ClientCache.class); this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(300); @@ -349,7 +365,7 @@ public class GemFireHttpSessionConfigurationTest { regionAttributesFactory.afterPropertiesSet(); - RegionAttributes sessionRegionAttributes = regionAttributesFactory.getObject(); + RegionAttributes sessionRegionAttributes = regionAttributesFactory.getObject(); assertThat(sessionRegionAttributes).isNotNull(); assertThat(sessionRegionAttributes.getKeyConstraint()).isEqualTo( @@ -366,6 +382,7 @@ public class GemFireHttpSessionConfigurationTest { @Test public void expirationIsAllowed() { + Cache mockCache = mock(Cache.class); ClientCache mockClientCache = mock(ClientCache.class); @@ -392,7 +409,9 @@ public class GemFireHttpSessionConfigurationTest { @Test public void expirationIsNotAllowed() { + Cache mockCache = mock(Cache.class); + ClientCache mockClientCache = mock(ClientCache.class); this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY); diff --git a/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBeanTest.java b/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBeanTest.java index 4791646..9cfddd8 100644 --- a/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBeanTest.java +++ b/spring-session-data-geode/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBeanTest.java @@ -20,9 +20,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @@ -38,7 +36,7 @@ import org.apache.geode.cache.client.ClientRegionShortcut; import org.springframework.beans.factory.BeanFactory; import org.springframework.data.gemfire.client.Interest; -import org.springframework.session.ExpiringSession; +import org.springframework.session.Session; /** * The GemFireCacheTypeAwareRegionFactoryBeanTest class is a test suite of test cases @@ -64,9 +62,6 @@ import org.springframework.session.ExpiringSession; @RunWith(MockitoJUnitRunner.class) public class GemFireCacheTypeAwareRegionFactoryBeanTest { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock Cache mockCache; @@ -74,30 +69,31 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { ClientCache mockClientCache; @Mock - Region mockClientRegion; + Region mockClientRegion; @Mock - Region mockServerRegion; + Region mockServerRegion; - private GemFireCacheTypeAwareRegionFactoryBean regionFactoryBean; + private GemFireCacheTypeAwareRegionFactoryBean regionFactoryBean; @Before public void setup() { - this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean(); + this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<>(); } protected void afterPropertiesSetCreatesCorrectRegionForGemFireCacheType(final GemFireCache expectedCache, - Region expectedRegion) throws Exception { + Region expectedRegion) throws Exception { + + this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean() { - this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean() { @Override - protected Region newClientRegion(GemFireCache gemfireCache) throws Exception { + protected Region newClientRegion(GemFireCache gemfireCache) throws Exception { assertThat(gemfireCache).isSameAs(expectedCache); return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion; } @Override - protected Region newServerRegion(GemFireCache gemfireCache) throws Exception { + protected Region newServerRegion(GemFireCache gemfireCache) throws Exception { assertThat(gemfireCache).isSameAs(expectedCache); return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockServerRegion; } @@ -123,6 +119,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test public void allKeysInterestsRegistration() { + Interest[] interests = this.regionFactoryBean.registerInterests(true); assertThat(interests).isNotNull(); @@ -135,6 +132,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test public void emptyInterestsRegistration() { + Interest[] interests = this.regionFactoryBean.registerInterests(false); assertThat(interests).isNotNull(); @@ -153,6 +151,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test public void setAndGetBeanFactory() { + BeanFactory mockBeanFactory = mock(BeanFactory.class); this.regionFactoryBean.setBeanFactory(mockBeanFactory); @@ -160,22 +159,36 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { assertThat(this.regionFactoryBean.getBeanFactory()).isEqualTo(mockBeanFactory); } - @Test + @Test(expected = IllegalArgumentException.class) + @SuppressWarnings("all") public void setBeanFactoryToNullThrowsIllegalArgumentException() { - this.exception.expect(IllegalArgumentException.class); - this.exception.expectMessage("BeanFactory is required"); - this.regionFactoryBean.setBeanFactory(null); + try { + this.regionFactoryBean.setBeanFactory(null); + } + catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("BeanFactory is required"); + assertThat(expected).hasNoCause(); + + throw expected; + } } - @Test + @Test(expected = IllegalStateException.class) public void getBeanFactoryWhenNullThrowsIllegalStateException() { - this.exception.expect(IllegalStateException.class); - this.exception.expectMessage("A reference to the BeanFactory was not properly configured"); - this.regionFactoryBean.getBeanFactory(); + try { + this.regionFactoryBean.getBeanFactory(); + } + catch (IllegalStateException expected) { + assertThat(expected).hasMessage("A reference to the BeanFactory was not properly configured"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAndGetClientRegionShortcut() { + assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT); @@ -192,6 +205,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test public void setAndGetGemfireCache() { + Cache mockCache = mock(Cache.class); this.regionFactoryBean.setGemfireCache(mockCache); @@ -199,22 +213,35 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { assertThat(this.regionFactoryBean.getGemfireCache()).isEqualTo(mockCache); } - @Test + @Test(expected = IllegalArgumentException.class) public void setGemfireCacheToNullThrowsIllegalArgumentException() { - this.exception.expect(IllegalArgumentException.class); - this.exception.expectMessage("GemFireCache is required"); - this.regionFactoryBean.setGemfireCache(null); + try { + this.regionFactoryBean.setGemfireCache(null); + } + catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("GemFireCache is required"); + assertThat(expected).hasNoCause(); + + throw expected; + } } - @Test + @Test(expected = IllegalStateException.class) public void getGemfireCacheWhenNullThrowsIllegalStateException() { - this.exception.expect(IllegalStateException.class); - this.exception.expectMessage("A reference to the GemFireCache was not properly configured"); - this.regionFactoryBean.getGemfireCache(); + try { + this.regionFactoryBean.getGemfireCache(); + } + catch (IllegalStateException expected) { + assertThat(expected).hasMessage("A reference to the GemFireCache was not properly configured"); + assertThat(expected).hasNoCause(); + + throw expected; + } } @Test public void setAndGetPoolName() { + assertThat(this.regionFactoryBean.getPoolName()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_GEMFIRE_POOL_NAME); @@ -241,7 +268,8 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test @SuppressWarnings("unchecked") public void setAndGetRegionAttributes() { - RegionAttributes mockRegionAttributes = mock(RegionAttributes.class); + + RegionAttributes mockRegionAttributes = mock(RegionAttributes.class); assertThat(this.regionFactoryBean.getRegionAttributes()).isNull(); @@ -256,6 +284,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test public void setAndGetRegionName() { + assertThat(this.regionFactoryBean.getRegionName()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); @@ -281,6 +310,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test public void setAndGetServerRegionShortcut() { + assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT);