From 7f3302253bf828a7e7d75913eca97c8e32dda13f Mon Sep 17 00:00:00 2001 From: Vedran Pavic Date: Sat, 5 Mar 2016 20:27:06 +0100 Subject: [PATCH] Prepare codebase to adhere to Checkstyle rules Issue gh-393 --- .../docs/AbstractGemFireIntegrationTests.java | 42 +- .../HttpSessionGemFireIndexingITests.java | 13 +- .../GemFireHttpSessionConfig.java | 7 +- ...ttpSessionGemFireIndexingCustomITests.java | 13 +- ...FindByIndexNameSessionRepositoryTests.java | 10 +- ...ationNoOpConfigureRedisActionXmlTests.java | 12 +- docs/src/test/java/docs/IndexDocTests.java | 44 +- ...gurationNoOpConfigureRedisActionTests.java | 11 +- .../java/docs/SpringHttpSessionConfig.java | 5 +- .../AbstractHttpSessionListenerTests.java | 20 +- .../docs/http/HazelcastHttpSessionConfig.java | 13 +- .../HttpSessionListenerJavaConfigTests.java | 3 +- .../http/HttpSessionListenerXmlTests.java | 3 +- .../docs/http/RedisHttpSessionConfig.java | 5 +- .../java/docs/websocket/WebSocketConfig.java | 21 +- .../groovy/sample/BootTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../groovy/sample/pages/LoginPage.groovy | 3 +- .../src/main/java/sample/Application.java | 19 +- .../java/sample/config/HttpSessionConfig.java | 5 +- .../java/sample/config/SecurityConfig.java | 19 +- .../main/java/sample/mvc/IndexController.java | 19 +- .../groovy/sample/AttributeTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../src/main/java/sample/Config.java | 5 +- .../src/main/java/sample/Initializer.java | 5 +- .../src/main/java/sample/SessionServlet.java | 14 +- .../groovy/sample/FindByUsernameTests.groovy | 5 +- .../groovy/sample/MultiBrowserGebSpec.groovy | 7 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../groovy/sample/pages/LoginPage.groovy | 3 +- .../sample/FindByUsernameApplication.java | 19 +- .../main/java/sample/config/GeoConfig.java | 7 +- .../java/sample/config/HttpSessionConfig.java | 5 +- .../java/sample/config/SecurityConfig.java | 19 +- .../main/java/sample/mvc/IndexController.java | 29 +- .../main/java/sample/mvc/LoginController.java | 3 +- .../java/sample/session/SessionDetails.java | 7 +- .../sample/session/SessionDetailsFilter.java | 25 +- .../session/SessionDetailsFilterTests.java | 23 +- .../groovy/sample/HazelcastSpringTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../groovy/sample/pages/LoginPage.groovy | 3 +- .../src/main/java/sample/Config.java | 15 +- .../src/main/java/sample/Initializer.java | 5 +- .../java/sample/ObjectStreamSerializer.java | 16 +- .../src/main/java/sample/SecurityConfig.java | 19 +- .../main/java/sample/SecurityInitializer.java | 5 +- .../src/main/java/sample/SessionServlet.java | 6 +- .../groovy/sample/AttributeTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../src/main/java/sample/Initializer.java | 53 +- .../java/sample/ObjectStreamSerializer.java | 16 +- .../src/main/java/sample/SessionServlet.java | 6 +- .../groovy/sample/AttributeTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../src/main/java/sample/Application.java | 5 +- ...FireCacheServerReadyBeanPostProcessor.java | 24 +- .../src/main/java/sample/SessionServlet.java | 6 +- .../groovy/sample/AttributeTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../src/main/java/sample/ClientConfig.java | 25 +- .../src/main/java/sample/Initializer.java | 5 +- .../src/main/java/sample/ServerConfig.java | 11 +- .../src/main/java/sample/SessionServlet.java | 4 +- .../groovy/sample/AttributeTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../src/main/java/sample/SessionServlet.java | 6 +- .../groovy/sample/AttributeTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../src/main/java/sample/Config.java | 3 +- .../src/main/java/sample/Initializer.java | 5 +- .../src/main/java/sample/SessionServlet.java | 4 +- .../groovy/sample/AttributeTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../src/main/java/sample/SessionServlet.java | 12 +- .../groovy/sample/AttributeTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../src/main/java/sample/Config.java | 5 +- .../src/main/java/sample/Initializer.java | 5 +- .../src/main/java/sample/SessionServlet.java | 14 +- .../groovy/sample/RestTests.groovy | 7 +- .../java/rest/RestMockMvcTests.java | 36 +- .../main/java/sample/HttpSessionConfig.java | 5 +- .../src/main/java/sample/Initializer.java | 5 +- .../src/main/java/sample/SecurityConfig.java | 19 +- .../main/java/sample/SecurityInitializer.java | 21 +- .../src/main/java/sample/mvc/MvcConfig.java | 19 +- .../main/java/sample/mvc/MvcInitializer.java | 22 +- .../java/sample/mvc/RestDemoController.java | 25 +- .../groovy/sample/SecurityTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../groovy/sample/pages/LoginPage.groovy | 3 +- .../security/src/main/java/sample/Config.java | 5 +- .../src/main/java/sample/Initializer.java | 5 +- .../src/main/java/sample/SecurityConfig.java | 19 +- .../main/java/sample/SecurityInitializer.java | 5 +- .../src/main/java/sample/SessionServlet.java | 6 +- .../groovy/sample/UserTests.groovy | 5 +- .../groovy/sample/pages/HomePage.groovy | 3 +- .../groovy/sample/pages/LinkPage.groovy | 3 +- .../users/src/main/java/sample/Account.java | 9 +- .../users/src/main/java/sample/Config.java | 21 +- .../src/main/java/sample/Initializer.java | 21 +- .../src/main/java/sample/LoginServlet.java | 10 +- .../src/main/java/sample/LogoutServlet.java | 7 +- .../main/java/sample/UserAccountsFilter.java | 14 +- .../src/main/java/sample/Application.java | 19 +- .../java/sample/config/DataSourceConfig.java | 3 +- .../java/sample/config/H2Initializer.java | 4 +- .../java/sample/config/WebSecurityConfig.java | 5 +- .../java/sample/config/WebSocketConfig.java | 23 +- .../config/WebSocketHandlersConfig.java | 27 +- .../config/WebSocketSecurityConfig.java | 25 +- .../java/sample/data/ActiveWebSocketUser.java | 10 +- .../data/ActiveWebSocketUserRepository.java | 5 +- .../main/java/sample/data/InstantMessage.java | 11 +- .../src/main/java/sample/data/User.java | 21 +- .../main/java/sample/data/UserRepository.java | 19 +- .../main/java/sample/mvc/CsrfController.java | 16 + .../java/sample/mvc/MessageController.java | 37 +- .../java/sample/security/CurrentUser.java | 3 +- .../UserRepositoryUserDetailsService.java | 12 +- .../websocket/WebSocketConnectHandler.java | 17 +- .../websocket/WebSocketDisconnectHandler.java | 21 +- .../session/data/SessionEventRegistry.java | 21 +- .../AbstractGemFireIntegrationTests.java | 40 +- ...ionsSessionRepositoryIntegrationTests.java | 55 +- ...ionsSessionRepositoryIntegrationTests.java | 82 +-- ...FireHttpSessionEventsIntegrationTests.java | 66 +- ...FireHttpSessionJavaConfigurationTests.java | 30 +- ...mFireHttpSessionXmlConfigurationTests.java | 28 +- ...ttpSessionExpireSessionDestroyedTests.java | 57 +- .../RedisHttpSessionConfig.java | 5 +- ...ssionRepositoryFlushImmediatelyITests.java | 16 +- ...isListenerContainerTaskExecutorITests.java | 48 +- .../AbstractHazelcastRepositoryITests.java | 17 +- .../HazelcastClientRepositoryITests.java | 11 +- .../hazelcast/HazelcastITestUtils.java | 7 +- .../HazelcastServerRepositoryITests.java | 2 +- ...EnableHazelcastHttpSessionEventsTests.java | 69 +- ...lcastHttpSessionConfigurationXmlTests.java | 31 +- .../session/ExpiringSession.java | 9 +- .../FindByIndexNameSessionRepository.java | 8 +- .../springframework/session/MapSession.java | 60 +- .../session/MapSessionRepository.java | 47 +- .../org/springframework/session/Session.java | 25 +- .../session/SessionRepository.java | 22 +- .../web/http/EnableSpringHttpSession.java | 7 +- .../http/SpringHttpSessionConfiguration.java | 20 +- ...actGemFireOperationsSessionRepository.java | 136 ++-- .../GemFireOperationsSessionRepository.java | 10 +- .../web/http/EnableGemFireHttpSession.java | 10 +- .../http/GemFireHttpSessionConfiguration.java | 60 +- ...emFireCacheTypeAwareRegionFactoryBean.java | 40 +- .../data/gemfire/support/GemFireUtils.java | 4 +- .../session/data/redis/RedisFlushMode.java | 3 +- .../RedisOperationsSessionRepository.java | 202 ++--- .../redis/RedisSessionExpirationPolicy.java | 47 +- .../data/redis/SessionMessageListener.java | 19 +- .../ConfigureNotifyKeyspaceEventsAction.java | 16 +- .../redis/config/ConfigureRedisAction.java | 3 +- .../web/http/EnableRedisHttpSession.java | 9 +- .../http/RedisHttpSessionConfiguration.java | 78 +- .../session/events/AbstractSessionEvent.java | 9 +- .../session/events/SessionCreatedEvent.java | 6 +- .../session/events/SessionDeletedEvent.java | 5 +- .../session/events/SessionDestroyedEvent.java | 6 +- .../session/events/SessionExpiredEvent.java | 5 +- .../hazelcast/SessionEntryListener.java | 19 +- .../web/http/EnableHazelcastHttpSession.java | 7 +- .../HazelcastHttpSessionConfiguration.java | 52 +- ...ractHttpSessionApplicationInitializer.java | 36 +- .../web/http/CookieHttpSessionStrategy.java | 145 ++-- .../session/web/http/CookieSerializer.java | 15 +- .../web/http/DefaultCookieSerializer.java | 49 +- .../web/http/ExpiringSessionHttpSession.java | 34 +- .../web/http/HeaderHttpSessionStrategy.java | 35 +- .../session/web/http/HttpSessionManager.java | 5 +- .../session/web/http/HttpSessionStrategy.java | 25 +- .../web/http/MultiHttpSessionStrategy.java | 8 +- .../web/http/OnCommittedResponseWrapper.java | 197 ++--- .../web/http/OncePerRequestFilter.java | 48 +- .../http/RequestResponsePostProcessor.java | 3 +- ...essionEventHttpSessionListenerAdapter.java | 14 +- .../web/http/SessionRepositoryFilter.java | 147 ++-- ...ssionWebSocketMessageBrokerConfigurer.java | 25 +- .../socket/events/SessionConnectEvent.java | 7 +- ...bSocketConnectHandlerDecoratorFactory.java | 12 +- .../handler/WebSocketRegistryListener.java | 55 +- .../SessionRepositoryMessageInterceptor.java | 18 +- .../session/MapSessionRepositoryTests.java | 27 +- .../session/MapSessionTests.java | 35 +- ...ttpSessionCustomCookieSerializerTests.java | 28 +- ...onCustomMultiHttpSessionStrategyTests.java | 26 +- ...emFireOperationsSessionRepositoryTest.java | 695 ++++++++++-------- ...emFireOperationsSessionRepositoryTest.java | 223 +++--- .../GemFireHttpSessionConfigurationTest.java | 186 ++--- ...reCacheTypeAwareRegionFactoryBeanTest.java | 158 ++-- .../gemfire/support/GemFireUtilsTest.java | 23 +- ...RedisOperationsSessionRepositoryTests.java | 421 ++++++----- .../RedisSessionExpirationPolicyTests.java | 71 +- .../redis/SessionMessageListenerTests.java | 79 +- ...KeyspaceNotificationsInitializerTests.java | 63 +- ...onClassPathXmlApplicationContextTests.java | 17 +- ...gurationNoOpConfigureRedisActionTests.java | 11 +- ...urationOverrideDefaultSerializerTests.java | 17 +- ...figurationOverrideSessionTaskExecutor.java | 20 +- ...igurationOverrideSessionTaskExecutors.java | 16 +- ...sionConfigurationXmlCustomExpireTests.java | 17 +- ...RedisHttpSessionConfigurationXmlTests.java | 17 +- .../annotation/web/http/gh109/Gh109Tests.java | 13 +- .../http/CookieHttpSessionStrategyTests.java | 213 +++--- .../http/DefaultCookieSerializerTests.java | 194 ++--- .../web/http/HeaderSessionStrategyTests.java | 63 +- .../http/OnCommittedResponseWrapperTests.java | 575 +++++++-------- .../web/http/OncePerRequestFilterTests.java | 54 +- ...nEventHttpSessionListenerAdapterTests.java | 42 +- .../http/SessionRepositoryFilterTests.java | 250 ++++--- ...etConnectHandlerDecoratorFactoryTests.java | 30 +- .../WebSocketRegistryListenerTests.java | 110 +-- ...sionRepositoryMessageInterceptorTests.java | 121 +-- 222 files changed, 4071 insertions(+), 3556 deletions(-) diff --git a/docs/src/integration-test/java/docs/AbstractGemFireIntegrationTests.java b/docs/src/integration-test/java/docs/AbstractGemFireIntegrationTests.java index 8bcf2425..a35d3cc2 100644 --- a/docs/src/integration-test/java/docs/AbstractGemFireIntegrationTests.java +++ b/docs/src/integration-test/java/docs/AbstractGemFireIntegrationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +16,6 @@ package docs; -import static org.assertj.core.api.Assertions.assertThat; - import java.io.File; import java.io.IOException; import java.net.Socket; @@ -27,14 +25,6 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Before; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationListener; -import org.springframework.session.ExpiringSession; -import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; -import org.springframework.session.data.gemfire.support.GemFireUtils; -import org.springframework.session.events.AbstractSessionEvent; - import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.DataPolicy; @@ -46,12 +36,23 @@ import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.ClientCacheFactory; import com.gemstone.gemfire.cache.query.Index; import com.gemstone.gemfire.cache.server.CacheServer; +import org.junit.Before; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationListener; +import org.springframework.session.ExpiringSession; +import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; +import org.springframework.session.data.gemfire.support.GemFireUtils; +import org.springframework.session.events.AbstractSessionEvent; + +import static org.assertj.core.api.Assertions.assertThat; /** * AbstractGemFireIntegrationTests is an abstract base class encapsulating common operations for writing * Spring Session GemFire integration tests. * * @author John Blum + * @since 1.1.0 * @see org.springframework.session.ExpiringSession * @see org.springframework.session.events.AbstractSessionEvent * @see com.gemstone.gemfire.cache.Cache @@ -61,7 +62,6 @@ import com.gemstone.gemfire.cache.server.CacheServer; * @see com.gemstone.gemfire.cache.Region * @see com.gemstone.gemfire.cache.client.ClientCache * @see com.gemstone.gemfire.cache.server.CacheServer - * @since 1.1.0 */ public class AbstractGemFireIntegrationTests { public static final String GEMFIRE_LOG_LEVEL = System.getProperty( @@ -73,7 +73,7 @@ public class AbstractGemFireIntegrationTests { protected static final int DEFAULT_GEMFIRE_SERVER_PORT = CacheServer.DEFAULT_PORT; protected static final long DEFAULT_WAIT_DURATION = TimeUnit.SECONDS.toMillis(20); - protected static final long DEFAULT_WAIT_INTERVAL = 500l; + protected static final long DEFAULT_WAIT_INTERVAL = 500L; protected static final File WORKING_DIRECTORY = new File(System.getProperty("user.dir")); @@ -356,7 +356,7 @@ public class AbstractGemFireIntegrationTests { List regionList = new ArrayList(regions.size()); - for (Region region : regions) { + for (Region region : regions) { regionList.add(region.getFullPath()); } @@ -366,7 +366,7 @@ public class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ @SuppressWarnings("unchecked") protected T createSession() { - T expiringSession = (T) sessionRepository.createSession(); + T expiringSession = (T) this.sessionRepository.createSession(); assertThat(expiringSession).isNotNull(); return expiringSession; } @@ -381,19 +381,19 @@ public class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ protected T expire(T session) { - session.setLastAccessedTime(0l); + session.setLastAccessedTime(0L); return session; } /* (non-Javadoc) */ @SuppressWarnings("unchecked") protected T get(String sessionId) { - return (T) sessionRepository.getSession(sessionId); + return (T) this.sessionRepository.getSession(sessionId); } /* (non-Javadoc) */ protected T save(T session) { - sessionRepository.save(session); + this.sessionRepository.save(session); return session; } @@ -424,14 +424,14 @@ public class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ public void onApplicationEvent(AbstractSessionEvent event) { - sessionEvent = event; + this.sessionEvent = event; } /* (non-Javadoc) */ public T waitForSessionEvent(long duration) { waitOnCondition(new Condition() { public boolean evaluate() { - return (sessionEvent != null); + return (SessionEventListener.this.sessionEvent != null); } }, duration); diff --git a/docs/src/integration-test/java/docs/http/HttpSessionGemFireIndexingITests.java b/docs/src/integration-test/java/docs/http/HttpSessionGemFireIndexingITests.java index e893774d..5aab06fa 100644 --- a/docs/src/integration-test/java/docs/http/HttpSessionGemFireIndexingITests.java +++ b/docs/src/integration-test/java/docs/http/HttpSessionGemFireIndexingITests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package docs.http; -import static org.assertj.core.api.Assertions.assertThat; +package docs.http; import java.util.Map; import java.util.Properties; +import docs.AbstractGemFireIntegrationTests; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.gemfire.CacheFactoryBean; @@ -36,7 +37,7 @@ import org.springframework.session.data.gemfire.config.annotation.web.http.Enabl import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import docs.AbstractGemFireIntegrationTests; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch @@ -59,7 +60,7 @@ public class HttpSessionGemFireIndexingITests extends AbstractGemFireIntegration sessionRepository.save(session); // tag::findbyindexname-get[] - Map idToSessions = sessionRepository.findByIndexNameAndIndexValue(indexName, username); + Map idToSessions = sessionRepository.findByIndexNameAndIndexValue(indexName, username); // end::findbyindexname-get[] assertThat(idToSessions.keySet()).containsOnly(session.getId()); @@ -82,7 +83,7 @@ public class HttpSessionGemFireIndexingITests extends AbstractGemFireIntegration // tag::findbyspringsecurityindexname-get[] String indexName = FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME; - Map idToSessions = sessionRepository.findByIndexNameAndIndexValue(indexName, authentication.getName()); + Map idToSessions = sessionRepository.findByIndexNameAndIndexValue(indexName, authentication.getName()); // end::findbyspringsecurityindexname-get[] assertThat(idToSessions.keySet()).containsOnly(session.getId()); diff --git a/docs/src/integration-test/java/docs/http/gemfire/indexablesessionattributes/GemFireHttpSessionConfig.java b/docs/src/integration-test/java/docs/http/gemfire/indexablesessionattributes/GemFireHttpSessionConfig.java index 13ad608c..096890a6 100644 --- a/docs/src/integration-test/java/docs/http/gemfire/indexablesessionattributes/GemFireHttpSessionConfig.java +++ b/docs/src/integration-test/java/docs/http/gemfire/indexablesessionattributes/GemFireHttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package docs.http.gemfire.indexablesessionattributes; import java.util.Properties; +import docs.AbstractGemFireIntegrationTests; + import org.springframework.context.annotation.Bean; import org.springframework.data.gemfire.CacheFactoryBean; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; -import docs.AbstractGemFireIntegrationTests; - /** * @author Rob Winch * diff --git a/docs/src/integration-test/java/docs/http/gemfire/indexablesessionattributes/HttpSessionGemFireIndexingCustomITests.java b/docs/src/integration-test/java/docs/http/gemfire/indexablesessionattributes/HttpSessionGemFireIndexingCustomITests.java index 780c2889..cfbae29d 100644 --- a/docs/src/integration-test/java/docs/http/gemfire/indexablesessionattributes/HttpSessionGemFireIndexingCustomITests.java +++ b/docs/src/integration-test/java/docs/http/gemfire/indexablesessionattributes/HttpSessionGemFireIndexingCustomITests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,26 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package docs.http.gemfire.indexablesessionattributes; -import static org.assertj.core.api.Assertions.assertThat; +package docs.http.gemfire.indexablesessionattributes; import java.util.Map; +import docs.AbstractGemFireIntegrationTests; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.session.ExpiringSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import docs.AbstractGemFireIntegrationTests; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes=GemFireHttpSessionConfig.class) +@ContextConfiguration(classes = GemFireHttpSessionConfig.class) public class HttpSessionGemFireIndexingCustomITests extends AbstractGemFireIntegrationTests { @Test @@ -48,7 +49,7 @@ public class HttpSessionGemFireIndexingCustomITests extends AbstractGemFireInteg sessionRepository.save(session); // tag::findbyindexname-get[] - Map idToSessions = sessionRepository.findByIndexNameAndIndexValue(indexName, attrValue); + Map idToSessions = sessionRepository.findByIndexNameAndIndexValue(indexName, attrValue); // end::findbyindexname-get[] assertThat(idToSessions.keySet()).containsOnly(session.getId()); diff --git a/docs/src/test/java/docs/FindByIndexNameSessionRepositoryTests.java b/docs/src/test/java/docs/FindByIndexNameSessionRepositoryTests.java index c876142f..986a3d72 100644 --- a/docs/src/test/java/docs/FindByIndexNameSessionRepositoryTests.java +++ b/docs/src/test/java/docs/FindByIndexNameSessionRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package docs; import java.util.Map; @@ -21,6 +22,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.Session; @@ -39,7 +41,7 @@ public class FindByIndexNameSessionRepositoryTests { public void setUsername() { // tag::set-username[] String username = "username"; - session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); + this.session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); // end::set-username[] } @@ -48,8 +50,8 @@ public class FindByIndexNameSessionRepositoryTests { public void findByUsername() { // tag::findby-username[] String username = "username"; - Map sessionIdToSession = - sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); + Map sessionIdToSession = + this.sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); // end::findby-username[] } } diff --git a/docs/src/test/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java b/docs/src/test/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java index 994c14bf..da23a011 100644 --- a/docs/src/test/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java +++ b/docs/src/test/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package docs; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.mock; +package docs; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.session.ExpiringSession; @@ -28,6 +27,9 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + /** * @author Rob Winch */ @@ -40,7 +42,7 @@ public class HttpSessionConfigurationNoOpConfigureRedisActionXmlTests { @Test public void redisConnectionFactoryNotUsedSinceNoValidation() { - assertThat(filter).isNotNull(); + assertThat(this.filter).isNotNull(); } diff --git a/docs/src/test/java/docs/IndexDocTests.java b/docs/src/test/java/docs/IndexDocTests.java index 8e19bfd4..3e683131 100644 --- a/docs/src/test/java/docs/IndexDocTests.java +++ b/docs/src/test/java/docs/IndexDocTests.java @@ -1,23 +1,23 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package docs; -import static org.assertj.core.api.Assertions.*; - import org.junit.Test; + import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.mock.web.MockServletContext; import org.springframework.session.ExpiringSession; @@ -28,6 +28,8 @@ import org.springframework.session.data.redis.RedisOperationsSessionRepository; import org.springframework.session.web.http.SessionRepositoryFilter; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Rob Winch */ @@ -47,15 +49,15 @@ public class IndexDocTests { private SessionRepository repository; // <1> public void demo() { - S toSave = repository.createSession(); // <2> + S toSave = this.repository.createSession(); // <2> // <3> User rwinch = new User("rwinch"); toSave.setAttribute(ATTR_USER, rwinch); - repository.save(toSave); // <4> + this.repository.save(toSave); // <4> - S session = repository.getSession(toSave.getId()); // <5> + S session = this.repository.getSession(toSave.getId()); // <5> // <6> User user = session.getAttribute(ATTR_USER); @@ -81,13 +83,13 @@ public class IndexDocTests { private SessionRepository repository; // <1> public void demo() { - S toSave = repository.createSession(); // <2> + S toSave = this.repository.createSession(); // <2> // ... toSave.setMaxInactiveIntervalInSeconds(30); // <3> - repository.save(toSave); // <4> + this.repository.save(toSave); // <4> - S session = repository.getSession(toSave.getId()); // <5> + S session = this.repository.getSession(toSave.getId()); // <5> // ... } @@ -122,12 +124,14 @@ public class IndexDocTests { try { context.getBean(SessionRepositoryFilter.class); - } finally { + } + finally { context.close(); } } - private static class User { - private User(String username) {} + private static final class User { + private User(String username) { + } } } diff --git a/docs/src/test/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java b/docs/src/test/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java index 2c17f2ca..21fa5600 100644 --- a/docs/src/test/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java +++ b/docs/src/test/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package docs; -import static org.mockito.Mockito.mock; +package docs; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; @@ -28,6 +28,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.mockito.Mockito.mock; + /** * @author Rob Winch */ @@ -37,7 +39,8 @@ import org.springframework.test.context.web.WebAppConfiguration; public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { @Test - public void redisConnectionFactoryNotUsedSinceNoValidation() {} + public void redisConnectionFactoryNotUsedSinceNoValidation() { + } @EnableRedisHttpSession @Configuration diff --git a/docs/src/test/java/docs/SpringHttpSessionConfig.java b/docs/src/test/java/docs/SpringHttpSessionConfig.java index b7456e90..30694cdf 100644 --- a/docs/src/test/java/docs/SpringHttpSessionConfig.java +++ b/docs/src/test/java/docs/SpringHttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package docs; import org.springframework.context.annotation.Bean; @@ -29,4 +30,4 @@ public class SpringHttpSessionConfig { return new MapSessionRepository(); } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/docs/src/test/java/docs/http/AbstractHttpSessionListenerTests.java b/docs/src/test/java/docs/http/AbstractHttpSessionListenerTests.java index 4a7fb67a..567f1f07 100644 --- a/docs/src/test/java/docs/http/AbstractHttpSessionListenerTests.java +++ b/docs/src/test/java/docs/http/AbstractHttpSessionListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package docs.http; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +package docs.http; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationListener; @@ -32,6 +30,10 @@ import org.springframework.session.Session; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + /** * @author Rob Winch * @since 1.2 @@ -49,16 +51,16 @@ public abstract class AbstractHttpSessionListenerTests { public void springSessionDestroyedTranslatedToSpringSecurityDestroyed() { Session session = new MapSession(); - publisher.publishEvent(new org.springframework.session.events.SessionDestroyedEvent(this, session)); + this.publisher.publishEvent(new org.springframework.session.events.SessionDestroyedEvent(this, session)); - assertThat(listener.getEvent().getId()).isEqualTo(session.getId()); + assertThat(this.listener.getEvent().getId()).isEqualTo(session.getId()); } static RedisConnectionFactory createMockRedisConnection() { RedisConnectionFactory factory = mock(RedisConnectionFactory.class); RedisConnection connection = mock(RedisConnection.class); - when(factory.getConnection()).thenReturn(connection); + given(factory.getConnection()).willReturn(connection); return factory; } @@ -74,7 +76,7 @@ public abstract class AbstractHttpSessionListenerTests { } public SessionDestroyedEvent getEvent() { - return event; + return this.event; } } } diff --git a/docs/src/test/java/docs/http/HazelcastHttpSessionConfig.java b/docs/src/test/java/docs/http/HazelcastHttpSessionConfig.java index 14f707f2..6a472095 100644 --- a/docs/src/test/java/docs/http/HazelcastHttpSessionConfig.java +++ b/docs/src/test/java/docs/http/HazelcastHttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package docs.http; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.session.hazelcast.config.annotation.web.http.EnableHazelcastHttpSession; +package docs.http; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.session.hazelcast.config.annotation.web.http.EnableHazelcastHttpSession; + //tag::config[] @EnableHazelcastHttpSession // <1> @Configuration @@ -33,4 +34,4 @@ public class HazelcastHttpSessionConfig { return Hazelcast.newHazelcastInstance(hazelcastConfig); // <2> } } -// end::config[] \ No newline at end of file +// end::config[] diff --git a/docs/src/test/java/docs/http/HttpSessionListenerJavaConfigTests.java b/docs/src/test/java/docs/http/HttpSessionListenerJavaConfigTests.java index 3aeecd8d..f051976e 100644 --- a/docs/src/test/java/docs/http/HttpSessionListenerJavaConfigTests.java +++ b/docs/src/test/java/docs/http/HttpSessionListenerJavaConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package docs.http; import org.springframework.context.annotation.Bean; diff --git a/docs/src/test/java/docs/http/HttpSessionListenerXmlTests.java b/docs/src/test/java/docs/http/HttpSessionListenerXmlTests.java index 43c900aa..aa359e23 100644 --- a/docs/src/test/java/docs/http/HttpSessionListenerXmlTests.java +++ b/docs/src/test/java/docs/http/HttpSessionListenerXmlTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package docs.http; import org.springframework.test.context.ContextConfiguration; diff --git a/docs/src/test/java/docs/http/RedisHttpSessionConfig.java b/docs/src/test/java/docs/http/RedisHttpSessionConfig.java index 13b97072..948de07e 100644 --- a/docs/src/test/java/docs/http/RedisHttpSessionConfig.java +++ b/docs/src/test/java/docs/http/RedisHttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package docs.http; import org.springframework.context.annotation.Bean; @@ -32,4 +33,4 @@ public class RedisHttpSessionConfig { // ... } -// end::config[] \ No newline at end of file +// end::config[] diff --git a/docs/src/test/java/docs/websocket/WebSocketConfig.java b/docs/src/test/java/docs/websocket/WebSocketConfig.java index 46123ad2..81b435ff 100644 --- a/docs/src/test/java/docs/websocket/WebSocketConfig.java +++ b/docs/src/test/java/docs/websocket/WebSocketConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package docs.websocket; import org.springframework.context.annotation.Configuration; @@ -43,4 +44,4 @@ public class WebSocketConfig registry.setApplicationDestinationPrefixes("/app"); } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/boot/src/integration-test/groovy/sample/BootTests.groovy b/samples/boot/src/integration-test/groovy/sample/BootTests.groovy index b1c8d7f4..f158edbd 100644 --- a/samples/boot/src/integration-test/groovy/sample/BootTests.groovy +++ b/samples/boot/src/integration-test/groovy/sample/BootTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -71,4 +72,4 @@ class BootTests extends GebReportingSpec { then: 'sent to the log in page' at LoginPage } -} \ No newline at end of file +} diff --git a/samples/boot/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/boot/src/integration-test/groovy/sample/pages/HomePage.groovy index 867b81a7..ae2c3e94 100644 --- a/samples/boot/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/boot/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/boot/src/integration-test/groovy/sample/pages/LoginPage.groovy b/samples/boot/src/integration-test/groovy/sample/pages/LoginPage.groovy index ceeb790a..68f98597 100644 --- a/samples/boot/src/integration-test/groovy/sample/pages/LoginPage.groovy +++ b/samples/boot/src/integration-test/groovy/sample/pages/LoginPage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/boot/src/main/java/sample/Application.java b/samples/boot/src/main/java/sample/Application.java index 8d570129..02627e78 100644 --- a/samples/boot/src/main/java/sample/Application.java +++ b/samples/boot/src/main/java/sample/Application.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; import org.springframework.boot.SpringApplication; diff --git a/samples/boot/src/main/java/sample/config/HttpSessionConfig.java b/samples/boot/src/main/java/sample/config/HttpSessionConfig.java index 29ba85c0..40b37329 100644 --- a/samples/boot/src/main/java/sample/config/HttpSessionConfig.java +++ b/samples/boot/src/main/java/sample/config/HttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.config; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @@ -21,4 +22,4 @@ import org.springframework.session.data.redis.config.annotation.web.http.EnableR // tag::class[] @EnableRedisHttpSession // <1> public class HttpSessionConfig { } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/boot/src/main/java/sample/config/SecurityConfig.java b/samples/boot/src/main/java/sample/config/SecurityConfig.java index ab040300..082b2fd5 100644 --- a/samples/boot/src/main/java/sample/config/SecurityConfig.java +++ b/samples/boot/src/main/java/sample/config/SecurityConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.config; import org.springframework.beans.factory.annotation.Autowired; diff --git a/samples/boot/src/main/java/sample/mvc/IndexController.java b/samples/boot/src/main/java/sample/mvc/IndexController.java index 8a76934d..8c94fb38 100644 --- a/samples/boot/src/main/java/sample/mvc/IndexController.java +++ b/samples/boot/src/main/java/sample/mvc/IndexController.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.mvc; import org.springframework.stereotype.Controller; diff --git a/samples/custom-cookie/src/integration-test/groovy/sample/AttributeTests.groovy b/samples/custom-cookie/src/integration-test/groovy/sample/AttributeTests.groovy index a5f85c86..c865fc43 100644 --- a/samples/custom-cookie/src/integration-test/groovy/sample/AttributeTests.groovy +++ b/samples/custom-cookie/src/integration-test/groovy/sample/AttributeTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -42,4 +43,4 @@ class AttributeTests extends GebReportingSpec { attributes[0].name == 'a' attributes[0].value == 'b' } -} \ No newline at end of file +} diff --git a/samples/custom-cookie/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/custom-cookie/src/integration-test/groovy/sample/pages/HomePage.groovy index e087b5c4..25215292 100644 --- a/samples/custom-cookie/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/custom-cookie/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/custom-cookie/src/main/java/sample/Config.java b/samples/custom-cookie/src/main/java/sample/Config.java index a1db9fef..1555763d 100644 --- a/samples/custom-cookie/src/main/java/sample/Config.java +++ b/samples/custom-cookie/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.context.annotation.Bean; @@ -40,4 +41,4 @@ public class Config { return serializer; } // end::cookie-serializer[] -} \ No newline at end of file +} diff --git a/samples/custom-cookie/src/main/java/sample/Initializer.java b/samples/custom-cookie/src/main/java/sample/Initializer.java index 7512f33c..508db307 100644 --- a/samples/custom-cookie/src/main/java/sample/Initializer.java +++ b/samples/custom-cookie/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; @@ -25,4 +26,4 @@ public class Initializer super(Config.class); // <2> } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/custom-cookie/src/main/java/sample/SessionServlet.java b/samples/custom-cookie/src/main/java/sample/SessionServlet.java index f0a8d6dc..95fc103a 100644 --- a/samples/custom-cookie/src/main/java/sample/SessionServlet.java +++ b/samples/custom-cookie/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; -import javax.servlet.*; -import javax.servlet.annotation.*; -import javax.servlet.http.*; import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + // tag::class[] @WebServlet("/session") public class SessionServlet extends HttpServlet { @@ -34,4 +38,4 @@ public class SessionServlet extends HttpServlet { private static final long serialVersionUID = 2878267318695777395L; } -// tag::end[] \ No newline at end of file +// tag::end[] diff --git a/samples/findbyusername/src/integration-test/groovy/sample/FindByUsernameTests.groovy b/samples/findbyusername/src/integration-test/groovy/sample/FindByUsernameTests.groovy index 511c3781..21228034 100644 --- a/samples/findbyusername/src/integration-test/groovy/sample/FindByUsernameTests.groovy +++ b/samples/findbyusername/src/integration-test/groovy/sample/FindByUsernameTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.Browser @@ -101,4 +102,4 @@ class FindByUsernameTests extends MultiBrowserGebSpec { then: 'browser a sent to log in' a.at LoginPage } -} \ No newline at end of file +} diff --git a/samples/findbyusername/src/integration-test/groovy/sample/MultiBrowserGebSpec.groovy b/samples/findbyusername/src/integration-test/groovy/sample/MultiBrowserGebSpec.groovy index 5c2f73a0..6f38c197 100644 --- a/samples/findbyusername/src/integration-test/groovy/sample/MultiBrowserGebSpec.groovy +++ b/samples/findbyusername/src/integration-test/groovy/sample/MultiBrowserGebSpec.groovy @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import geb.* import spock.lang.* @@ -97,4 +98,4 @@ abstract class MultiBrowserGebSpec extends Specification { def cleanupSpec() { if (isSpecStepwise()) resetBrowsers() } -} \ No newline at end of file +} diff --git a/samples/findbyusername/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/findbyusername/src/integration-test/groovy/sample/pages/HomePage.groovy index 3d877631..a9d002df 100644 --- a/samples/findbyusername/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/findbyusername/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/findbyusername/src/integration-test/groovy/sample/pages/LoginPage.groovy b/samples/findbyusername/src/integration-test/groovy/sample/pages/LoginPage.groovy index 612be1e6..b93ad5f9 100644 --- a/samples/findbyusername/src/integration-test/groovy/sample/pages/LoginPage.groovy +++ b/samples/findbyusername/src/integration-test/groovy/sample/pages/LoginPage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/findbyusername/src/main/java/sample/FindByUsernameApplication.java b/samples/findbyusername/src/main/java/sample/FindByUsernameApplication.java index 433e782b..0bca487f 100644 --- a/samples/findbyusername/src/main/java/sample/FindByUsernameApplication.java +++ b/samples/findbyusername/src/main/java/sample/FindByUsernameApplication.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; import org.springframework.boot.SpringApplication; diff --git a/samples/findbyusername/src/main/java/sample/config/GeoConfig.java b/samples/findbyusername/src/main/java/sample/config/GeoConfig.java index d34404d2..c74a29fb 100644 --- a/samples/findbyusername/src/main/java/sample/config/GeoConfig.java +++ b/samples/findbyusername/src/main/java/sample/config/GeoConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.config; import java.io.InputStream; +import com.maxmind.geoip2.DatabaseReader; + import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.maxmind.geoip2.DatabaseReader; - /** * * @author Rob Winch diff --git a/samples/findbyusername/src/main/java/sample/config/HttpSessionConfig.java b/samples/findbyusername/src/main/java/sample/config/HttpSessionConfig.java index f516173f..fd61436a 100644 --- a/samples/findbyusername/src/main/java/sample/config/HttpSessionConfig.java +++ b/samples/findbyusername/src/main/java/sample/config/HttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.config; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @@ -25,4 +26,4 @@ import org.springframework.session.data.redis.config.annotation.web.http.EnableR // tag::class[] @EnableRedisHttpSession // <1> public class HttpSessionConfig { } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/findbyusername/src/main/java/sample/config/SecurityConfig.java b/samples/findbyusername/src/main/java/sample/config/SecurityConfig.java index ade70f5f..9747d785 100644 --- a/samples/findbyusername/src/main/java/sample/config/SecurityConfig.java +++ b/samples/findbyusername/src/main/java/sample/config/SecurityConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.config; import org.springframework.beans.factory.annotation.Autowired; diff --git a/samples/findbyusername/src/main/java/sample/mvc/IndexController.java b/samples/findbyusername/src/main/java/sample/mvc/IndexController.java index 0200fc5d..51ee4fd0 100644 --- a/samples/findbyusername/src/main/java/sample/mvc/IndexController.java +++ b/samples/findbyusername/src/main/java/sample/mvc/IndexController.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.mvc; import java.security.Principal; @@ -43,7 +44,7 @@ public class IndexController { @RequestMapping("/") public String index(Principal principal, Model model) { Collection usersSessions = - sessions.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, + this.sessions.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal.getName()).values(); model.addAttribute("sessions", usersSessions); return "index"; @@ -52,12 +53,12 @@ public class IndexController { @RequestMapping(value = "/sessions/{sessionIdToDelete}", method = RequestMethod.DELETE) public String removeSession(Principal principal, @PathVariable String sessionIdToDelete) { - Set usersSessionIds = sessions.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, + Set usersSessionIds = this.sessions.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal.getName()).keySet(); - if(usersSessionIds.contains(sessionIdToDelete)) { - sessions.delete(sessionIdToDelete); + if (usersSessionIds.contains(sessionIdToDelete)) { + this.sessions.delete(sessionIdToDelete); } return "redirect:/"; } -} \ No newline at end of file +} diff --git a/samples/findbyusername/src/main/java/sample/mvc/LoginController.java b/samples/findbyusername/src/main/java/sample/mvc/LoginController.java index 81bb64a1..7403b021 100644 --- a/samples/findbyusername/src/main/java/sample/mvc/LoginController.java +++ b/samples/findbyusername/src/main/java/sample/mvc/LoginController.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.mvc; import org.springframework.stereotype.Controller; diff --git a/samples/findbyusername/src/main/java/sample/session/SessionDetails.java b/samples/findbyusername/src/main/java/sample/session/SessionDetails.java index 3d6b52f5..03be008f 100644 --- a/samples/findbyusername/src/main/java/sample/session/SessionDetails.java +++ b/samples/findbyusername/src/main/java/sample/session/SessionDetails.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.session; import java.io.Serializable; @@ -30,7 +31,7 @@ public class SessionDetails implements Serializable { private String accessType; public String getLocation() { - return location; + return this.location; } public void setLocation(String location) { @@ -38,7 +39,7 @@ public class SessionDetails implements Serializable { } public String getAccessType() { - return accessType; + return this.accessType; } public void setAccessType(String accessType) { diff --git a/samples/findbyusername/src/main/java/sample/session/SessionDetailsFilter.java b/samples/findbyusername/src/main/java/sample/session/SessionDetailsFilter.java index 70b6e4ec..4731734f 100644 --- a/samples/findbyusername/src/main/java/sample/session/SessionDetailsFilter.java +++ b/samples/findbyusername/src/main/java/sample/session/SessionDetailsFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.session; import java.io.IOException; @@ -24,15 +25,15 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.model.CityResponse; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; -import com.maxmind.geoip2.DatabaseReader; -import com.maxmind.geoip2.model.CityResponse; - /** * Inserts the session details into the session for every request. Some users * may prefer to insert session details only after authentication. This is fine, @@ -76,18 +77,21 @@ public class SessionDetailsFilter extends OncePerRequestFilter { String getGeoLocation(String remoteAddr) { try { - CityResponse city = reader.city(InetAddress.getByName(remoteAddr)); + CityResponse city = this.reader.city(InetAddress.getByName(remoteAddr)); String cityName = city.getCity().getName(); String countryName = city.getCountry().getName(); - if(cityName == null && countryName == null) { + if (cityName == null && countryName == null) { return null; - } else if(cityName == null) { + } + else if (cityName == null) { return countryName; - } else if(countryName == null) { + } + else if (countryName == null) { return cityName; } return cityName + ", " + countryName; - } catch (Exception e) { + } + catch (Exception e) { return UNKNOWN; } @@ -97,7 +101,8 @@ public class SessionDetailsFilter extends OncePerRequestFilter { String remoteAddr = request.getHeader("X-FORWARDED-FOR"); if (remoteAddr == null) { remoteAddr = request.getRemoteAddr(); - } else if (remoteAddr.contains(",")) { + } + else if (remoteAddr.contains(",")) { remoteAddr = remoteAddr.split(",")[0]; } return remoteAddr; diff --git a/samples/findbyusername/src/test/java/sample/session/SessionDetailsFilterTests.java b/samples/findbyusername/src/test/java/sample/session/SessionDetailsFilterTests.java index da098b59..66eb75ea 100644 --- a/samples/findbyusername/src/test/java/sample/session/SessionDetailsFilterTests.java +++ b/samples/findbyusername/src/test/java/sample/session/SessionDetailsFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,20 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.session; -import static org.assertj.core.api.Assertions.*; - +import com.maxmind.geoip2.DatabaseReader; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + +import sample.config.GeoConfig; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.maxmind.geoip2.DatabaseReader; - -import sample.config.GeoConfig; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch @@ -42,21 +43,21 @@ public class SessionDetailsFilterTests { @Before public void setup() { - filter = new SessionDetailsFilter(reader); + this.filter = new SessionDetailsFilter(this.reader); } @Test public void getGeoLocationHanldesInvalidIp() { - assertThat(filter.getGeoLocation("a")).isEqualTo(SessionDetailsFilter.UNKNOWN); + assertThat(this.filter.getGeoLocation("a")).isEqualTo(SessionDetailsFilter.UNKNOWN); } @Test public void getGeoLocationNullCity() { - assertThat(filter.getGeoLocation("22.231.113.64")).isEqualTo("United States"); + assertThat(this.filter.getGeoLocation("22.231.113.64")).isEqualTo("United States"); } @Test public void getGeoLocationBoth() { - assertThat(filter.getGeoLocation("184.154.83.119")).isEqualTo("Chicago, United States"); + assertThat(this.filter.getGeoLocation("184.154.83.119")).isEqualTo("Chicago, United States"); } -} \ No newline at end of file +} diff --git a/samples/hazelcast-spring/src/integration-test/groovy/sample/HazelcastSpringTests.groovy b/samples/hazelcast-spring/src/integration-test/groovy/sample/HazelcastSpringTests.groovy index 12a1fa96..df2c1cab 100644 --- a/samples/hazelcast-spring/src/integration-test/groovy/sample/HazelcastSpringTests.groovy +++ b/samples/hazelcast-spring/src/integration-test/groovy/sample/HazelcastSpringTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.GebReportingSpec @@ -62,4 +63,4 @@ class HazelcastSpringTests extends GebReportingSpec { then: 'sent to the log in page' at LoginPage } -} \ No newline at end of file +} diff --git a/samples/hazelcast-spring/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/hazelcast-spring/src/integration-test/groovy/sample/pages/HomePage.groovy index 45634e66..b98a276e 100644 --- a/samples/hazelcast-spring/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/hazelcast-spring/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.Page diff --git a/samples/hazelcast-spring/src/integration-test/groovy/sample/pages/LoginPage.groovy b/samples/hazelcast-spring/src/integration-test/groovy/sample/pages/LoginPage.groovy index 08c7fb27..d8a5beaf 100644 --- a/samples/hazelcast-spring/src/integration-test/groovy/sample/pages/LoginPage.groovy +++ b/samples/hazelcast-spring/src/integration-test/groovy/sample/pages/LoginPage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.Page diff --git a/samples/hazelcast-spring/src/main/java/sample/Config.java b/samples/hazelcast-spring/src/main/java/sample/Config.java index 4fcbcf16..ba591e60 100644 --- a/samples/hazelcast-spring/src/main/java/sample/Config.java +++ b/samples/hazelcast-spring/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package sample; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.session.hazelcast.config.annotation.web.http.EnableHazelcastHttpSession; -import org.springframework.util.SocketUtils; +package sample; import com.hazelcast.config.NetworkConfig; import com.hazelcast.config.SerializerConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.session.hazelcast.config.annotation.web.http.EnableHazelcastHttpSession; +import org.springframework.util.SocketUtils; + // tag::class[] @EnableHazelcastHttpSession(maxInactiveIntervalInSeconds = 300) @Configuration @@ -45,4 +46,4 @@ public class Config { } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/hazelcast-spring/src/main/java/sample/Initializer.java b/samples/hazelcast-spring/src/main/java/sample/Initializer.java index f8627a7f..6970e506 100644 --- a/samples/hazelcast-spring/src/main/java/sample/Initializer.java +++ b/samples/hazelcast-spring/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; @@ -21,4 +22,4 @@ import org.springframework.session.web.context.AbstractHttpSessionApplicationIni public class Initializer extends AbstractHttpSessionApplicationInitializer { } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/hazelcast-spring/src/main/java/sample/ObjectStreamSerializer.java b/samples/hazelcast-spring/src/main/java/sample/ObjectStreamSerializer.java index 11db8e8c..78b31ee6 100644 --- a/samples/hazelcast-spring/src/main/java/sample/ObjectStreamSerializer.java +++ b/samples/hazelcast-spring/src/main/java/sample/ObjectStreamSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; @@ -37,18 +42,19 @@ public class ObjectStreamSerializer implements StreamSerializer { } public void write(ObjectDataOutput objectDataOutput, Object object) - throws IOException { + throws IOException { ObjectOutputStream out = new ObjectOutputStream((OutputStream) objectDataOutput); out.writeObject(object); out.flush(); } public Object read(ObjectDataInput objectDataInput) - throws IOException { + throws IOException { ObjectInputStream in = new ObjectInputStream((InputStream) objectDataInput); try { return in.readObject(); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { throw new IOException(e); } } diff --git a/samples/hazelcast-spring/src/main/java/sample/SecurityConfig.java b/samples/hazelcast-spring/src/main/java/sample/SecurityConfig.java index e6c5da8c..47487c9e 100644 --- a/samples/hazelcast-spring/src/main/java/sample/SecurityConfig.java +++ b/samples/hazelcast-spring/src/main/java/sample/SecurityConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; /** diff --git a/samples/hazelcast-spring/src/main/java/sample/SecurityInitializer.java b/samples/hazelcast-spring/src/main/java/sample/SecurityInitializer.java index 7cb5982d..8122d211 100644 --- a/samples/hazelcast-spring/src/main/java/sample/SecurityInitializer.java +++ b/samples/hazelcast-spring/src/main/java/sample/SecurityInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; @@ -25,4 +26,4 @@ public class SecurityInitializer extends super(SecurityConfig.class, Config.class); } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/hazelcast-spring/src/main/java/sample/SessionServlet.java b/samples/hazelcast-spring/src/main/java/sample/SessionServlet.java index 2d56ce48..16e60bb6 100644 --- a/samples/hazelcast-spring/src/main/java/sample/SessionServlet.java +++ b/samples/hazelcast-spring/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; +import java.io.IOException; + import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; @WebServlet("/session") public class SessionServlet extends HttpServlet { diff --git a/samples/hazelcast/src/integration-test/groovy/sample/AttributeTests.groovy b/samples/hazelcast/src/integration-test/groovy/sample/AttributeTests.groovy index a5f85c86..c865fc43 100644 --- a/samples/hazelcast/src/integration-test/groovy/sample/AttributeTests.groovy +++ b/samples/hazelcast/src/integration-test/groovy/sample/AttributeTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -42,4 +43,4 @@ class AttributeTests extends GebReportingSpec { attributes[0].name == 'a' attributes[0].value == 'b' } -} \ No newline at end of file +} diff --git a/samples/hazelcast/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/hazelcast/src/integration-test/groovy/sample/pages/HomePage.groovy index e087b5c4..25215292 100644 --- a/samples/hazelcast/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/hazelcast/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/hazelcast/src/main/java/sample/Initializer.java b/samples/hazelcast/src/main/java/sample/Initializer.java index c1caf406..41c99128 100644 --- a/samples/hazelcast/src/main/java/sample/Initializer.java +++ b/samples/hazelcast/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,19 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; -import com.hazelcast.config.Config; -import com.hazelcast.config.MapConfig; -import com.hazelcast.config.NetworkConfig; -import com.hazelcast.config.SerializerConfig; -import com.hazelcast.core.Hazelcast; -import com.hazelcast.core.HazelcastInstance; -import org.springframework.session.ExpiringSession; -import org.springframework.session.MapSession; -import org.springframework.session.MapSessionRepository; -import org.springframework.session.SessionRepository; -import org.springframework.session.web.http.SessionRepositoryFilter; +import java.io.IOException; +import java.net.ServerSocket; +import java.util.EnumSet; +import java.util.Map; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration.Dynamic; @@ -33,10 +27,19 @@ import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; -import java.io.IOException; -import java.net.ServerSocket; -import java.util.EnumSet; -import java.util.Map; + +import com.hazelcast.config.Config; +import com.hazelcast.config.MapConfig; +import com.hazelcast.config.NetworkConfig; +import com.hazelcast.config.SerializerConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; + +import org.springframework.session.ExpiringSession; +import org.springframework.session.MapSession; +import org.springframework.session.MapSessionRepository; +import org.springframework.session.SessionRepository; +import org.springframework.session.web.http.SessionRepositoryFilter; @WebListener public class Initializer implements ServletContextListener { @@ -59,8 +62,8 @@ public class Initializer implements ServletContextListener { mc.setTimeToLiveSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); cfg.addMapConfig(mc); - instance = Hazelcast.newHazelcastInstance(cfg); - Map sessions = instance.getMap(sessionMapName); + this.instance = Hazelcast.newHazelcastInstance(cfg); + Map sessions = this.instance.getMap(sessionMapName); SessionRepository sessionRepository = new MapSessionRepository(sessions); @@ -71,7 +74,7 @@ public class Initializer implements ServletContextListener { } public void contextDestroyed(ServletContextEvent sce) { - instance.shutdown(); + this.instance.shutdown(); } private static int getAvailablePort() { @@ -79,12 +82,16 @@ public class Initializer implements ServletContextListener { try { socket = new ServerSocket(0); return socket.getLocalPort(); - } catch(IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); - } finally { + } + finally { try { socket.close(); - }catch(IOException e) {} + } + catch (IOException e) { + } } } -} \ No newline at end of file +} diff --git a/samples/hazelcast/src/main/java/sample/ObjectStreamSerializer.java b/samples/hazelcast/src/main/java/sample/ObjectStreamSerializer.java index 11db8e8c..78b31ee6 100644 --- a/samples/hazelcast/src/main/java/sample/ObjectStreamSerializer.java +++ b/samples/hazelcast/src/main/java/sample/ObjectStreamSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; @@ -37,18 +42,19 @@ public class ObjectStreamSerializer implements StreamSerializer { } public void write(ObjectDataOutput objectDataOutput, Object object) - throws IOException { + throws IOException { ObjectOutputStream out = new ObjectOutputStream((OutputStream) objectDataOutput); out.writeObject(object); out.flush(); } public Object read(ObjectDataInput objectDataInput) - throws IOException { + throws IOException { ObjectInputStream in = new ObjectInputStream((InputStream) objectDataInput); try { return in.readObject(); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { throw new IOException(e); } } diff --git a/samples/hazelcast/src/main/java/sample/SessionServlet.java b/samples/hazelcast/src/main/java/sample/SessionServlet.java index 95924600..f7560ef5 100644 --- a/samples/hazelcast/src/main/java/sample/SessionServlet.java +++ b/samples/hazelcast/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; +import java.io.IOException; + import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * @author Rob Winch diff --git a/samples/httpsession-gemfire-clientserver-xml/src/integration-test/groovy/sample/AttributeTests.groovy b/samples/httpsession-gemfire-clientserver-xml/src/integration-test/groovy/sample/AttributeTests.groovy index a5f85c86..c865fc43 100644 --- a/samples/httpsession-gemfire-clientserver-xml/src/integration-test/groovy/sample/AttributeTests.groovy +++ b/samples/httpsession-gemfire-clientserver-xml/src/integration-test/groovy/sample/AttributeTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -42,4 +43,4 @@ class AttributeTests extends GebReportingSpec { attributes[0].name == 'a' attributes[0].value == 'b' } -} \ No newline at end of file +} diff --git a/samples/httpsession-gemfire-clientserver-xml/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/httpsession-gemfire-clientserver-xml/src/integration-test/groovy/sample/pages/HomePage.groovy index e087b5c4..25215292 100644 --- a/samples/httpsession-gemfire-clientserver-xml/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/httpsession-gemfire-clientserver-xml/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/Application.java b/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/Application.java index c47fa628..0ca3a875 100644 --- a/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/Application.java +++ b/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/Application.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/GemFireCacheServerReadyBeanPostProcessor.java b/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/GemFireCacheServerReadyBeanPostProcessor.java index 570d35b7..9b962d3c 100644 --- a/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/GemFireCacheServerReadyBeanPostProcessor.java +++ b/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/GemFireCacheServerReadyBeanPostProcessor.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; @@ -21,8 +22,14 @@ import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; + import javax.annotation.Resource; +import com.gemstone.gemfire.cache.client.Pool; +import com.gemstone.gemfire.management.membership.ClientMembership; +import com.gemstone.gemfire.management.membership.ClientMembershipEvent; +import com.gemstone.gemfire.management.membership.ClientMembershipListenerAdapter; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -30,15 +37,10 @@ import org.springframework.data.gemfire.client.PoolFactoryBean; import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.util.Assert; -import com.gemstone.gemfire.cache.client.Pool; -import com.gemstone.gemfire.management.membership.ClientMembership; -import com.gemstone.gemfire.management.membership.ClientMembershipEvent; -import com.gemstone.gemfire.management.membership.ClientMembershipListenerAdapter; - public class GemFireCacheServerReadyBeanPostProcessor implements BeanPostProcessor { static final long DEFAULT_WAIT_DURATION = TimeUnit.SECONDS.toMillis(20); - static final long DEFAULT_WAIT_INTERVAL = 500l; + static final long DEFAULT_WAIT_INTERVAL = 500L; static final CountDownLatch latch = new CountDownLatch(1); @@ -65,8 +67,8 @@ public class GemFireCacheServerReadyBeanPostProcessor implements BeanPostProcess public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof PoolFactoryBean || bean instanceof Pool) { String host = getServerHost(DEFAULT_SERVER_HOST); - Assert.isTrue(waitForCacheServerToStart(host, port), String.format( - "GemFire Server failed to start [host: '%1$s', port: %2$d]%n", host, port)); + Assert.isTrue(waitForCacheServerToStart(host, this.port), String.format( + "GemFire Server failed to start [host: '%1$s', port: %2$d]%n", host, this.port)); } return bean; @@ -91,7 +93,7 @@ public class GemFireCacheServerReadyBeanPostProcessor implements BeanPostProcess } String getServerHost(String defaultServerHost) { - return applicationProperties.getProperty("application.gemfire.client-server.host", defaultServerHost); + return this.applicationProperties.getProperty("application.gemfire.client-server.host", defaultServerHost); } boolean waitForCacheServerToStart(String host, int port) { diff --git a/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/SessionServlet.java b/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/SessionServlet.java index cac9108c..b030339b 100644 --- a/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/SessionServlet.java +++ b/samples/httpsession-gemfire-clientserver-xml/src/main/java/sample/SessionServlet.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; + import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; diff --git a/samples/httpsession-gemfire-clientserver/src/integration-test/groovy/sample/AttributeTests.groovy b/samples/httpsession-gemfire-clientserver/src/integration-test/groovy/sample/AttributeTests.groovy index a5f85c86..c865fc43 100644 --- a/samples/httpsession-gemfire-clientserver/src/integration-test/groovy/sample/AttributeTests.groovy +++ b/samples/httpsession-gemfire-clientserver/src/integration-test/groovy/sample/AttributeTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -42,4 +43,4 @@ class AttributeTests extends GebReportingSpec { attributes[0].name == 'a' attributes[0].value == 'b' } -} \ No newline at end of file +} diff --git a/samples/httpsession-gemfire-clientserver/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/httpsession-gemfire-clientserver/src/integration-test/groovy/sample/pages/HomePage.groovy index e087b5c4..25215292 100644 --- a/samples/httpsession-gemfire-clientserver/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/httpsession-gemfire-clientserver/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/httpsession-gemfire-clientserver/src/main/java/sample/ClientConfig.java b/samples/httpsession-gemfire-clientserver/src/main/java/sample/ClientConfig.java index 1d0d2c72..1b5ecdde 100644 --- a/samples/httpsession-gemfire-clientserver/src/main/java/sample/ClientConfig.java +++ b/samples/httpsession-gemfire-clientserver/src/main/java/sample/ClientConfig.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; @@ -23,6 +24,11 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import com.gemstone.gemfire.cache.client.Pool; +import com.gemstone.gemfire.management.membership.ClientMembership; +import com.gemstone.gemfire.management.membership.ClientMembershipEvent; +import com.gemstone.gemfire.management.membership.ClientMembershipListenerAdapter; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -36,17 +42,12 @@ import org.springframework.session.data.gemfire.config.annotation.web.http.Enabl import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.util.Assert; -import com.gemstone.gemfire.cache.client.Pool; -import com.gemstone.gemfire.management.membership.ClientMembership; -import com.gemstone.gemfire.management.membership.ClientMembershipEvent; -import com.gemstone.gemfire.management.membership.ClientMembershipListenerAdapter; - // tag::class[] @EnableGemFireHttpSession(maxInactiveIntervalInSeconds = 30) // <1> public class ClientConfig { static final long DEFAULT_WAIT_DURATION = TimeUnit.SECONDS.toMillis(20); - static final long DEFAULT_WAIT_INTERVAL = 500l; + static final long DEFAULT_WAIT_INTERVAL = 500L; static final CountDownLatch latch = new CountDownLatch(1); @@ -75,8 +76,8 @@ public class ClientConfig { } @Bean(name = GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME) - PoolFactoryBean gemfirePool( // <3> - @Value("${spring.session.data.gemfire.port:"+ServerConfig.SERVER_PORT+"}") int port) { + PoolFactoryBean gemfirePool(// <3> + @Value("${spring.session.data.gemfire.port:" + ServerConfig.SERVER_PORT + "}") int port) { PoolFactoryBean poolFactory = new PoolFactoryBean(); @@ -109,8 +110,8 @@ public class ClientConfig { } @Bean - BeanPostProcessor gemfireCacheServerReadyBeanPostProcessor( // <5> - @Value("${spring.session.data.gemfire.port:"+ServerConfig.SERVER_PORT+"}") final int port) { + BeanPostProcessor gemfireCacheServerReadyBeanPostProcessor(// <5> + @Value("${spring.session.data.gemfire.port:" + ServerConfig.SERVER_PORT + "}") final int port) { return new BeanPostProcessor() { diff --git a/samples/httpsession-gemfire-clientserver/src/main/java/sample/Initializer.java b/samples/httpsession-gemfire-clientserver/src/main/java/sample/Initializer.java index 3690e0a3..533b1c76 100644 --- a/samples/httpsession-gemfire-clientserver/src/main/java/sample/Initializer.java +++ b/samples/httpsession-gemfire-clientserver/src/main/java/sample/Initializer.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; diff --git a/samples/httpsession-gemfire-clientserver/src/main/java/sample/ServerConfig.java b/samples/httpsession-gemfire-clientserver/src/main/java/sample/ServerConfig.java index 832f4a46..1498d414 100644 --- a/samples/httpsession-gemfire-clientserver/src/main/java/sample/ServerConfig.java +++ b/samples/httpsession-gemfire-clientserver/src/main/java/sample/ServerConfig.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,11 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; import java.util.Properties; +import com.gemstone.gemfire.cache.Cache; + import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -26,8 +29,6 @@ import org.springframework.data.gemfire.CacheFactoryBean; import org.springframework.data.gemfire.server.CacheServerFactoryBean; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; -import com.gemstone.gemfire.cache.Cache; - // tag::class[] @EnableGemFireHttpSession(maxInactiveIntervalInSeconds = 30)// <1> public class ServerConfig { @@ -68,7 +69,7 @@ public class ServerConfig { @Bean CacheServerFactoryBean gemfireCacheServer(Cache gemfireCache, // <4> - @Value("${spring.session.data.gemfire.port:"+SERVER_PORT+"}") int port) { + @Value("${spring.session.data.gemfire.port:" + SERVER_PORT + "}") int port) { CacheServerFactoryBean cacheServerFactory = new CacheServerFactoryBean(); diff --git a/samples/httpsession-gemfire-clientserver/src/main/java/sample/SessionServlet.java b/samples/httpsession-gemfire-clientserver/src/main/java/sample/SessionServlet.java index 07b22e04..98f3ae85 100644 --- a/samples/httpsession-gemfire-clientserver/src/main/java/sample/SessionServlet.java +++ b/samples/httpsession-gemfire-clientserver/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; + import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; diff --git a/samples/httpsession-gemfire-p2p-xml/src/integration-test/groovy/sample/AttributeTests.groovy b/samples/httpsession-gemfire-p2p-xml/src/integration-test/groovy/sample/AttributeTests.groovy index a5f85c86..c865fc43 100644 --- a/samples/httpsession-gemfire-p2p-xml/src/integration-test/groovy/sample/AttributeTests.groovy +++ b/samples/httpsession-gemfire-p2p-xml/src/integration-test/groovy/sample/AttributeTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -42,4 +43,4 @@ class AttributeTests extends GebReportingSpec { attributes[0].name == 'a' attributes[0].value == 'b' } -} \ No newline at end of file +} diff --git a/samples/httpsession-gemfire-p2p-xml/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/httpsession-gemfire-p2p-xml/src/integration-test/groovy/sample/pages/HomePage.groovy index e087b5c4..25215292 100644 --- a/samples/httpsession-gemfire-p2p-xml/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/httpsession-gemfire-p2p-xml/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/httpsession-gemfire-p2p-xml/src/main/java/sample/SessionServlet.java b/samples/httpsession-gemfire-p2p-xml/src/main/java/sample/SessionServlet.java index 478d53b0..f37983be 100644 --- a/samples/httpsession-gemfire-p2p-xml/src/main/java/sample/SessionServlet.java +++ b/samples/httpsession-gemfire-p2p-xml/src/main/java/sample/SessionServlet.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; + import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; diff --git a/samples/httpsession-gemfire-p2p/src/integration-test/groovy/sample/AttributeTests.groovy b/samples/httpsession-gemfire-p2p/src/integration-test/groovy/sample/AttributeTests.groovy index a5f85c86..c865fc43 100644 --- a/samples/httpsession-gemfire-p2p/src/integration-test/groovy/sample/AttributeTests.groovy +++ b/samples/httpsession-gemfire-p2p/src/integration-test/groovy/sample/AttributeTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -42,4 +43,4 @@ class AttributeTests extends GebReportingSpec { attributes[0].name == 'a' attributes[0].value == 'b' } -} \ No newline at end of file +} diff --git a/samples/httpsession-gemfire-p2p/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/httpsession-gemfire-p2p/src/integration-test/groovy/sample/pages/HomePage.groovy index e087b5c4..25215292 100644 --- a/samples/httpsession-gemfire-p2p/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/httpsession-gemfire-p2p/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/httpsession-gemfire-p2p/src/main/java/sample/Config.java b/samples/httpsession-gemfire-p2p/src/main/java/sample/Config.java index 66f53b62..ca622484 100644 --- a/samples/httpsession-gemfire-p2p/src/main/java/sample/Config.java +++ b/samples/httpsession-gemfire-p2p/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.util.Properties; diff --git a/samples/httpsession-gemfire-p2p/src/main/java/sample/Initializer.java b/samples/httpsession-gemfire-p2p/src/main/java/sample/Initializer.java index 7512f33c..508db307 100644 --- a/samples/httpsession-gemfire-p2p/src/main/java/sample/Initializer.java +++ b/samples/httpsession-gemfire-p2p/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; @@ -25,4 +26,4 @@ public class Initializer super(Config.class); // <2> } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/httpsession-gemfire-p2p/src/main/java/sample/SessionServlet.java b/samples/httpsession-gemfire-p2p/src/main/java/sample/SessionServlet.java index 07b22e04..98f3ae85 100644 --- a/samples/httpsession-gemfire-p2p/src/main/java/sample/SessionServlet.java +++ b/samples/httpsession-gemfire-p2p/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; + import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; diff --git a/samples/httpsession-xml/src/integration-test/groovy/sample/AttributeTests.groovy b/samples/httpsession-xml/src/integration-test/groovy/sample/AttributeTests.groovy index a5f85c86..c865fc43 100644 --- a/samples/httpsession-xml/src/integration-test/groovy/sample/AttributeTests.groovy +++ b/samples/httpsession-xml/src/integration-test/groovy/sample/AttributeTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -42,4 +43,4 @@ class AttributeTests extends GebReportingSpec { attributes[0].name == 'a' attributes[0].value == 'b' } -} \ No newline at end of file +} diff --git a/samples/httpsession-xml/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/httpsession-xml/src/integration-test/groovy/sample/pages/HomePage.groovy index e087b5c4..25215292 100644 --- a/samples/httpsession-xml/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/httpsession-xml/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/httpsession-xml/src/main/java/sample/SessionServlet.java b/samples/httpsession-xml/src/main/java/sample/SessionServlet.java index d93d6320..8ceb344f 100644 --- a/samples/httpsession-xml/src/main/java/sample/SessionServlet.java +++ b/samples/httpsession-xml/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; -import javax.servlet.*; -import javax.servlet.http.*; import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + // tag::class[] public class SessionServlet extends HttpServlet { @@ -33,4 +37,4 @@ public class SessionServlet extends HttpServlet { private static final long serialVersionUID = 2878267318695777395L; } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/httpsession/src/integration-test/groovy/sample/AttributeTests.groovy b/samples/httpsession/src/integration-test/groovy/sample/AttributeTests.groovy index a5f85c86..c865fc43 100644 --- a/samples/httpsession/src/integration-test/groovy/sample/AttributeTests.groovy +++ b/samples/httpsession/src/integration-test/groovy/sample/AttributeTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -42,4 +43,4 @@ class AttributeTests extends GebReportingSpec { attributes[0].name == 'a' attributes[0].value == 'b' } -} \ No newline at end of file +} diff --git a/samples/httpsession/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/httpsession/src/integration-test/groovy/sample/pages/HomePage.groovy index e087b5c4..25215292 100644 --- a/samples/httpsession/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/httpsession/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/httpsession/src/main/java/sample/Config.java b/samples/httpsession/src/main/java/sample/Config.java index 6cf4ddfc..d33bb287 100644 --- a/samples/httpsession/src/main/java/sample/Config.java +++ b/samples/httpsession/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.context.annotation.Bean; @@ -28,4 +29,4 @@ public class Config { return new JedisConnectionFactory(); // <2> } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/httpsession/src/main/java/sample/Initializer.java b/samples/httpsession/src/main/java/sample/Initializer.java index 7512f33c..508db307 100644 --- a/samples/httpsession/src/main/java/sample/Initializer.java +++ b/samples/httpsession/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; @@ -25,4 +26,4 @@ public class Initializer super(Config.class); // <2> } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/httpsession/src/main/java/sample/SessionServlet.java b/samples/httpsession/src/main/java/sample/SessionServlet.java index f0a8d6dc..95fc103a 100644 --- a/samples/httpsession/src/main/java/sample/SessionServlet.java +++ b/samples/httpsession/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; -import javax.servlet.*; -import javax.servlet.annotation.*; -import javax.servlet.http.*; import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + // tag::class[] @WebServlet("/session") public class SessionServlet extends HttpServlet { @@ -34,4 +38,4 @@ public class SessionServlet extends HttpServlet { private static final long serialVersionUID = 2878267318695777395L; } -// tag::end[] \ No newline at end of file +// tag::end[] diff --git a/samples/rest/src/integration-test/groovy/sample/RestTests.groovy b/samples/rest/src/integration-test/groovy/sample/RestTests.groovy index 39016b6c..7ac41007 100644 --- a/samples/rest/src/integration-test/groovy/sample/RestTests.groovy +++ b/samples/rest/src/integration-test/groovy/sample/RestTests.groovy @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import groovyx.net.http.HttpResponseException @@ -82,4 +83,4 @@ class RestTests extends Specification { response.status == HttpServletResponse.SC_NO_CONTENT session == '' } -} \ No newline at end of file +} diff --git a/samples/rest/src/integration-test/java/rest/RestMockMvcTests.java b/samples/rest/src/integration-test/java/rest/RestMockMvcTests.java index cf994bd7..efab86cf 100644 --- a/samples/rest/src/integration-test/java/rest/RestMockMvcTests.java +++ b/samples/rest/src/integration-test/java/rest/RestMockMvcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package rest; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; -import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; +package rest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + +import sample.HttpSessionConfig; +import sample.SecurityConfig; +import sample.mvc.MvcConfig; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.session.ExpiringSession; @@ -35,13 +35,17 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import sample.HttpSessionConfig; -import sample.SecurityConfig; -import sample.mvc.MvcConfig; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes= {HttpSessionConfig.class,SecurityConfig.class, MvcConfig.class}) +@ContextConfiguration(classes = {HttpSessionConfig.class, SecurityConfig.class, MvcConfig.class}) @WebAppConfiguration public class RestMockMvcTests { @@ -55,16 +59,16 @@ public class RestMockMvcTests { @Before public void setup() { - mvc = MockMvcBuilders.webAppContextSetup(context) + this.mvc = MockMvcBuilders.webAppContextSetup(this.context) .alwaysDo(print()) - .addFilters(sessionRepositoryFilter) + .addFilters(this.sessionRepositoryFilter) .apply(springSecurity()) .build(); } @Test public void noSessionOnNoCredentials() throws Exception { - mvc.perform(get("/")) + this.mvc.perform(get("/")) .andExpect(header().doesNotExist("x-auth-token")) .andExpect(status().isUnauthorized()); } @@ -72,14 +76,14 @@ public class RestMockMvcTests { @WithMockUser @Test public void autheticatedAnnotation() throws Exception { - mvc.perform(get("/")) + this.mvc.perform(get("/")) .andExpect(content().string("{\"username\":\"user\"}")); } @Test public void autheticatedRequestPostProcessor() throws Exception { - mvc.perform(get("/").with(user("user"))) + this.mvc.perform(get("/").with(user("user"))) .andExpect(content().string("{\"username\":\"user\"}")); } diff --git a/samples/rest/src/main/java/sample/HttpSessionConfig.java b/samples/rest/src/main/java/sample/HttpSessionConfig.java index 5ef3a6c3..f7ef6859 100644 --- a/samples/rest/src/main/java/sample/HttpSessionConfig.java +++ b/samples/rest/src/main/java/sample/HttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.context.annotation.Bean; @@ -37,4 +38,4 @@ public class HttpSessionConfig { return new HeaderHttpSessionStrategy(); // <3> } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/rest/src/main/java/sample/Initializer.java b/samples/rest/src/main/java/sample/Initializer.java index f8627a7f..6970e506 100644 --- a/samples/rest/src/main/java/sample/Initializer.java +++ b/samples/rest/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; @@ -21,4 +22,4 @@ import org.springframework.session.web.context.AbstractHttpSessionApplicationIni public class Initializer extends AbstractHttpSessionApplicationInitializer { } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/rest/src/main/java/sample/SecurityConfig.java b/samples/rest/src/main/java/sample/SecurityConfig.java index 0df88acb..dc452d1e 100644 --- a/samples/rest/src/main/java/sample/SecurityConfig.java +++ b/samples/rest/src/main/java/sample/SecurityConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; import org.springframework.beans.factory.annotation.Autowired; diff --git a/samples/rest/src/main/java/sample/SecurityInitializer.java b/samples/rest/src/main/java/sample/SecurityInitializer.java index 754f3b44..4faac92d 100644 --- a/samples/rest/src/main/java/sample/SecurityInitializer.java +++ b/samples/rest/src/main/java/sample/SecurityInitializer.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; @@ -23,4 +24,4 @@ import org.springframework.security.web.context.AbstractSecurityWebApplicationIn public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { -} \ No newline at end of file +} diff --git a/samples/rest/src/main/java/sample/mvc/MvcConfig.java b/samples/rest/src/main/java/sample/mvc/MvcConfig.java index b1d60737..40842ec7 100644 --- a/samples/rest/src/main/java/sample/mvc/MvcConfig.java +++ b/samples/rest/src/main/java/sample/mvc/MvcConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.mvc; import org.springframework.context.annotation.ComponentScan; diff --git a/samples/rest/src/main/java/sample/mvc/MvcInitializer.java b/samples/rest/src/main/java/sample/mvc/MvcInitializer.java index 6c88c72c..c79c2d68 100644 --- a/samples/rest/src/main/java/sample/mvc/MvcInitializer.java +++ b/samples/rest/src/main/java/sample/mvc/MvcInitializer.java @@ -1,24 +1,26 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.mvc; -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import sample.HttpSessionConfig; import sample.SecurityConfig; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + /** * @author Rob Winch */ diff --git a/samples/rest/src/main/java/sample/mvc/RestDemoController.java b/samples/rest/src/main/java/sample/mvc/RestDemoController.java index 08ca0585..58e2a502 100644 --- a/samples/rest/src/main/java/sample/mvc/RestDemoController.java +++ b/samples/rest/src/main/java/sample/mvc/RestDemoController.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.mvc; import java.security.Principal; @@ -32,9 +33,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class RestDemoController { - @RequestMapping(value="/",produces = "application/json") - public Map helloUser(Principal principal) { - HashMap result = new HashMap(); + @RequestMapping(value = "/", produces = "application/json") + public Map helloUser(Principal principal) { + HashMap result = new HashMap(); result.put("username", principal.getName()); return result; } diff --git a/samples/security/src/integration-test/groovy/sample/SecurityTests.groovy b/samples/security/src/integration-test/groovy/sample/SecurityTests.groovy index 5dd53f12..340fdc5a 100644 --- a/samples/security/src/integration-test/groovy/sample/SecurityTests.groovy +++ b/samples/security/src/integration-test/groovy/sample/SecurityTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.GebReportingSpec @@ -62,4 +63,4 @@ class SecurityTests extends GebReportingSpec { then: 'sent to the log in page' at LoginPage } -} \ No newline at end of file +} diff --git a/samples/security/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/security/src/integration-test/groovy/sample/pages/HomePage.groovy index 45634e66..b98a276e 100644 --- a/samples/security/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/security/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.Page diff --git a/samples/security/src/integration-test/groovy/sample/pages/LoginPage.groovy b/samples/security/src/integration-test/groovy/sample/pages/LoginPage.groovy index 08c7fb27..d8a5beaf 100644 --- a/samples/security/src/integration-test/groovy/sample/pages/LoginPage.groovy +++ b/samples/security/src/integration-test/groovy/sample/pages/LoginPage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.Page diff --git a/samples/security/src/main/java/sample/Config.java b/samples/security/src/main/java/sample/Config.java index 33e3218b..ecfa7bfe 100644 --- a/samples/security/src/main/java/sample/Config.java +++ b/samples/security/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.context.annotation.Bean; @@ -30,4 +31,4 @@ public class Config { return new JedisConnectionFactory(); // <2> } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/security/src/main/java/sample/Initializer.java b/samples/security/src/main/java/sample/Initializer.java index f8627a7f..6970e506 100644 --- a/samples/security/src/main/java/sample/Initializer.java +++ b/samples/security/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; @@ -21,4 +22,4 @@ import org.springframework.session.web.context.AbstractHttpSessionApplicationIni public class Initializer extends AbstractHttpSessionApplicationInitializer { } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/security/src/main/java/sample/SecurityConfig.java b/samples/security/src/main/java/sample/SecurityConfig.java index e6c5da8c..47487c9e 100644 --- a/samples/security/src/main/java/sample/SecurityConfig.java +++ b/samples/security/src/main/java/sample/SecurityConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; /** diff --git a/samples/security/src/main/java/sample/SecurityInitializer.java b/samples/security/src/main/java/sample/SecurityInitializer.java index 7cb5982d..8122d211 100644 --- a/samples/security/src/main/java/sample/SecurityInitializer.java +++ b/samples/security/src/main/java/sample/SecurityInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; @@ -25,4 +26,4 @@ public class SecurityInitializer extends super(SecurityConfig.class, Config.class); } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/security/src/main/java/sample/SessionServlet.java b/samples/security/src/main/java/sample/SessionServlet.java index 2d56ce48..16e60bb6 100644 --- a/samples/security/src/main/java/sample/SessionServlet.java +++ b/samples/security/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; +import java.io.IOException; + import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; @WebServlet("/session") public class SessionServlet extends HttpServlet { diff --git a/samples/users/src/integration-test/groovy/sample/UserTests.groovy b/samples/users/src/integration-test/groovy/sample/UserTests.groovy index 46aa5c61..dc16e84e 100644 --- a/samples/users/src/integration-test/groovy/sample/UserTests.groovy +++ b/samples/users/src/integration-test/groovy/sample/UserTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample import geb.spock.* @@ -140,4 +141,4 @@ class UserTests extends GebReportingSpec { then: !username } -} \ No newline at end of file +} diff --git a/samples/users/src/integration-test/groovy/sample/pages/HomePage.groovy b/samples/users/src/integration-test/groovy/sample/pages/HomePage.groovy index 47e2bd4f..f1b34d89 100644 --- a/samples/users/src/integration-test/groovy/sample/pages/HomePage.groovy +++ b/samples/users/src/integration-test/groovy/sample/pages/HomePage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/users/src/integration-test/groovy/sample/pages/LinkPage.groovy b/samples/users/src/integration-test/groovy/sample/pages/LinkPage.groovy index 13fc7143..c8c19953 100644 --- a/samples/users/src/integration-test/groovy/sample/pages/LinkPage.groovy +++ b/samples/users/src/integration-test/groovy/sample/pages/LinkPage.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.pages import geb.* diff --git a/samples/users/src/main/java/sample/Account.java b/samples/users/src/main/java/sample/Account.java index b0348f5d..e09d75f6 100644 --- a/samples/users/src/main/java/sample/Account.java +++ b/samples/users/src/main/java/sample/Account.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; public class Account { @@ -30,15 +31,15 @@ public class Account { } public String getUsername() { - return username; + return this.username; } public String getLogoutUrl() { - return logoutUrl; + return this.logoutUrl; } public String getSwitchAccountUrl() { - return switchAccountUrl; + return this.switchAccountUrl; } } diff --git a/samples/users/src/main/java/sample/Config.java b/samples/users/src/main/java/sample/Config.java index 98c25753..8573d259 100644 --- a/samples/users/src/main/java/sample/Config.java +++ b/samples/users/src/main/java/sample/Config.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; import org.springframework.context.annotation.Bean; @@ -34,4 +35,4 @@ public class Config { return new JedisConnectionFactory(); } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/users/src/main/java/sample/Initializer.java b/samples/users/src/main/java/sample/Initializer.java index 8bc0289d..e1ce9694 100644 --- a/samples/users/src/main/java/sample/Initializer.java +++ b/samples/users/src/main/java/sample/Initializer.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; import javax.servlet.ServletContext; @@ -32,4 +33,4 @@ public class Initializer extends AbstractHttpSessionApplicationInitializer { protected void afterSessionRepositoryFilter(ServletContext servletContext) { appendFilters(servletContext, new UserAccountsFilter()); } -} \ No newline at end of file +} diff --git a/samples/users/src/main/java/sample/LoginServlet.java b/samples/users/src/main/java/sample/LoginServlet.java index 856a19e7..59e0837f 100644 --- a/samples/users/src/main/java/sample/LoginServlet.java +++ b/samples/users/src/main/java/sample/LoginServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; @@ -32,15 +33,16 @@ public class LoginServlet extends HttpServlet { String username = req.getParameter("username"); String password = req.getParameter("password"); - if(username != null && !"".equals(username) && username.equals(password)) { + if (username != null && !"".equals(username) && username.equals(password)) { req.getSession().setAttribute("username", username); String url = resp.encodeRedirectURL(req.getContextPath() + "/"); resp.sendRedirect(url); - } else { + } + else { String url = resp.encodeRedirectURL(req.getContextPath() + "/?error"); resp.sendRedirect(url); } } private static final long serialVersionUID = -8157634860354132501L; -} \ No newline at end of file +} diff --git a/samples/users/src/main/java/sample/LogoutServlet.java b/samples/users/src/main/java/sample/LogoutServlet.java index 3f91ae46..f17ee20a 100644 --- a/samples/users/src/main/java/sample/LogoutServlet.java +++ b/samples/users/src/main/java/sample/LogoutServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; @@ -31,7 +32,7 @@ public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(false); - if(session != null) { + if (session != null) { session.invalidate(); } String url = resp.encodeRedirectURL(req.getContextPath() + "/"); @@ -39,4 +40,4 @@ public class LogoutServlet extends HttpServlet { } private static final long serialVersionUID = 4061762524521437433L; -} \ No newline at end of file +} diff --git a/samples/users/src/main/java/sample/UserAccountsFilter.java b/samples/users/src/main/java/sample/UserAccountsFilter.java index 88721b1b..77d35ed7 100644 --- a/samples/users/src/main/java/sample/UserAccountsFilter.java +++ b/samples/users/src/main/java/sample/UserAccountsFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample; import java.io.IOException; @@ -56,17 +57,17 @@ public class UserAccountsFilter implements Filter { String contextPath = httpRequest.getContextPath(); List accounts = new ArrayList(); Account currentAccount = null; - for(Map.Entry entry : sessionIds.entrySet()) { + for (Map.Entry entry : sessionIds.entrySet()) { String alias = entry.getKey(); String sessionId = entry.getValue(); Session session = repo.getSession(sessionId); - if(session == null) { + if (session == null) { continue; } String username = session.getAttribute("username"); - if(username == null) { + if (username == null) { unauthenticatedAlias = alias; continue; } @@ -74,9 +75,10 @@ public class UserAccountsFilter implements Filter { String logoutUrl = sessionManager.encodeURL("./logout", alias); String switchAccountUrl = sessionManager.encodeURL("./", alias); Account account = new Account(username, logoutUrl, switchAccountUrl); - if(currentSessionAlias.equals(alias)) { + if (currentSessionAlias.equals(alias)) { currentAccount = account; - } else { + } + else { accounts.add(account); } } diff --git a/samples/websocket/src/main/java/sample/Application.java b/samples/websocket/src/main/java/sample/Application.java index 7646ee50..973e145b 100644 --- a/samples/websocket/src/main/java/sample/Application.java +++ b/samples/websocket/src/main/java/sample/Application.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample; import org.springframework.boot.SpringApplication; diff --git a/samples/websocket/src/main/java/sample/config/DataSourceConfig.java b/samples/websocket/src/main/java/sample/config/DataSourceConfig.java index 7c1f60f1..2ac6e04a 100644 --- a/samples/websocket/src/main/java/sample/config/DataSourceConfig.java +++ b/samples/websocket/src/main/java/sample/config/DataSourceConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.config; import javax.sql.DataSource; diff --git a/samples/websocket/src/main/java/sample/config/H2Initializer.java b/samples/websocket/src/main/java/sample/config/H2Initializer.java index bdc7a0ae..4f136fee 100644 --- a/samples/websocket/src/main/java/sample/config/H2Initializer.java +++ b/samples/websocket/src/main/java/sample/config/H2Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.config; import org.h2.server.web.WebServlet; + import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/samples/websocket/src/main/java/sample/config/WebSecurityConfig.java b/samples/websocket/src/main/java/sample/config/WebSecurityConfig.java index 4f787e43..c185387f 100644 --- a/samples/websocket/src/main/java/sample/config/WebSecurityConfig.java +++ b/samples/websocket/src/main/java/sample/config/WebSecurityConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.config; import org.springframework.beans.factory.annotation.Autowired; @@ -64,4 +65,4 @@ public class WebSecurityConfig public SecurityEvaluationContextExtension securityEvaluationContextExtension() { return new SecurityEvaluationContextExtension(); } -} \ No newline at end of file +} diff --git a/samples/websocket/src/main/java/sample/config/WebSocketConfig.java b/samples/websocket/src/main/java/sample/config/WebSocketConfig.java index 63ffab44..63270d59 100644 --- a/samples/websocket/src/main/java/sample/config/WebSocketConfig.java +++ b/samples/websocket/src/main/java/sample/config/WebSocketConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.config; import org.springframework.context.annotation.Configuration; @@ -28,7 +29,7 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @EnableScheduling @EnableWebSocketMessageBroker public class WebSocketConfig - extends AbstractSessionWebSocketMessageBrokerConfigurer { // <1> + extends AbstractSessionWebSocketMessageBrokerConfigurer { // <1> protected void configureStompEndpoints(StompEndpointRegistry registry) { // <2> registry.addEndpoint("/messages") @@ -40,4 +41,4 @@ public class WebSocketConfig registry.setApplicationDestinationPrefixes("/app"); } } -// end::class[] \ No newline at end of file +// end::class[] diff --git a/samples/websocket/src/main/java/sample/config/WebSocketHandlersConfig.java b/samples/websocket/src/main/java/sample/config/WebSocketHandlersConfig.java index 65378c72..949381e9 100644 --- a/samples/websocket/src/main/java/sample/config/WebSocketHandlersConfig.java +++ b/samples/websocket/src/main/java/sample/config/WebSocketHandlersConfig.java @@ -1,28 +1,29 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.config; +import sample.data.ActiveWebSocketUserRepository; +import sample.websocket.WebSocketConnectHandler; +import sample.websocket.WebSocketDisconnectHandler; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.session.ExpiringSession; -import sample.data.ActiveWebSocketUserRepository; -import sample.websocket.WebSocketConnectHandler; -import sample.websocket.WebSocketDisconnectHandler; - /** * These handlers are separated from WebSocketConfig because they are specific to this application and do not demonstrate a typical Spring Session setup. * diff --git a/samples/websocket/src/main/java/sample/config/WebSocketSecurityConfig.java b/samples/websocket/src/main/java/sample/config/WebSocketSecurityConfig.java index d159ae35..11ef2557 100644 --- a/samples/websocket/src/main/java/sample/config/WebSocketSecurityConfig.java +++ b/samples/websocket/src/main/java/sample/config/WebSocketSecurityConfig.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.config; import org.springframework.context.annotation.Configuration; @@ -29,9 +30,9 @@ public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBro @Override protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { messages - .simpMessageDestMatchers("/queue/**","/topic/**").denyAll() - .simpSubscribeDestMatchers("/queue/**/*-user*","/topic/**/*-user*").denyAll() + .simpMessageDestMatchers("/queue/**", "/topic/**").denyAll() + .simpSubscribeDestMatchers("/queue/**/*-user*", "/topic/**/*-user*").denyAll() .anyMessage().authenticated(); } // @formatter:on -} \ No newline at end of file +} diff --git a/samples/websocket/src/main/java/sample/data/ActiveWebSocketUser.java b/samples/websocket/src/main/java/sample/data/ActiveWebSocketUser.java index 0352ee0f..ef953f01 100644 --- a/samples/websocket/src/main/java/sample/data/ActiveWebSocketUser.java +++ b/samples/websocket/src/main/java/sample/data/ActiveWebSocketUser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.data; import java.util.Calendar; @@ -29,7 +30,8 @@ public class ActiveWebSocketUser { private Calendar connectionTime; - public ActiveWebSocketUser() {} + public ActiveWebSocketUser() { + } public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { super(); @@ -39,7 +41,7 @@ public class ActiveWebSocketUser { } public String getUsername() { - return username; + return this.username; } public void setUsername(String username) { @@ -47,7 +49,7 @@ public class ActiveWebSocketUser { } public Calendar getConnectionTime() { - return connectionTime; + return this.connectionTime; } public void setConnectionTime(Calendar connectionTime) { diff --git a/samples/websocket/src/main/java/sample/data/ActiveWebSocketUserRepository.java b/samples/websocket/src/main/java/sample/data/ActiveWebSocketUserRepository.java index fad2c3c6..8123d3e8 100644 --- a/samples/websocket/src/main/java/sample/data/ActiveWebSocketUserRepository.java +++ b/samples/websocket/src/main/java/sample/data/ActiveWebSocketUserRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.data; import java.util.List; @@ -20,7 +21,7 @@ import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; -public interface ActiveWebSocketUserRepository extends CrudRepository { +public interface ActiveWebSocketUserRepository extends CrudRepository { @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != ?#{principal?.username}") List findAllActiveUsers(); diff --git a/samples/websocket/src/main/java/sample/data/InstantMessage.java b/samples/websocket/src/main/java/sample/data/InstantMessage.java index b8e1b8a1..44fca39a 100644 --- a/samples/websocket/src/main/java/sample/data/InstantMessage.java +++ b/samples/websocket/src/main/java/sample/data/InstantMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.data; import java.util.Calendar; @@ -27,7 +28,7 @@ public class InstantMessage { private Calendar created = Calendar.getInstance(); public String getTo() { - return to; + return this.to; } public void setTo(String to) { @@ -35,7 +36,7 @@ public class InstantMessage { } public String getFrom() { - return from; + return this.from; } public void setFrom(String from) { @@ -43,7 +44,7 @@ public class InstantMessage { } public String getMessage() { - return message; + return this.message; } public void setMessage(String message) { @@ -51,7 +52,7 @@ public class InstantMessage { } public Calendar getCreated() { - return created; + return this.created; } public void setCreated(Calendar created) { diff --git a/samples/websocket/src/main/java/sample/data/User.java b/samples/websocket/src/main/java/sample/data/User.java index 541ba209..ffec2fa7 100644 --- a/samples/websocket/src/main/java/sample/data/User.java +++ b/samples/websocket/src/main/java/sample/data/User.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.data; import java.io.Serializable; @@ -25,6 +26,7 @@ import javax.persistence.Id; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; + import org.springframework.security.crypto.password.PasswordEncoder; /** @@ -52,13 +54,14 @@ public class User implements Serializable { @Email(message = "Please provide a valid email address.") @NotEmpty(message = "Email is required.") - @Column(unique=true, nullable = false) + @Column(unique = true, nullable = false) private String email; @NotEmpty(message = "Password is required.") private String password; - public User() {} + public User() { + } public User(User user) { this.id = user.id; @@ -69,7 +72,7 @@ public class User implements Serializable { } public String getPassword() { - return password; + return this.password; } public void setPassword(String password) { @@ -77,7 +80,7 @@ public class User implements Serializable { } public Long getId() { - return id; + return this.id; } public void setId(Long id) { @@ -85,7 +88,7 @@ public class User implements Serializable { } public String getFirstName() { - return firstName; + return this.firstName; } public void setFirstName(String firstName) { @@ -93,7 +96,7 @@ public class User implements Serializable { } public String getLastName() { - return lastName; + return this.lastName; } public void setLastName(String lastName) { @@ -101,7 +104,7 @@ public class User implements Serializable { } public String getEmail() { - return email; + return this.email; } public void setEmail(String email) { @@ -109,4 +112,4 @@ public class User implements Serializable { } private static final long serialVersionUID = 2738859149330833739L; -} \ No newline at end of file +} diff --git a/samples/websocket/src/main/java/sample/data/UserRepository.java b/samples/websocket/src/main/java/sample/data/UserRepository.java index 76084255..67906167 100644 --- a/samples/websocket/src/main/java/sample/data/UserRepository.java +++ b/samples/websocket/src/main/java/sample/data/UserRepository.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.data; import org.springframework.data.repository.CrudRepository; diff --git a/samples/websocket/src/main/java/sample/mvc/CsrfController.java b/samples/websocket/src/main/java/sample/mvc/CsrfController.java index 84fba11c..87feddc8 100644 --- a/samples/websocket/src/main/java/sample/mvc/CsrfController.java +++ b/samples/websocket/src/main/java/sample/mvc/CsrfController.java @@ -1,3 +1,19 @@ +/* + * Copyright 2014-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package sample.mvc; import org.springframework.security.web.csrf.CsrfToken; diff --git a/samples/websocket/src/main/java/sample/mvc/MessageController.java b/samples/websocket/src/main/java/sample/mvc/MessageController.java index dfda7fbb..1ba7fb41 100644 --- a/samples/websocket/src/main/java/sample/mvc/MessageController.java +++ b/samples/websocket/src/main/java/sample/mvc/MessageController.java @@ -1,22 +1,28 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package sample.mvc; import java.util.List; +import sample.data.ActiveWebSocketUserRepository; +import sample.data.InstantMessage; +import sample.data.User; +import sample.security.CurrentUser; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.MessageMapping; @@ -25,11 +31,6 @@ import org.springframework.messaging.simp.annotation.SubscribeMapping; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; -import sample.data.ActiveWebSocketUserRepository; -import sample.data.InstantMessage; -import sample.data.User; -import sample.security.CurrentUser; - /** * Controller for managing {@link Message} instances. * @@ -43,7 +44,7 @@ public class MessageController { private ActiveWebSocketUserRepository activeUserRepository; @Autowired - public MessageController(ActiveWebSocketUserRepository activeUserRepository,SimpMessageSendingOperations messagingTemplate) { + public MessageController(ActiveWebSocketUserRepository activeUserRepository, SimpMessageSendingOperations messagingTemplate) { this.activeUserRepository = activeUserRepository; this.messagingTemplate = messagingTemplate; } @@ -56,12 +57,12 @@ public class MessageController { @MessageMapping("/im") public void im(InstantMessage im, @CurrentUser User currentUser) { im.setFrom(currentUser.getEmail()); - messagingTemplate.convertAndSendToUser(im.getTo(),"/queue/messages",im); - messagingTemplate.convertAndSendToUser(im.getFrom(),"/queue/messages",im); + this.messagingTemplate.convertAndSendToUser(im.getTo(), "/queue/messages", im); + this.messagingTemplate.convertAndSendToUser(im.getFrom(), "/queue/messages", im); } @SubscribeMapping("/users") public List subscribeMessages() throws Exception { - return activeUserRepository.findAllActiveUsers(); + return this.activeUserRepository.findAllActiveUsers(); } } diff --git a/samples/websocket/src/main/java/sample/security/CurrentUser.java b/samples/websocket/src/main/java/sample/security/CurrentUser.java index 39c96577..fae2f6a7 100644 --- a/samples/websocket/src/main/java/sample/security/CurrentUser.java +++ b/samples/websocket/src/main/java/sample/security/CurrentUser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.security; import java.lang.annotation.Documented; diff --git a/samples/websocket/src/main/java/sample/security/UserRepositoryUserDetailsService.java b/samples/websocket/src/main/java/sample/security/UserRepositoryUserDetailsService.java index 5344ab20..30cbda25 100644 --- a/samples/websocket/src/main/java/sample/security/UserRepositoryUserDetailsService.java +++ b/samples/websocket/src/main/java/sample/security/UserRepositoryUserDetailsService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.security; import java.util.Collection; +import sample.data.User; +import sample.data.UserRepository; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; -import sample.data.User; -import sample.data.UserRepository; import org.springframework.stereotype.Service; /** @@ -45,8 +47,8 @@ public class UserRepositoryUserDetailsService implements UserDetailsService { */ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - User user = userRepository.findByEmail(username); - if(user == null) { + User user = this.userRepository.findByEmail(username); + if (user == null) { throw new UsernameNotFoundException("Could not find user " + username); } return new CustomUserDetails(user); diff --git a/samples/websocket/src/main/java/sample/websocket/WebSocketConnectHandler.java b/samples/websocket/src/main/java/sample/websocket/WebSocketConnectHandler.java index 18dd9e8c..3673ab3e 100644 --- a/samples/websocket/src/main/java/sample/websocket/WebSocketConnectHandler.java +++ b/samples/websocket/src/main/java/sample/websocket/WebSocketConnectHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package sample.websocket; import java.security.Principal; import java.util.Arrays; import java.util.Calendar; +import sample.data.ActiveWebSocketUser; +import sample.data.ActiveWebSocketUserRepository; + import org.springframework.context.ApplicationListener; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionConnectEvent; -import sample.data.ActiveWebSocketUser; -import sample.data.ActiveWebSocketUserRepository; - public class WebSocketConnectHandler implements ApplicationListener { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; @@ -41,11 +42,11 @@ public class WebSocketConnectHandler implements ApplicationListener implements ApplicationListener { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; @@ -36,16 +37,16 @@ public class WebSocketDisconnectHandler implements ApplicationListener { - private Map events = new HashMap(); - private Map locks = new HashMap(); + private Map events = new HashMap(); + private Map locks = new HashMap(); public void onApplicationEvent(AbstractSessionEvent event) { String sessionId = event.getSessionId(); @@ -51,20 +52,20 @@ public class SessionEventRegistry implements ApplicationListener E waitForEvent(String sessionId) throws InterruptedException { Object lock = getLock(sessionId); - synchronized(lock) { - if(!events.containsKey(sessionId)) { + synchronized (lock) { + if (!this.events.containsKey(sessionId)) { lock.wait(10000); } } - return (E) events.get(sessionId); + return (E) this.events.get(sessionId); } private Object getLock(String sessionId) { - synchronized(locks) { - Object lock = locks.get(sessionId); - if(lock == null) { + synchronized (this.locks) { + Object lock = this.locks.get(sessionId); + if (lock == null) { lock = new Object(); - locks.put(sessionId, lock); + this.locks.put(sessionId, lock); } return lock; } diff --git a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/AbstractGemFireIntegrationTests.java b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/AbstractGemFireIntegrationTests.java index 83a81cd9..de92c8b3 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/AbstractGemFireIntegrationTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/AbstractGemFireIntegrationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +16,6 @@ package org.springframework.session.data.gemfire; -import static org.assertj.core.api.Assertions.assertThat; - import java.io.File; import java.io.IOException; import java.net.Socket; @@ -27,13 +25,6 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Before; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationListener; -import org.springframework.session.ExpiringSession; -import org.springframework.session.data.gemfire.support.GemFireUtils; -import org.springframework.session.events.AbstractSessionEvent; - import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.DataPolicy; @@ -45,12 +36,22 @@ import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.ClientCacheFactory; import com.gemstone.gemfire.cache.query.Index; import com.gemstone.gemfire.cache.server.CacheServer; +import org.junit.Before; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationListener; +import org.springframework.session.ExpiringSession; +import org.springframework.session.data.gemfire.support.GemFireUtils; +import org.springframework.session.events.AbstractSessionEvent; + +import static org.assertj.core.api.Assertions.assertThat; /** * AbstractGemFireIntegrationTests is an abstract base class encapsulating common operations for writing * Spring Session GemFire integration tests. * * @author John Blum + * @since 1.1.0 * @see org.springframework.session.ExpiringSession * @see org.springframework.session.events.AbstractSessionEvent * @see com.gemstone.gemfire.cache.Cache @@ -60,7 +61,6 @@ import com.gemstone.gemfire.cache.server.CacheServer; * @see com.gemstone.gemfire.cache.Region * @see com.gemstone.gemfire.cache.client.ClientCache * @see com.gemstone.gemfire.cache.server.CacheServer - * @since 1.1.0 */ public abstract class AbstractGemFireIntegrationTests { @@ -70,7 +70,7 @@ public abstract class AbstractGemFireIntegrationTests { protected static final int DEFAULT_GEMFIRE_SERVER_PORT = CacheServer.DEFAULT_PORT; protected static final long DEFAULT_WAIT_DURATION = TimeUnit.SECONDS.toMillis(20); - protected static final long DEFAULT_WAIT_INTERVAL = 500l; + protected static final long DEFAULT_WAIT_INTERVAL = 500L; protected static final File WORKING_DIRECTORY = new File(System.getProperty("user.dir")); @@ -355,7 +355,7 @@ public abstract class AbstractGemFireIntegrationTests { List regionList = new ArrayList(regions.size()); - for (Region region : regions) { + for (Region region : regions) { regionList.add(region.getFullPath()); } @@ -365,7 +365,7 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ @SuppressWarnings("unchecked") protected T createSession() { - T expiringSession = (T) gemfireSessionRepository.createSession(); + T expiringSession = (T) this.gemfireSessionRepository.createSession(); assertThat(expiringSession).isNotNull(); return expiringSession; } @@ -380,19 +380,19 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ protected T expire(T session) { - session.setLastAccessedTime(0l); + session.setLastAccessedTime(0L); return session; } /* (non-Javadoc) */ @SuppressWarnings("unchecked") protected T get(String sessionId) { - return (T) gemfireSessionRepository.getSession(sessionId); + return (T) this.gemfireSessionRepository.getSession(sessionId); } /* (non-Javadoc) */ protected T save(T session) { - gemfireSessionRepository.save(session); + this.gemfireSessionRepository.save(session); return session; } @@ -423,14 +423,14 @@ public abstract class AbstractGemFireIntegrationTests { /* (non-Javadoc) */ public void onApplicationEvent(AbstractSessionEvent event) { - sessionEvent = event; + this.sessionEvent = event; } /* (non-Javadoc) */ public T waitForSessionEvent(long duration) { waitOnCondition(new Condition() { public boolean evaluate() { - return (sessionEvent != null); + return (SessionEventListener.this.sessionEvent != null); } }, duration); diff --git a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerGemFireOperationsSessionRepositoryIntegrationTests.java b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerGemFireOperationsSessionRepositoryIntegrationTests.java index b4d33b21..63e56a36 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerGemFireOperationsSessionRepositoryIntegrationTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/ClientServerGemFireOperationsSessionRepositoryIntegrationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +16,6 @@ package org.springframework.session.data.gemfire; -import static org.assertj.core.api.Assertions.assertThat; - import java.io.File; import java.io.IOException; import java.net.InetAddress; @@ -29,12 +27,19 @@ import java.util.Date; import java.util.Properties; import java.util.concurrent.TimeUnit; +import com.gemstone.gemfire.cache.Cache; +import com.gemstone.gemfire.cache.DataPolicy; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.RegionAttributes; +import com.gemstone.gemfire.cache.client.ClientCache; +import com.gemstone.gemfire.cache.client.Pool; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ConfigurableApplicationContext; @@ -61,18 +66,14 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.util.FileSystemUtils; import org.springframework.util.SocketUtils; -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionAttributes; -import com.gemstone.gemfire.cache.client.ClientCache; -import com.gemstone.gemfire.cache.client.Pool; +import static org.assertj.core.api.Assertions.assertThat; /** * The ClientServerGemFireOperationsSessionRepositoryIntegrationTests class is a test suite of test cases testing * the functionality of GemFire-backed Spring Sessions using a GemFire client-server topology. * * @author John Blum + * @since 1.1.0 * @see org.junit.Test * @see org.junit.runner.RunWith * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests @@ -86,7 +87,6 @@ import com.gemstone.gemfire.cache.client.Pool; * @see com.gemstone.gemfire.cache.client.ClientCache * @see com.gemstone.gemfire.cache.client.Pool * @see com.gemstone.gemfire.cache.server.CacheServer - * @since 1.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = @@ -164,7 +164,7 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests exte @After public void tearDown() { - sessionEventListener.getSessionEvent(); + this.sessionEventListener.getSessionEvent(); } @Test @@ -173,7 +173,7 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests exte ExpiringSession expectedSession = save(createSession()); - AbstractSessionEvent sessionEvent = sessionEventListener.waitForSessionEvent(500); + AbstractSessionEvent sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); @@ -185,35 +185,35 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests exte assertThat(createdSession.getLastAccessedTime()).isEqualTo(createdSession.getCreationTime()); assertThat(createdSession.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); - gemfireSessionRepository.delete(expectedSession.getId()); + this.gemfireSessionRepository.delete(expectedSession.getId()); } @Test public void getExistingNonExpiredSessionBeforeAndAfterExpiration() { ExpiringSession expectedSession = save(touch(createSession())); - AbstractSessionEvent sessionEvent = sessionEventListener.waitForSessionEvent(500); + AbstractSessionEvent sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); assertThat(sessionEvent.getSession()).isEqualTo(expectedSession); - assertThat(sessionEventListener.getSessionEvent()).isNull(); + assertThat(this.sessionEventListener.getSessionEvent()).isNull(); - ExpiringSession savedSession = gemfireSessionRepository.getSession(expectedSession.getId()); + ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); // NOTE for some reason or another, performing a GemFire (Client)Cache Region.get(key) // causes a Region CREATE event... o.O // calling sessionEventListener.getSessionEvent() here to clear the event - sessionEventListener.getSessionEvent(); + this.sessionEventListener.getSessionEvent(); - sessionEvent = sessionEventListener.waitForSessionEvent(TimeUnit.SECONDS.toMillis( + sessionEvent = this.sessionEventListener.waitForSessionEvent(TimeUnit.SECONDS.toMillis( MAX_INACTIVE_INTERVAL_IN_SECONDS + 1)); assertThat(sessionEvent).isInstanceOf(SessionExpiredEvent.class); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSession.getId()); - ExpiringSession expiredSession = gemfireSessionRepository.getSession(expectedSession.getId()); + ExpiringSession expiredSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); assertThat(expiredSession).isNull(); } @@ -222,19 +222,19 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests exte public void deleteExistingNonExpiredSessionFiresSessionDeletedEventAndReturnsNullOnGet() { ExpiringSession expectedSession = save(touch(createSession())); - AbstractSessionEvent sessionEvent = sessionEventListener.waitForSessionEvent(500); + AbstractSessionEvent sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); assertThat(sessionEvent.getSession()).isEqualTo(expectedSession); - gemfireSessionRepository.delete(expectedSession.getId()); + this.gemfireSessionRepository.delete(expectedSession.getId()); - sessionEvent = sessionEventListener.waitForSessionEvent(500); + sessionEvent = this.sessionEventListener.waitForSessionEvent(500); assertThat(sessionEvent).isInstanceOf(SessionDeletedEvent.class); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSession.getId()); - ExpiringSession deletedSession = gemfireSessionRepository.getSession(expectedSession.getId()); + ExpiringSession deletedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); assertThat(deletedSession).isNull(); } @@ -257,9 +257,10 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests exte } @Bean(name = GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME) - PoolFactoryBean gemfirePool(@Value("${spring.session.data.gemfire.port:"+DEFAULT_GEMFIRE_SERVER_PORT+"}") int port) { + PoolFactoryBean gemfirePool(@Value("${spring.session.data.gemfire.port:" + DEFAULT_GEMFIRE_SERVER_PORT + "}") int port) { PoolFactoryBean poolFactory = new PoolFactoryBean() { - @Override protected Properties resolveGemfireProperties() { + @Override + protected Properties resolveGemfireProperties() { return gemfireProperties(); } }; @@ -350,7 +351,7 @@ public class ClientServerGemFireOperationsSessionRepositoryIntegrationTests exte @Bean CacheServerFactoryBean gemfireCacheServer(Cache gemfireCache, - @Value("${spring.session.data.gemfire.port:"+DEFAULT_GEMFIRE_SERVER_PORT+"}") int port) { + @Value("${spring.session.data.gemfire.port:" + DEFAULT_GEMFIRE_SERVER_PORT + "}") int port) { CacheServerFactoryBean cacheServerFactory = new CacheServerFactoryBean(); diff --git a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryIntegrationTests.java b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryIntegrationTests.java index 6e8b9b75..a6ba93a2 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryIntegrationTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryIntegrationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,10 +16,6 @@ package org.springframework.session.data.gemfire; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME; -import static org.springframework.session.data.gemfire.GemFireOperationsSessionRepository.GemFireSession; - import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -27,9 +23,19 @@ import java.util.Map; import java.util.Properties; import java.util.UUID; +import com.gemstone.gemfire.cache.DataPolicy; +import com.gemstone.gemfire.cache.ExpirationAction; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.query.Query; +import com.gemstone.gemfire.cache.query.QueryService; +import com.gemstone.gemfire.cache.query.SelectResults; +import com.gemstone.gemfire.pdx.PdxReader; +import com.gemstone.gemfire.pdx.PdxSerializable; +import com.gemstone.gemfire.pdx.PdxWriter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.context.annotation.Bean; import org.springframework.data.gemfire.CacheFactoryBean; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -46,21 +52,14 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.ExpirationAction; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.query.Query; -import com.gemstone.gemfire.cache.query.QueryService; -import com.gemstone.gemfire.cache.query.SelectResults; -import com.gemstone.gemfire.pdx.PdxReader; -import com.gemstone.gemfire.pdx.PdxSerializable; -import com.gemstone.gemfire.pdx.PdxWriter; +import static org.assertj.core.api.Assertions.assertThat; /** * The GemFireOperationsSessionRepositoryIntegrationTests class is a test suite of test cases testing * the findByPrincipalName query method on the GemFireOpeationsSessionRepository class. * * @author John Blum + * @since 1.1.0 * @see org.junit.Test * @see org.junit.runner.RunWith * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests @@ -71,7 +70,6 @@ import com.gemstone.gemfire.pdx.PdxWriter; * @see org.springframework.test.context.web.WebAppConfiguration * @see com.gemstone.gemfire.cache.Cache * @see com.gemstone.gemfire.cache.Region - * @since 1.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @@ -91,35 +89,35 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Before public void setup() { - context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(new UsernamePasswordAuthenticationToken("username-"+UUID.randomUUID(), "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); + this.context = SecurityContextHolder.createEmptyContext(); + this.context.setAuthentication(new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); - changedContext = SecurityContextHolder.createEmptyContext(); - changedContext.setAuthentication(new UsernamePasswordAuthenticationToken("changedContext-"+UUID.randomUUID(), "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); + this.changedContext = SecurityContextHolder.createEmptyContext(); + this.changedContext.setAuthentication(new UsernamePasswordAuthenticationToken("changedContext-" + UUID.randomUUID(), "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); - assertThat(gemfireCache).isNotNull(); - assertThat(gemfireSessionRepository).isNotNull(); - assertThat(gemfireSessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo( + assertThat(this.gemfireCache).isNotNull(); + assertThat(this.gemfireSessionRepository).isNotNull(); + assertThat(this.gemfireSessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo( MAX_INACTIVE_INTERVAL_IN_SECONDS); - Region sessionRegion = 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(String indexName, String indexValue) { - return gemfireSessionRepository.findByIndexNameAndIndexValue(indexName, indexValue); + return this.gemfireSessionRepository.findByIndexNameAndIndexValue(indexName, indexValue); } protected Map doFindByPrincipalName(String principalName) { - return doFindByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, principalName); + return doFindByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName); } @SuppressWarnings({ "unchecked" }) protected Map doFindByPrincipalName(String regionName, String principalName) { try { - Region region = gemfireCache.getRegion(regionName); + Region region = this.gemfireCache.getRegion(regionName); assertThat(region).isNotNull(); @@ -239,7 +237,7 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void findSessionsBySecurityPrincipalName() { ExpiringSession toSave = this.gemfireSessionRepository.createSession(); - toSave.setAttribute(SPRING_SECURITY_CONTEXT, context); + toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); save(toSave); @@ -251,10 +249,10 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void findSessionsByChangedSecurityPrincipalName() { ExpiringSession toSave = this.gemfireSessionRepository.createSession(); - toSave.setAttribute(SPRING_SECURITY_CONTEXT, context); + toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); save(toSave); - toSave.setAttribute(SPRING_SECURITY_CONTEXT, changedContext); + toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.changedContext); save(toSave); Map findByPrincipalName = doFindByPrincipalName(getSecurityName()); @@ -287,11 +285,11 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract @Test public void saveAndReadSessionWithAttributes() { - ExpiringSession expectedSession = gemfireSessionRepository.createSession(); + ExpiringSession expectedSession = this.gemfireSessionRepository.createSession(); - assertThat(expectedSession).isInstanceOf(GemFireSession.class); + assertThat(expectedSession).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class); - ((GemFireSession) expectedSession).setPrincipalName("jblum"); + ((AbstractGemFireOperationsSessionRepository.GemFireSession) expectedSession).setPrincipalName("jblum"); List expectedAttributeNames = Arrays.asList( "booleanAttribute", "numericAttribute", "stringAttribute", "personAttribute"); @@ -303,16 +301,16 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract expectedSession.setAttribute(expectedAttributeNames.get(2), "test"); expectedSession.setAttribute(expectedAttributeNames.get(3), jonDoe); - gemfireSessionRepository.save(touch(expectedSession)); + this.gemfireSessionRepository.save(touch(expectedSession)); - ExpiringSession savedSession = gemfireSessionRepository.getSession(expectedSession.getId()); + ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); - assertThat(savedSession).isInstanceOf(GemFireSession.class); - assertThat(((GemFireSession) savedSession).getPrincipalName()).isEqualTo("jblum"); + assertThat(savedSession).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class); + assertThat(((AbstractGemFireOperationsSessionRepository.GemFireSession) savedSession).getPrincipalName()).isEqualTo("jblum"); assertThat(savedSession.getAttributeNames().containsAll(expectedAttributeNames)).as( - String.format("Expected (%1$s); but was (%2$s)", expectedAttributeNames,savedSession.getAttributeNames())) + String.format("Expected (%1$s); but was (%2$s)", expectedAttributeNames, savedSession.getAttributeNames())) .isTrue(); assertThat(Boolean.valueOf(String.valueOf(savedSession.getAttribute(expectedAttributeNames.get(0))))).isTrue(); @@ -323,11 +321,11 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract } private String getSecurityName() { - return context.getAuthentication().getName(); + return this.context.getAuthentication().getName(); } private String getChangedSecurityName() { - return changedContext.getAuthentication().getName(); + return this.changedContext.getAuthentication().getName(); } @EnableGemFireHttpSession(regionName = SPRING_SESSION_GEMFIRE_REGION_NAME, @@ -377,11 +375,11 @@ public class GemFireOperationsSessionRepositoryIntegrationTests extends Abstract } public String getFirstName() { - return firstName; + return this.firstName; } public String getLastName() { - return lastName; + return this.lastName; } public String getName() { diff --git a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSessionEventsIntegrationTests.java b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSessionEventsIntegrationTests.java index 6ed19690..8c2a59e0 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSessionEventsIntegrationTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSessionEventsIntegrationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,16 +16,19 @@ package org.springframework.session.data.gemfire.config.annotation.web.http; -import static org.assertj.core.api.Assertions.assertThat; - import java.util.Properties; import java.util.UUID; import java.util.concurrent.TimeUnit; +import com.gemstone.gemfire.cache.DataPolicy; +import com.gemstone.gemfire.cache.ExpirationAction; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.RegionShortcut; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.data.gemfire.CacheFactoryBean; @@ -41,16 +44,14 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.ExpirationAction; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionShortcut; +import static org.assertj.core.api.Assertions.assertThat; /** * The EnableGemFireHttpSessionEventsIntegrationTests class is a test suite of test cases testing the Session Event * functionality and behavior of the 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 @@ -64,7 +65,6 @@ import com.gemstone.gemfire.cache.RegionShortcut; * @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner * @see org.springframework.test.context.web.WebAppConfiguration * @see com.gemstone.gemfire.cache.Region - * @since 1.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @@ -82,13 +82,13 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF @Before public void setup() { - assertThat(GemFireUtils.isPeer(gemfireCache)).isTrue(); - assertThat(gemfireSessionRepository).isNotNull(); - assertThat(gemfireSessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo( + assertThat(GemFireUtils.isPeer(this.gemfireCache)).isTrue(); + assertThat(this.gemfireSessionRepository).isNotNull(); + assertThat(this.gemfireSessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo( MAX_INACTIVE_INTERVAL_IN_SECONDS); - assertThat(sessionEventListener).isNotNull(); + assertThat(this.sessionEventListener).isNotNull(); - Region sessionRegion = 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.REPLICATE); assertEntryIdleTimeout(sessionRegion, ExpirationAction.INVALIDATE, MAX_INACTIVE_INTERVAL_IN_SECONDS); @@ -96,7 +96,7 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF @After public void tearDown() { - sessionEventListener.getSessionEvent(); + this.sessionEventListener.getSessionEvent(); } @Test @@ -105,7 +105,7 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF ExpiringSession expectedSession = save(createSession()); - AbstractSessionEvent sessionEvent = sessionEventListener.getSessionEvent(); + AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); @@ -126,7 +126,7 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF assertThat(expectedSession.isExpired()).isFalse(); // NOTE though unlikely, a possible race condition exists between save and get... - ExpiringSession savedSession = gemfireSessionRepository.getSession(expectedSession.getId()); + ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); } @@ -135,7 +135,7 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF public void getExistingExpiredSession() { ExpiringSession expectedSession = save(expire(createSession())); - AbstractSessionEvent sessionEvent = sessionEventListener.getSessionEvent(); + AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); @@ -143,25 +143,25 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF assertThat(createdSession).isEqualTo(expectedSession); assertThat(createdSession.isExpired()).isTrue(); - assertThat(gemfireSessionRepository.getSession(createdSession.getId())).isNull(); + assertThat(this.gemfireSessionRepository.getSession(createdSession.getId())).isNull(); } @Test public void getNonExistingSession() { - assertThat(gemfireSessionRepository.getSession(UUID.randomUUID().toString())).isNull(); + assertThat(this.gemfireSessionRepository.getSession(UUID.randomUUID().toString())).isNull(); } @Test public void deleteExistingNonExpiredSession() { ExpiringSession expectedSession = save(touch(createSession())); - ExpiringSession savedSession = gemfireSessionRepository.getSession(expectedSession.getId()); + ExpiringSession savedSession = this.gemfireSessionRepository.getSession(expectedSession.getId()); assertThat(savedSession).isEqualTo(expectedSession); assertThat(savedSession.isExpired()).isFalse(); - gemfireSessionRepository.delete(savedSession.getId()); + this.gemfireSessionRepository.delete(savedSession.getId()); - AbstractSessionEvent sessionEvent = sessionEventListener.getSessionEvent(); + AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionDeletedEvent.class); assertThat(sessionEvent.getSessionId()).isEqualTo(savedSession.getId()); @@ -169,14 +169,14 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF ExpiringSession deletedSession = sessionEvent.getSession(); assertThat(deletedSession).isEqualTo(savedSession); - assertThat(gemfireSessionRepository.getSession(deletedSession.getId())).isNull(); + assertThat(this.gemfireSessionRepository.getSession(deletedSession.getId())).isNull(); } @Test public void deleteExistingExpiredSession() { ExpiringSession expectedSession = save(createSession()); - AbstractSessionEvent sessionEvent = sessionEventListener.getSessionEvent(); + AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionCreatedEvent.class); @@ -184,8 +184,8 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF assertThat(createdSession).isEqualTo(expectedSession); - sessionEvent = sessionEventListener.waitForSessionEvent(TimeUnit.SECONDS.toMillis( - gemfireSessionRepository.getMaxInactiveIntervalInSeconds() + 1)); + sessionEvent = this.sessionEventListener.waitForSessionEvent(TimeUnit.SECONDS.toMillis( + this.gemfireSessionRepository.getMaxInactiveIntervalInSeconds() + 1)); assertThat(sessionEvent).isInstanceOf(SessionExpiredEvent.class); @@ -194,25 +194,25 @@ public class EnableGemFireHttpSessionEventsIntegrationTests extends AbstractGemF assertThat(expiredSession).isEqualTo(createdSession); assertThat(expiredSession.isExpired()).isTrue(); - gemfireSessionRepository.delete(expectedSession.getId()); + this.gemfireSessionRepository.delete(expectedSession.getId()); - sessionEvent = sessionEventListener.getSessionEvent(); + sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionDeletedEvent.class); assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(expiredSession.getId()); - assertThat(gemfireSessionRepository.getSession(sessionEvent.getSessionId())).isNull(); + assertThat(this.gemfireSessionRepository.getSession(sessionEvent.getSessionId())).isNull(); } @Test public void deleteNonExistingSession() { String expectedSessionId = UUID.randomUUID().toString(); - assertThat(gemfireSessionRepository.getSession(expectedSessionId)).isNull(); + assertThat(this.gemfireSessionRepository.getSession(expectedSessionId)).isNull(); - gemfireSessionRepository.delete(expectedSessionId); + this.gemfireSessionRepository.delete(expectedSessionId); - AbstractSessionEvent sessionEvent = sessionEventListener.getSessionEvent(); + AbstractSessionEvent sessionEvent = this.sessionEventListener.getSessionEvent(); assertThat(sessionEvent).isInstanceOf(SessionDeletedEvent.class); assertThat(sessionEvent.getSession()).isNull(); diff --git a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionJavaConfigurationTests.java b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionJavaConfigurationTests.java index 67d600f1..8d7123ca 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionJavaConfigurationTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionJavaConfigurationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,12 +16,18 @@ package org.springframework.session.data.gemfire.config.annotation.web.http; -import static org.assertj.core.api.Assertions.assertThat; - import java.util.Properties; +import com.gemstone.gemfire.cache.Cache; +import com.gemstone.gemfire.cache.DataPolicy; +import com.gemstone.gemfire.cache.ExpirationAction; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.RegionShortcut; +import com.gemstone.gemfire.cache.query.Index; +import com.gemstone.gemfire.cache.query.QueryService; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.data.gemfire.CacheFactoryBean; @@ -33,19 +39,14 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.ExpirationAction; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionShortcut; -import com.gemstone.gemfire.cache.query.Index; -import com.gemstone.gemfire.cache.query.QueryService; +import static org.assertj.core.api.Assertions.assertThat; /** * The GemFireHttpSessionJavaConfigurationTests class is a test suite of test cases testing the configuration of * Spring Session backed by GemFire using Java-based configuration meta-data. * * @author John Blum + * @since 1.1.0 * @see org.junit.Test * @see org.springframework.session.ExpiringSession * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests @@ -55,7 +56,6 @@ import com.gemstone.gemfire.cache.query.QueryService; * @see org.springframework.test.context.web.WebAppConfiguration * @see com.gemstone.gemfire.cache.Cache * @see com.gemstone.gemfire.cache.Region - * @since 1.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @@ -78,7 +78,7 @@ public class GemFireHttpSessionJavaConfigurationTests extends AbstractGemFireInt @Test public void gemfireCacheConfigurationIsValid() { - Region example = assertCacheAndRegion(gemfireCache, "JavaExample", + Region example = assertCacheAndRegion(this.gemfireCache, "JavaExample", DataPolicy.REPLICATE); assertEntryIdleTimeout(example, ExpirationAction.INVALIDATE, 900); @@ -86,7 +86,7 @@ public class GemFireHttpSessionJavaConfigurationTests extends AbstractGemFireInt @Test public void verifyGemFireExampleCacheRegionPrincipalNameIndexWasCreatedSuccessfully() { - Region example = assertCacheAndRegion(gemfireCache, "JavaExample", + Region example = assertCacheAndRegion(this.gemfireCache, "JavaExample", DataPolicy.REPLICATE); QueryService queryService = example.getRegionService().getQueryService(); @@ -100,7 +100,7 @@ public class GemFireHttpSessionJavaConfigurationTests extends AbstractGemFireInt @Test public void verifyGemFireExampleCacheRegionSessionAttributesIndexWasNotCreated() { - Region example = assertCacheAndRegion(gemfireCache, "JavaExample", + Region example = assertCacheAndRegion(this.gemfireCache, "JavaExample", DataPolicy.REPLICATE); QueryService queryService = example.getRegionService().getQueryService(); diff --git a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionXmlConfigurationTests.java b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionXmlConfigurationTests.java index 028cd8a8..3822ac12 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionXmlConfigurationTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionXmlConfigurationTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,10 +16,15 @@ package org.springframework.session.data.gemfire.config.annotation.web.http; -import static org.assertj.core.api.Assertions.assertThat; - +import com.gemstone.gemfire.cache.Cache; +import com.gemstone.gemfire.cache.DataPolicy; +import com.gemstone.gemfire.cache.ExpirationAction; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.query.Index; +import com.gemstone.gemfire.cache.query.QueryService; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.session.ExpiringSession; import org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests; @@ -29,18 +34,14 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.DataPolicy; -import com.gemstone.gemfire.cache.ExpirationAction; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.query.Index; -import com.gemstone.gemfire.cache.query.QueryService; +import static org.assertj.core.api.Assertions.assertThat; /** * The GemFireHttpSessionXmlConfigurationTests class is a test suite of test cases testing the configuration of * Spring Session backed by GemFire using XML configuration meta-data. * * @author John Blum + * @since 1.1.0 * @see org.junit.Test * @see org.springframework.session.ExpiringSession * @see org.springframework.session.data.gemfire.AbstractGemFireIntegrationTests @@ -50,7 +51,6 @@ import com.gemstone.gemfire.cache.query.QueryService; * @see org.springframework.test.context.web.WebAppConfiguration * @see com.gemstone.gemfire.cache.Cache * @see com.gemstone.gemfire.cache.Region - * @since 1.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @@ -73,14 +73,14 @@ public class GemFireHttpSessionXmlConfigurationTests extends AbstractGemFireInte @Test public void gemfireCacheConfigurationIsValid() { - Region example = assertCacheAndRegion(gemfireCache, "XmlExample", DataPolicy.NORMAL); + Region example = assertCacheAndRegion(this.gemfireCache, "XmlExample", DataPolicy.NORMAL); assertEntryIdleTimeout(example, ExpirationAction.INVALIDATE, 3600); } @Test public void verifyGemFireExampleCacheRegionPrincipalNameIndexWasCreatedSuccessfully() { - Region example = assertCacheAndRegion(gemfireCache, "XmlExample", DataPolicy.NORMAL); + Region example = assertCacheAndRegion(this.gemfireCache, "XmlExample", DataPolicy.NORMAL); QueryService queryService = example.getRegionService().getQueryService(); @@ -93,7 +93,7 @@ public class GemFireHttpSessionXmlConfigurationTests extends AbstractGemFireInte @Test public void verifyGemFireExampleCacheRegionSessionAttributesIndexWasCreatedSuccessfully() { - Region example = assertCacheAndRegion(gemfireCache, "XmlExample", DataPolicy.NORMAL); + Region example = assertCacheAndRegion(this.gemfireCache, "XmlExample", DataPolicy.NORMAL); QueryService queryService = example.getRegionService().getQueryService(); diff --git a/spring-session/src/integration-test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSessionExpireSessionDestroyedTests.java b/spring-session/src/integration-test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSessionExpireSessionDestroyedTests.java index 5c15ef7f..c32349cb 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSessionExpireSessionDestroyedTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSessionExpireSessionDestroyedTests.java @@ -1,28 +1,27 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session.data.redis.config.annotation.web.http; - -import static org.assertj.core.api.Assertions.*; - import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; @@ -40,6 +39,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration @@ -54,35 +55,35 @@ public class EnableRedisHttpSessionExpireSessionDestroyedTests { @@ -90,14 +91,14 @@ public class EnableRedisHttpSessionExpireSessionDestroyedTests { @@ -36,10 +38,10 @@ public class RedisOperationsSessionRepositoryFlushImmediatelyITests ops = redis + BoundSetOperations ops = this.redis .boundSetOps("spring:session:RedisListenerContainerTaskExecutorITests:expirations:dummy"); ops.add("value"); ops.remove("value"); - assertThat(executor.taskDispatched()).isTrue(); + assertThat(this.executor.taskDispatched()).isTrue(); } @@ -52,29 +69,30 @@ public class RedisListenerContainerTaskExecutorITests { private Boolean taskDispatched; - public SessionTaskExecutor(Executor executor) { + SessionTaskExecutor(Executor executor) { this.executor = executor; } public void execute(Runnable task) { - synchronized (lock) { + synchronized (this.lock) { try { - executor.execute(task); - } finally { - taskDispatched = true; - lock.notifyAll(); + this.executor.execute(task); + } + finally { + this.taskDispatched = true; + this.lock.notifyAll(); } } } public boolean taskDispatched() throws InterruptedException { - if(taskDispatched != null) { - return taskDispatched; + if (this.taskDispatched != null) { + return this.taskDispatched; } - synchronized (lock) { - lock.wait(TimeUnit.SECONDS.toMillis(1)); + synchronized (this.lock) { + this.lock.wait(TimeUnit.SECONDS.toMillis(1)); } - return taskDispatched == null ? Boolean.FALSE : taskDispatched; + return this.taskDispatched == null ? Boolean.FALSE : this.taskDispatched; } } diff --git a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/AbstractHazelcastRepositoryITests.java b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/AbstractHazelcastRepositoryITests.java index f5a3681c..10aa0ddf 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/AbstractHazelcastRepositoryITests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/AbstractHazelcastRepositoryITests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,15 @@ package org.springframework.session.hazelcast; -import static org.assertj.core.api.Assertions.assertThat; - +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.session.ExpiringSession; import org.springframework.session.SessionRepository; -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.core.IMap; +import static org.assertj.core.api.Assertions.assertThat; /** * Abstract base class for Hazelcast integration tests. @@ -43,19 +42,19 @@ public abstract class AbstractHazelcastRepositoryITests hazelcastMap = hazelcast.getMap("spring:session:sessions"); + IMap hazelcastMap = this.hazelcast.getMap("spring:session:sessions"); assertThat(hazelcastMap.size()).isEqualTo(0); - repository.save(sessionToSave); + this.repository.save(sessionToSave); assertThat(hazelcastMap.size()).isEqualTo(1); assertThat(hazelcastMap.get(sessionId)).isEqualTo(sessionToSave); - repository.delete(sessionId); + this.repository.delete(sessionId); assertThat(hazelcastMap.size()).isEqualTo(0); } diff --git a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastClientRepositoryITests.java b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastClientRepositoryITests.java index bdbf19ea..06b9600d 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastClientRepositoryITests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastClientRepositoryITests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ package org.springframework.session.hazelcast; +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.client.config.ClientConfig; +import com.hazelcast.core.HazelcastInstance; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; @@ -29,10 +32,6 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.util.SocketUtils; -import com.hazelcast.client.HazelcastClient; -import com.hazelcast.client.config.ClientConfig; -import com.hazelcast.core.HazelcastInstance; - /** * Integration tests that check the underlying data source - in this case * Hazelcast Client. @@ -59,7 +58,7 @@ public class HazelcastClientRepositoryITests @AfterClass public static void teardown() { - if(hazelcastInstance != null) { + if (hazelcastInstance != null) { hazelcastInstance.shutdown(); } } diff --git a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastITestUtils.java b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastITestUtils.java index bd7b8196..cf844dfb 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastITestUtils.java +++ b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastITestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,10 @@ import org.springframework.util.SocketUtils; * * @author Vedran Pavic */ -public class HazelcastITestUtils { +public final class HazelcastITestUtils { + + private HazelcastITestUtils() { + } /** * Creates {@link HazelcastInstance} for use in integration tests. diff --git a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastServerRepositoryITests.java b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastServerRepositoryITests.java index 5e871140..4df5b29f 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastServerRepositoryITests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/HazelcastServerRepositoryITests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java index c2e2c797..151441d1 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.hazelcast.config.annotation.web.http; -import static org.assertj.core.api.Assertions.*; - +import com.hazelcast.core.HazelcastInstance; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -41,7 +42,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import com.hazelcast.core.HazelcastInstance; +import static org.assertj.core.api.Assertions.assertThat; /** * Ensure that the appropriate SessionEvents are fired at the expected times. @@ -65,30 +66,30 @@ public class EnableHazelcastHttpSessionEventsTests { @Before public void setup() { - registry.clear(); + this.registry.clear(); } @Test public void saveSessionTest() throws InterruptedException { - String username = "saves-"+System.currentTimeMillis(); + String username = "saves-" + System.currentTimeMillis(); - S sessionToSave = repository.createSession(); + S sessionToSave = this.repository.createSession(); String expectedAttributeName = "a"; String expectedAttributeValue = "b"; sessionToSave.setAttribute(expectedAttributeName, expectedAttributeValue); - Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username,"password", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext(); toSaveContext.setAuthentication(toSaveToken); sessionToSave.setAttribute("SPRING_SECURITY_CONTEXT", toSaveContext); sessionToSave.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); - repository.save(sessionToSave); + this.repository.save(sessionToSave); - assertThat(registry.receivedEvent(sessionToSave.getId())).isTrue(); - assertThat(registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionCreatedEvent.class); + assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue(); + assertThat(this.registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionCreatedEvent.class); - Session session = repository.getSession(sessionToSave.getId()); + Session session = this.repository.getSession(sessionToSave.getId()); assertThat(session.getId()).isEqualTo(sessionToSave.getId()); assertThat(session.getAttributeNames()).isEqualTo(sessionToSave.getAttributeNames()); @@ -97,62 +98,62 @@ public class EnableHazelcastHttpSessionEventsTests { @Test public void expiredSessionTest() throws InterruptedException { - S sessionToSave = repository.createSession(); + S sessionToSave = this.repository.createSession(); - repository.save(sessionToSave); + this.repository.save(sessionToSave); - assertThat(registry.receivedEvent(sessionToSave.getId())).isTrue(); - assertThat(registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionCreatedEvent.class); - registry.clear(); + assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue(); + assertThat(this.registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionCreatedEvent.class); + this.registry.clear(); assertThat(sessionToSave.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); - assertThat(registry.receivedEvent(sessionToSave.getId())).isTrue(); - assertThat(registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionExpiredEvent.class); + assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue(); + assertThat(this.registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionExpiredEvent.class); - assertThat(repository.getSession(sessionToSave.getId())).isNull(); + assertThat(this.repository.getSession(sessionToSave.getId())).isNull(); } @Test public void deletedSessionTest() throws InterruptedException { - S sessionToSave = repository.createSession(); + S sessionToSave = this.repository.createSession(); - repository.save(sessionToSave); + this.repository.save(sessionToSave); - assertThat(registry.receivedEvent(sessionToSave.getId())).isTrue(); - assertThat(registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionCreatedEvent.class); - registry.clear(); + assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue(); + assertThat(this.registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionCreatedEvent.class); + this.registry.clear(); - repository.delete(sessionToSave.getId()); + this.repository.delete(sessionToSave.getId()); - assertThat(registry.receivedEvent(sessionToSave.getId())).isTrue(); - assertThat(registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionDeletedEvent.class); + assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue(); + assertThat(this.registry.getEvent(sessionToSave.getId())).isInstanceOf(SessionDeletedEvent.class); - assertThat(repository.getSession(sessionToSave.getId())).isNull(); + assertThat(this.repository.getSession(sessionToSave.getId())).isNull(); } @Test public void saveUpdatesTimeToLiveTest() throws InterruptedException { Object lock = new Object(); - S sessionToSave = repository.createSession(); + S sessionToSave = this.repository.createSession(); - repository.save(sessionToSave); + this.repository.save(sessionToSave); synchronized (lock) { lock.wait((sessionToSave.getMaxInactiveIntervalInSeconds() * 1000) - 500); } // Get and save the session like SessionRepositoryFilter would. - S sessionToUpdate = repository.getSession(sessionToSave.getId()); + S sessionToUpdate = this.repository.getSession(sessionToSave.getId()); sessionToUpdate.setLastAccessedTime(System.currentTimeMillis()); - repository.save(sessionToUpdate); + this.repository.save(sessionToUpdate); synchronized (lock) { lock.wait((sessionToUpdate.getMaxInactiveIntervalInSeconds() * 1000) - 100); } - assertThat(repository.getSession(sessionToUpdate.getId())).isNotNull(); + assertThat(this.repository.getSession(sessionToUpdate.getId())).isNotNull(); } @Configuration diff --git a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationXmlTests.java b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationXmlTests.java index a5b2c436..a0edc88b 100644 --- a/spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationXmlTests.java +++ b/spring-session/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationXmlTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.hazelcast.config.annotation.web.http; -import static org.assertj.core.api.Assertions.*; - +import com.hazelcast.config.ClasspathXmlConfig; +import com.hazelcast.config.Config; +import com.hazelcast.config.NetworkConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -29,16 +34,12 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.util.SocketUtils; -import com.hazelcast.config.ClasspathXmlConfig; -import com.hazelcast.config.Config; -import com.hazelcast.config.NetworkConfig; -import com.hazelcast.core.Hazelcast; -import com.hazelcast.core.HazelcastInstance; +import static org.assertj.core.api.Assertions.assertThat; /** * Test the different configuration options for the * {@link EnableHazelcastHttpSession} annotation. - * + * * @author Tommy Ludwig */ public class HazelcastHttpSessionConfigurationXmlTests { @@ -54,11 +55,11 @@ public class HazelcastHttpSessionConfigurationXmlTests * the type of Session being managed by this * {@link FindByIndexNameSessionRepository} + * @author Rob Winch */ public interface FindByIndexNameSessionRepository extends SessionRepository { @@ -61,4 +61,4 @@ public interface FindByIndexNameSessionRepository extends Ses * an empty Map is returned. */ Map findByIndexNameAndIndexValue(String indexName, String indexValue); -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/MapSession.java b/spring-session/src/main/java/org/springframework/session/MapSession.java index 96dfdf29..f6966fe7 100644 --- a/spring-session/src/main/java/org/springframework/session/MapSession.java +++ b/spring-session/src/main/java/org/springframework/session/MapSession.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session; import java.io.Serializable; @@ -37,22 +38,22 @@ import java.util.concurrent.TimeUnit; * This implementation has no synchronization, so it is best to use the copy constructor when working on multiple threads. *

* - * @since 1.0 * @author Rob Winch + * @since 1.0 */ public final class MapSession implements ExpiringSession, Serializable { /** - * Default {@link #setMaxInactiveIntervalInSeconds(int)} (30 minutes) + * Default {@link #setMaxInactiveIntervalInSeconds(int)} (30 minutes). */ public static final int DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS = 1800; private String id; private Map sessionAttrs = new HashMap(); private long creationTime = System.currentTimeMillis(); - private long lastAccessedTime = creationTime; + private long lastAccessedTime = this.creationTime; /** - * Defaults to 30 minutes + * Defaults to 30 minutes. */ private int maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS; @@ -75,12 +76,12 @@ public final class MapSession implements ExpiringSession, Serializable { } /** - * Creates a new instance from the provided {@link Session} + * Creates a new instance from the provided {@link Session}. * * @param session the {@link Session} to initialize this {@link Session} with. Cannot be null. */ public MapSession(ExpiringSession session) { - if(session == null) { + if (session == null) { throw new IllegalArgumentException("session cannot be null"); } this.id = session.getId(); @@ -99,15 +100,15 @@ public final class MapSession implements ExpiringSession, Serializable { } public long getCreationTime() { - return creationTime; + return this.creationTime; } public String getId() { - return id; + return this.id; } public long getLastAccessedTime() { - return lastAccessedTime; + return this.lastAccessedTime; } public void setMaxInactiveIntervalInSeconds(int interval) { @@ -115,7 +116,7 @@ public final class MapSession implements ExpiringSession, Serializable { } public int getMaxInactiveIntervalInSeconds() { - return maxInactiveInterval; + return this.maxInactiveInterval; } public boolean isExpired() { @@ -123,31 +124,32 @@ public final class MapSession implements ExpiringSession, Serializable { } boolean isExpired(long now) { - if(maxInactiveInterval < 0) { + if (this.maxInactiveInterval < 0) { return false; } - return now - TimeUnit.SECONDS.toMillis(maxInactiveInterval) >= lastAccessedTime; + return now - TimeUnit.SECONDS.toMillis(this.maxInactiveInterval) >= this.lastAccessedTime; } @SuppressWarnings("unchecked") public T getAttribute(String attributeName) { - return (T) sessionAttrs.get(attributeName); + return (T) this.sessionAttrs.get(attributeName); } public Set getAttributeNames() { - return sessionAttrs.keySet(); + return this.sessionAttrs.keySet(); } public void setAttribute(String attributeName, Object attributeValue) { if (attributeValue == null) { removeAttribute(attributeName); - } else { - sessionAttrs.put(attributeName, attributeValue); + } + else { + this.sessionAttrs.put(attributeName, attributeValue); } } public void removeAttribute(String attributeName) { - sessionAttrs.remove(attributeName); + this.sessionAttrs.remove(attributeName); } /** @@ -168,12 +170,12 @@ public final class MapSession implements ExpiringSession, Serializable { } public boolean equals(Object obj) { - return obj instanceof Session && id.equals(((Session) obj).getId()); + return obj instanceof Session && this.id.equals(((Session) obj).getId()); } public int hashCode() { - return id.hashCode(); + return this.id.hashCode(); } private static final long serialVersionUID = 7160779239673823561L; -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/MapSessionRepository.java b/spring-session/src/main/java/org/springframework/session/MapSessionRepository.java index 15a96f48..98fc7ba0 100644 --- a/spring-session/src/main/java/org/springframework/session/MapSessionRepository.java +++ b/spring-session/src/main/java/org/springframework/session/MapSessionRepository.java @@ -1,26 +1,27 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package org.springframework.session; -import org.springframework.session.events.SessionDeletedEvent; -import org.springframework.session.events.SessionExpiredEvent; +package org.springframework.session; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.springframework.session.events.SessionDeletedEvent; +import org.springframework.session.events.SessionExpiredEvent; + /** * A {@link SessionRepository} backed by a {@link java.util.Map} and that uses a {@link MapSession}. By default a * {@link java.util.concurrent.ConcurrentHashMap} is used, but a custom {@link java.util.Map} can be injected to use @@ -39,10 +40,10 @@ public class MapSessionRepository implements SessionRepository */ private Integer defaultMaxInactiveInterval; - private final Map sessions; + private final Map sessions; /** - * Creates an instance backed by a {@link java.util.concurrent.ConcurrentHashMap} + * Creates an instance backed by a {@link java.util.concurrent.ConcurrentHashMap}. */ public MapSessionRepository() { this(new ConcurrentHashMap()); @@ -53,8 +54,8 @@ public class MapSessionRepository implements SessionRepository * * @param sessions the {@link java.util.Map} to use. Cannot be null. */ - public MapSessionRepository(Map sessions) { - if(sessions == null) { + public MapSessionRepository(Map sessions) { + if (sessions == null) { throw new IllegalArgumentException("sessions cannot be null"); } this.sessions = sessions; @@ -69,15 +70,15 @@ public class MapSessionRepository implements SessionRepository } public void save(ExpiringSession session) { - sessions.put(session.getId(), new MapSession(session)); + this.sessions.put(session.getId(), new MapSession(session)); } public ExpiringSession getSession(String id) { - ExpiringSession saved = sessions.get(id); - if(saved == null) { + ExpiringSession saved = this.sessions.get(id); + if (saved == null) { return null; } - if(saved.isExpired()) { + if (saved.isExpired()) { delete(saved.getId()); return null; } @@ -85,13 +86,13 @@ public class MapSessionRepository implements SessionRepository } public void delete(String id) { - sessions.remove(id); + this.sessions.remove(id); } public ExpiringSession createSession() { ExpiringSession result = new MapSession(); - if(defaultMaxInactiveInterval != null) { - result.setMaxInactiveIntervalInSeconds(defaultMaxInactiveInterval); + if (this.defaultMaxInactiveInterval != null) { + result.setMaxInactiveIntervalInSeconds(this.defaultMaxInactiveInterval); } return result; } diff --git a/spring-session/src/main/java/org/springframework/session/Session.java b/spring-session/src/main/java/org/springframework/session/Session.java index 7f94c2eb..5dcb1b36 100644 --- a/spring-session/src/main/java/org/springframework/session/Session.java +++ b/spring-session/src/main/java/org/springframework/session/Session.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session; import java.util.Set; @@ -27,7 +28,7 @@ import java.util.Set; public interface Session { /** - * Gets a unique string that identifies the {@link Session} + * Gets a unique string that identifies the {@link Session}. * * @return a unique string that identifies the {@link Session} */ @@ -59,8 +60,8 @@ public interface Session { void setAttribute(String attributeName, Object attributeValue); /** - * Removes the attribute with the provided attribute name + * Removes the attribute with the provided attribute name. * @param attributeName the name of the attribute to remove */ void removeAttribute(String attributeName); -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/SessionRepository.java b/spring-session/src/main/java/org/springframework/session/SessionRepository.java index c8ea352e..ae4c44f8 100644 --- a/spring-session/src/main/java/org/springframework/session/SessionRepository.java +++ b/spring-session/src/main/java/org/springframework/session/SessionRepository.java @@ -1,23 +1,25 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session; /** * A repository interface for managing {@link Session} instances. * + * @param the {@link Session} type * @author Rob Winch * @since 1.0 */ @@ -59,4 +61,4 @@ public interface SessionRepository { * @param id the {@link org.springframework.session.Session#getId()} to delete */ void delete(String id); -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSession.java b/spring-session/src/main/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSession.java index f3232f69..6133ce8c 100644 --- a/spring-session/src/main/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSession.java +++ b/spring-session/src/main/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.config.annotation.web.http; import java.lang.annotation.Documented; @@ -73,8 +74,8 @@ import org.springframework.session.events.SessionDestroyedEvent; * @author Rob Winch * @since 1.1 */ -@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) -@Target(value = { java.lang.annotation.ElementType.TYPE }) +@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) +@Target({ java.lang.annotation.ElementType.TYPE }) @Documented @Import(SpringHttpSessionConfiguration.class) @Configuration diff --git a/spring-session/src/main/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java b/spring-session/src/main/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java index a9056bde..b60ceeec 100644 --- a/spring-session/src/main/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java +++ b/spring-session/src/main/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.config.annotation.web.http; import java.util.ArrayList; @@ -85,7 +86,7 @@ public class SpringHttpSessionConfiguration { private CookieHttpSessionStrategy defaultHttpSessionStrategy = new CookieHttpSessionStrategy(); - private HttpSessionStrategy httpSessionStrategy = defaultHttpSessionStrategy; + private HttpSessionStrategy httpSessionStrategy = this.defaultHttpSessionStrategy; private List httpSessionListeners = new ArrayList(); @@ -93,22 +94,23 @@ public class SpringHttpSessionConfiguration { @Bean public SessionEventHttpSessionListenerAdapter sessionEventHttpSessionListenerAdapter() { - return new SessionEventHttpSessionListenerAdapter(httpSessionListeners); + return new SessionEventHttpSessionListenerAdapter(this.httpSessionListeners); } @Bean public SessionRepositoryFilter springSessionRepositoryFilter(SessionRepository sessionRepository) { SessionRepositoryFilter sessionRepositoryFilter = new SessionRepositoryFilter(sessionRepository); - sessionRepositoryFilter.setServletContext(servletContext); - if(httpSessionStrategy instanceof MultiHttpSessionStrategy) { - sessionRepositoryFilter.setHttpSessionStrategy((MultiHttpSessionStrategy) httpSessionStrategy); - } else { - sessionRepositoryFilter.setHttpSessionStrategy(httpSessionStrategy); + sessionRepositoryFilter.setServletContext(this.servletContext); + if (this.httpSessionStrategy instanceof MultiHttpSessionStrategy) { + sessionRepositoryFilter.setHttpSessionStrategy((MultiHttpSessionStrategy) this.httpSessionStrategy); + } + else { + sessionRepositoryFilter.setHttpSessionStrategy(this.httpSessionStrategy); } return sessionRepositoryFilter; } - @Autowired(required=false) + @Autowired(required = false) public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } diff --git a/spring-session/src/main/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepository.java b/spring-session/src/main/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepository.java index 47230c27..f898aeee 100644 --- a/spring-session/src/main/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepository.java +++ b/spring-session/src/main/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepository.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,8 +33,17 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; +import com.gemstone.gemfire.DataSerializable; +import com.gemstone.gemfire.DataSerializer; +import com.gemstone.gemfire.Delta; +import com.gemstone.gemfire.Instantiator; +import com.gemstone.gemfire.InvalidDeltaException; +import com.gemstone.gemfire.cache.EntryEvent; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.util.CacheListenerAdapter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; @@ -54,20 +63,12 @@ import org.springframework.session.events.SessionExpiredEvent; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -import com.gemstone.gemfire.DataSerializable; -import com.gemstone.gemfire.DataSerializer; -import com.gemstone.gemfire.Delta; -import com.gemstone.gemfire.Instantiator; -import com.gemstone.gemfire.InvalidDeltaException; -import com.gemstone.gemfire.cache.EntryEvent; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.util.CacheListenerAdapter; - /** * AbstractGemFireOperationsSessionRepository is an abstract base class encapsulating functionality common * to all implementations that support SessionRepository operations backed by GemFire. * * @author John Blum + * @since 1.1.0 * @see org.springframework.beans.factory.InitializingBean * @see org.springframework.context.ApplicationEventPublisher * @see org.springframework.context.ApplicationEventPublisherAware @@ -79,7 +80,6 @@ import com.gemstone.gemfire.cache.util.CacheListenerAdapter; * @see org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration * @see com.gemstone.gemfire.cache.Region * @see com.gemstone.gemfire.cache.util.CacheListenerAdapter - * @since 1.1.0 */ public abstract class AbstractGemFireOperationsSessionRepository extends CacheListenerAdapter implements InitializingBean, FindByIndexNameSessionRepository, @@ -140,7 +140,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * @see org.springframework.context.ApplicationEventPublisher */ protected ApplicationEventPublisher getApplicationEventPublisher() { - return applicationEventPublisher; + return this.applicationEventPublisher; } /** @@ -150,7 +150,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * and manage Session data. */ protected String getFullyQualifiedRegionName() { - return fullyQualifiedRegionName; + return this.fullyQualifiedRegionName; } /** @@ -170,7 +170,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * before it is considered expired. */ public int getMaxInactiveIntervalInSeconds() { - return maxInactiveIntervalInSeconds; + return this.maxInactiveIntervalInSeconds; } /** @@ -181,7 +181,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi * @see org.springframework.data.gemfire.GemfireOperations */ public GemfireOperations getTemplate() { - return template; + return this.template; } /** @@ -198,7 +198,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi Region region = ((GemfireAccessor) template).getRegion(); - fullyQualifiedRegionName = region.getFullPath(); + this.fullyQualifiedRegionName = region.getFullPath(); region.getAttributesMutator().addCacheListener(this); } @@ -318,7 +318,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi getApplicationEventPublisher().publishEvent(event); } catch (Throwable t) { - logger.error(String.format("error occurred publishing event (%1$s)", event), t); + this.logger.error(String.format("error occurred publishing event (%1$s)", event), t); } } @@ -346,7 +346,8 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi static { Instantiator.register(new Instantiator(GemFireSession.class, 800813552) { - @Override public DataSerializable newInstance() { + @Override + public DataSerializable newInstance() { return new GemFireSession(); } }); @@ -415,37 +416,37 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public synchronized String getId() { - return id; + return this.id; } /* (non-Javadoc) */ public synchronized long getCreationTime() { - return creationTime; + return this.creationTime; } /* (non-Javadoc) */ public void setAttribute(String attributeName, Object attributeValue) { - sessionAttributes.setAttribute(attributeName, attributeValue); + this.sessionAttributes.setAttribute(attributeName, attributeValue); } /* (non-Javadoc) */ public void removeAttribute(String attributeName) { - sessionAttributes.removeAttribute(attributeName); + this.sessionAttributes.removeAttribute(attributeName); } /* (non-Javadoc) */ public T getAttribute(String attributeName) { - return sessionAttributes.getAttribute(attributeName); + return this.sessionAttributes.getAttribute(attributeName); } /* (non-Javadoc) */ public Set getAttributeNames() { - return sessionAttributes.getAttributeNames(); + return this.sessionAttributes.getAttributeNames(); } /* (non-Javadoc) */ public GemFireSessionAttributes getAttributes() { - return sessionAttributes; + return this.sessionAttributes; } /* (non-Javadoc) */ @@ -470,7 +471,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public synchronized long getLastAccessedTime() { - return lastAccessedTime; + return this.lastAccessedTime; } /* (non-Javadoc) */ @@ -481,7 +482,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public synchronized int getMaxInactiveIntervalInSeconds() { - return maxInactiveIntervalInSeconds; + return this.maxInactiveIntervalInSeconds; } /* (non-Javadoc) */ @@ -497,7 +498,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi Object authentication = getAttribute(SPRING_SECURITY_CONTEXT); if (authentication != null) { - Expression expression = parser.parseExpression("authentication?.name"); + Expression expression = this.parser.parseExpression("authentication?.name"); principalName = expression.getValue(authentication, String.class); } } @@ -521,7 +522,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi out.writeUTF(principalName); } - writeObject(sessionAttributes, out); + writeObject(this.sessionAttributes, out); this.delta = false; } @@ -533,8 +534,8 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public synchronized void fromData(DataInput in) throws ClassNotFoundException, IOException { - id = in.readUTF(); - creationTime = in.readLong(); + this.id = in.readUTF(); + this.creationTime = in.readLong(); setLastAccessedTime(in.readLong()); setMaxInactiveIntervalInSeconds(in.readInt()); @@ -544,7 +545,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi setPrincipalName(in.readUTF()); } - sessionAttributes.from(this.readObject(in)); + this.sessionAttributes.from(this.readObject(in)); this.delta = false; } @@ -556,14 +557,14 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public synchronized boolean hasDelta() { - return (delta || sessionAttributes.hasDelta()); + return (this.delta || this.sessionAttributes.hasDelta()); } /* (non-Javadoc) */ public synchronized void toDelta(DataOutput out) throws IOException { out.writeLong(getLastAccessedTime()); out.writeInt(getMaxInactiveIntervalInSeconds()); - sessionAttributes.toDelta(out); + this.sessionAttributes.toDelta(out); this.delta = false; } @@ -571,7 +572,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi public synchronized void fromDelta(DataInput in) throws IOException { setLastAccessedTime(in.readLong()); setMaxInactiveIntervalInSeconds(in.readInt()); - sessionAttributes.fromDelta(in); + this.sessionAttributes.fromDelta(in); this.delta = false; } @@ -640,7 +641,8 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi static { Instantiator.register(new Instantiator(GemFireSessionAttributes.class, 800828008) { - @Override public DataSerializable newInstance() { + @Override + public DataSerializable newInstance() { return new GemFireSessionAttributes(); } }); @@ -663,10 +665,10 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public void setAttribute(String attributeName, Object attributeValue) { - synchronized (lock) { + synchronized (this.lock) { if (attributeValue != null) { - if (!attributeValue.equals(sessionAttributes.put(attributeName, attributeValue))) { - sessionAttributeDeltas.put(attributeName, attributeValue); + if (!attributeValue.equals(this.sessionAttributes.put(attributeName, attributeValue))) { + this.sessionAttributeDeltas.put(attributeName, attributeValue); } } else { @@ -677,9 +679,9 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public void removeAttribute(String attributeName) { - synchronized (lock) { - if (sessionAttributes.remove(attributeName) != null) { - sessionAttributeDeltas.put(attributeName, null); + synchronized (this.lock) { + if (this.sessionAttributes.remove(attributeName) != null) { + this.sessionAttributeDeltas.put(attributeName, null); } } } @@ -687,15 +689,15 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ @SuppressWarnings("unchecked") public T getAttribute(String attributeName) { - synchronized (lock) { - return (T) sessionAttributes.get(attributeName); + synchronized (this.lock) { + return (T) this.sessionAttributes.get(attributeName); } } /* (non-Javadoc) */ public Set getAttributeNames() { - synchronized (lock) { - return Collections.unmodifiableSet(new HashSet(sessionAttributes.keySet())); + synchronized (this.lock) { + return Collections.unmodifiableSet(new HashSet(this.sessionAttributes.keySet())); } } @@ -709,19 +711,21 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi @SuppressWarnings("all") public Set> entrySet() { return new AbstractSet>() { - @Override public Iterator> iterator() { - return Collections.unmodifiableMap(sessionAttributes).entrySet().iterator(); + @Override + public Iterator> iterator() { + return Collections.unmodifiableMap(GemFireSessionAttributes.this.sessionAttributes).entrySet().iterator(); } - @Override public int size() { - return sessionAttributes.size(); + @Override + public int size() { + return GemFireSessionAttributes.this.sessionAttributes.size(); } }; } /* (non-Javadoc) */ public void from(Session session) { - synchronized (lock) { + synchronized (this.lock) { for (String attributeName : session.getAttributeNames()) { setAttribute(attributeName, session.getAttribute(attributeName)); } @@ -730,7 +734,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public void from(GemFireSessionAttributes sessionAttributes) { - synchronized (lock) { + synchronized (this.lock) { for (String attributeName : sessionAttributes.getAttributeNames()) { setAttribute(attributeName, sessionAttributes.getAttribute(attributeName)); } @@ -739,7 +743,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public void toData(DataOutput out) throws IOException { - synchronized (lock) { + synchronized (this.lock) { Set attributeNames = getAttributeNames(); out.writeInt(attributeNames.size()); @@ -758,44 +762,44 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi /* (non-Javadoc) */ public void fromData(DataInput in) throws IOException, ClassNotFoundException { - synchronized (lock) { + synchronized (this.lock) { for (int count = in.readInt(); count > 0; count--) { setAttribute(in.readUTF(), readObject(in)); } - sessionAttributeDeltas.clear(); + this.sessionAttributeDeltas.clear(); } } /* (non-Javadoc) */ - T readObject(DataInput in) throws ClassNotFoundException , IOException { + T readObject(DataInput in) throws ClassNotFoundException, IOException { return DataSerializer.readObject(in); } /* (non-Javadoc) */ public boolean hasDelta() { - synchronized (lock) { - return !sessionAttributeDeltas.isEmpty(); + synchronized (this.lock) { + return !this.sessionAttributeDeltas.isEmpty(); } } /* (non-Javadoc) */ public void toDelta(DataOutput out) throws IOException { - synchronized (lock) { - out.writeInt(sessionAttributeDeltas.size()); + synchronized (this.lock) { + out.writeInt(this.sessionAttributeDeltas.size()); - for (Map.Entry entry : sessionAttributeDeltas.entrySet()) { + for (Map.Entry entry : this.sessionAttributeDeltas.entrySet()) { out.writeUTF(entry.getKey()); writeObject(entry.getValue(), out); } - sessionAttributeDeltas.clear(); + this.sessionAttributeDeltas.clear(); } } /* (non-Javadoc) */ public void fromDelta(DataInput in) throws InvalidDeltaException, IOException { - synchronized (lock) { + synchronized (this.lock) { try { int count = in.readInt(); @@ -807,7 +811,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi for (Map.Entry entry : deltas.entrySet()) { setAttribute(entry.getKey(), entry.getValue()); - sessionAttributeDeltas.remove(entry.getKey()); + this.sessionAttributeDeltas.remove(entry.getKey()); } } catch (ClassNotFoundException e) { @@ -818,7 +822,7 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi @Override public String toString() { - return sessionAttributes.toString(); + return this.sessionAttributes.toString(); } } diff --git a/spring-session/src/main/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepository.java b/spring-session/src/main/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepository.java index dfa49856..28a00dd7 100644 --- a/spring-session/src/main/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepository.java +++ b/spring-session/src/main/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepository.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,21 +19,21 @@ package org.springframework.session.data.gemfire; import java.util.HashMap; import java.util.Map; +import com.gemstone.gemfire.cache.query.SelectResults; + import org.springframework.data.gemfire.GemfireOperations; import org.springframework.session.ExpiringSession; -import com.gemstone.gemfire.cache.query.SelectResults; - /** * The GemFireOperationsSessionRepository class is a Spring SessionRepository implementation that interfaces with * and uses GemFire to back and store Spring Sessions. * * @author John Blum + * @since 1.1.0 * @see org.springframework.data.gemfire.GemfireOperations * @see org.springframework.session.ExpiringSession * @see org.springframework.session.Session * @see org.springframework.session.data.gemfire.AbstractGemFireOperationsSessionRepository - * @since 1.1.0 */ public class GemFireOperationsSessionRepository extends AbstractGemFireOperationsSessionRepository { diff --git a/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSession.java b/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSession.java index a6229563..b245e52d 100644 --- a/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSession.java +++ b/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/EnableGemFireHttpSession.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,12 +22,12 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - import com.gemstone.gemfire.cache.RegionShortcut; import com.gemstone.gemfire.cache.client.ClientRegionShortcut; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + /** * Add this annotation to an {@code @Configuration} class to expose the SessionRepositoryFilter * as a bean named "springSessionRepositoryFilter" and backed by Pivotal GemFire or Apache Geode. diff --git a/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.java b/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.java index 8ec6f602..d69ba30e 100644 --- a/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.java +++ b/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,6 +18,14 @@ package org.springframework.session.data.gemfire.config.annotation.web.http; import java.util.concurrent.TimeUnit; +import com.gemstone.gemfire.cache.ExpirationAction; +import com.gemstone.gemfire.cache.ExpirationAttributes; +import com.gemstone.gemfire.cache.GemFireCache; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.RegionAttributes; +import com.gemstone.gemfire.cache.RegionShortcut; +import com.gemstone.gemfire.cache.client.ClientRegionShortcut; + import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; @@ -40,19 +48,12 @@ import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; -import com.gemstone.gemfire.cache.ExpirationAction; -import com.gemstone.gemfire.cache.ExpirationAttributes; -import com.gemstone.gemfire.cache.GemFireCache; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionAttributes; -import com.gemstone.gemfire.cache.RegionShortcut; -import com.gemstone.gemfire.cache.client.ClientRegionShortcut; - /** * The GemFireHttpSessionConfiguration class is a Spring @Configuration class used to configure and initialize * Pivotal GemFire (or Apache Geode) as a clustered, replicated HttpSession provider implementation in Spring Session. * * @author John Blum + * @since 1.1.0 * @see org.springframework.beans.factory.BeanClassLoaderAware * @see org.springframework.context.annotation.Bean * @see org.springframework.context.annotation.Configuration @@ -71,23 +72,40 @@ import com.gemstone.gemfire.cache.client.ClientRegionShortcut; * @see com.gemstone.gemfire.cache.RegionAttributes * @see com.gemstone.gemfire.cache.RegionShortcut * @see com.gemstone.gemfire.cache.client.ClientRegionShortcut - * @since 1.1.0 */ @Configuration public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfiguration implements BeanClassLoaderAware, ImportAware { + /** + * The default maximum interval in seconds in which a Session can remain inactive + * before it is considered expired. + */ public static final int DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS = (int) TimeUnit.MINUTES.toSeconds(30); protected static final Class SPRING_SESSION_GEMFIRE_REGION_KEY_CONSTRAINT = Object.class; protected static final Class SPRING_SESSION_GEMFIRE_REGION_VALUE_CONSTRAINT = GemFireSession.class; + /** + * The default {@link ClientRegionShortcut} used to configure the GemFire ClientCache + * Region that will store Spring Sessions. + */ public static final ClientRegionShortcut DEFAULT_CLIENT_REGION_SHORTCUT = ClientRegionShortcut.PROXY; + /** + * The default {@link RegionShortcut} used to configure the GemFire Cache Region that + * will store Spring Sessions. + */ public static final RegionShortcut DEFAULT_SERVER_REGION_SHORTCUT = RegionShortcut.PARTITION; + /** + * The default name of the Gemfire (Client)Cache Region used to store Sessions. + */ public static final String DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME = "ClusteredSpringSessions"; + /** + * The default names of all Session attributes that should be indexed by GemFire. + */ public static final String[] DEFAULT_INDEXABLE_SESSION_ATTRIBUTES = new String[0]; private int maxInactiveIntervalInSeconds = DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS; @@ -120,7 +138,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see java.lang.ClassLoader */ protected ClassLoader getBeanClassLoader() { - return beanClassLoader; + return this.beanClassLoader; } /** @@ -143,7 +161,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see EnableGemFireHttpSession#clientRegionShortcut() */ protected ClientRegionShortcut getClientRegionShortcut() { - return (clientRegionShortcut != null ? clientRegionShortcut : DEFAULT_CLIENT_REGION_SHORTCUT); + return (this.clientRegionShortcut != null ? this.clientRegionShortcut : DEFAULT_CLIENT_REGION_SHORTCUT); } /** @@ -164,7 +182,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see EnableGemFireHttpSession#indexableSessionAttributes() */ protected String[] getIndexableSessionAttributes() { - return (indexableSessionAttributes != null ? indexableSessionAttributes : DEFAULT_INDEXABLE_SESSION_ATTRIBUTES); + return (this.indexableSessionAttributes != null ? this.indexableSessionAttributes : DEFAULT_INDEXABLE_SESSION_ATTRIBUTES); } /** @@ -207,7 +225,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see EnableGemFireHttpSession#maxInactiveIntervalInSeconds() */ protected int getMaxInactiveIntervalInSeconds() { - return maxInactiveIntervalInSeconds; + return this.maxInactiveIntervalInSeconds; } /** @@ -217,7 +235,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see com.gemstone.gemfire.cache.RegionShortcut */ public void setServerRegionShortcut(RegionShortcut shortcut) { - serverRegionShortcut = shortcut; + this.serverRegionShortcut = shortcut; } /** @@ -229,7 +247,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see EnableGemFireHttpSession#serverRegionShortcut() */ protected RegionShortcut getServerRegionShortcut() { - return (serverRegionShortcut != null ? serverRegionShortcut : DEFAULT_SERVER_REGION_SHORTCUT); + return (this.serverRegionShortcut != null ? this.serverRegionShortcut : DEFAULT_SERVER_REGION_SHORTCUT); } /** @@ -251,7 +269,7 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat * @see EnableGemFireHttpSession#regionName() */ protected String getSpringSessionGemFireRegionName() { - return (StringUtils.hasText(springSessionGemFireRegionName) ? springSessionGemFireRegionName + return (StringUtils.hasText(this.springSessionGemFireRegionName) ? this.springSessionGemFireRegionName : DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); } @@ -408,7 +426,8 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat @DependsOn(DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME) public IndexFactoryBean principalNameIndex(final GemFireCache gemfireCache) { IndexFactoryBean index = new IndexFactoryBean() { - @Override public void afterPropertiesSet() throws Exception { + @Override + public void afterPropertiesSet() throws Exception { if (GemFireUtils.isPeer(gemfireCache)) { super.afterPropertiesSet(); } @@ -439,7 +458,8 @@ public class GemFireHttpSessionConfiguration extends SpringHttpSessionConfigurat @DependsOn(DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME) public IndexFactoryBean sessionAttributesIndex(final GemFireCache gemfireCache) { IndexFactoryBean index = new IndexFactoryBean() { - @Override public void afterPropertiesSet() throws Exception { + @Override + public void afterPropertiesSet() throws Exception { if (GemFireUtils.isPeer(gemfireCache) && !ObjectUtils.isEmpty(getIndexableSessionAttributes())) { super.afterPropertiesSet(); } diff --git a/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBean.java b/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBean.java index 579a9674..28fea0af 100644 --- a/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBean.java +++ b/spring-session/src/main/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBean.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +16,13 @@ package org.springframework.session.data.gemfire.config.annotation.web.http.support; +import com.gemstone.gemfire.cache.GemFireCache; +import com.gemstone.gemfire.cache.InterestResultPolicy; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.RegionAttributes; +import com.gemstone.gemfire.cache.RegionShortcut; +import com.gemstone.gemfire.cache.client.ClientRegionShortcut; + import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.data.gemfire.GenericRegionFactoryBean; @@ -26,18 +33,14 @@ import org.springframework.session.data.gemfire.support.GemFireUtils; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -import com.gemstone.gemfire.cache.GemFireCache; -import com.gemstone.gemfire.cache.InterestResultPolicy; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionAttributes; -import com.gemstone.gemfire.cache.RegionShortcut; -import com.gemstone.gemfire.cache.client.ClientRegionShortcut; - /** * The GemFireCacheTypeAwareRegionFactoryBean class is a Spring {@link FactoryBean} used to construct, configure * and initialize the GemFire cache {@link Region} used to store and manage Session state. * + * @param the type of keys + * @param the type of values * @author John Blum + * @since 1.1.0 * @see org.springframework.beans.factory.FactoryBean * @see org.springframework.beans.factory.InitializingBean * @see org.springframework.data.gemfire.GenericRegionFactoryBean @@ -49,7 +52,6 @@ import com.gemstone.gemfire.cache.client.ClientRegionShortcut; * @see com.gemstone.gemfire.cache.RegionAttributes * @see com.gemstone.gemfire.cache.RegionShortcut * @see com.gemstone.gemfire.cache.client.ClientRegionShortcut - * @since 1.1.0 */ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean>, InitializingBean { @@ -88,7 +90,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean public void afterPropertiesSet() throws Exception { GemFireCache gemfireCache = getGemfireCache(); - region = (GemFireUtils.isClient(gemfireCache) ? newClientRegion(gemfireCache) + this.region = (GemFireUtils.isClient(gemfireCache) ? newClientRegion(gemfireCache) : newServerRegion(gemfireCache)); } @@ -179,7 +181,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean * @see com.gemstone.gemfire.cache.Region */ public Region getObject() throws Exception { - return region; + return this.region; } /** @@ -191,7 +193,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean * @see java.lang.Class */ public Class getObjectType() { - return (region != null ? region.getClass() : Region.class); + return (this.region != null ? this.region.getClass() : Region.class); } /** @@ -223,7 +225,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean * @see com.gemstone.gemfire.cache.client.ClientRegionShortcut */ protected ClientRegionShortcut getClientRegionShortcut() { - return (clientRegionShortcut != null ? clientRegionShortcut : DEFAULT_CLIENT_REGION_SHORTCUT); + return (this.clientRegionShortcut != null ? this.clientRegionShortcut : DEFAULT_CLIENT_REGION_SHORTCUT); } /** @@ -244,8 +246,8 @@ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean * @throws IllegalStateException if the {@link GemFireCache} reference is null. */ protected GemFireCache getGemfireCache() { - Assert.state(gemfireCache != null, "A reference to a GemFireCache was not properly configured"); - return gemfireCache; + Assert.state(this.gemfireCache != null, "A reference to a GemFireCache was not properly configured"); + return this.gemfireCache; } /** @@ -267,7 +269,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean * @see com.gemstone.gemfire.cache.RegionAttributes */ protected RegionAttributes getRegionAttributes() { - return regionAttributes; + return this.regionAttributes; } /** @@ -287,7 +289,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean * @see com.gemstone.gemfire.cache.Region#getName() */ protected String getRegionName() { - return (StringUtils.hasText(regionName) ? regionName : DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); + return (StringUtils.hasText(this.regionName) ? this.regionName : DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); } /** @@ -308,7 +310,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean implements FactoryBean * @see com.gemstone.gemfire.cache.RegionShortcut */ protected RegionShortcut getServerRegionShortcut() { - return (serverRegionShortcut != null ? serverRegionShortcut : DEFAULT_SERVER_REGION_SHORTCUT); + return (this.serverRegionShortcut != null ? this.serverRegionShortcut : DEFAULT_SERVER_REGION_SHORTCUT); } } diff --git a/spring-session/src/main/java/org/springframework/session/data/gemfire/support/GemFireUtils.java b/spring-session/src/main/java/org/springframework/session/data/gemfire/support/GemFireUtils.java index 2a510e24..48234c40 100644 --- a/spring-session/src/main/java/org/springframework/session/data/gemfire/support/GemFireUtils.java +++ b/spring-session/src/main/java/org/springframework/session/data/gemfire/support/GemFireUtils.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-session/src/main/java/org/springframework/session/data/redis/RedisFlushMode.java b/spring-session/src/main/java/org/springframework/session/data/redis/RedisFlushMode.java index 089d2e93..6847a8da 100644 --- a/spring-session/src/main/java/org/springframework/session/data/redis/RedisFlushMode.java +++ b/spring-session/src/main/java/org/springframework/session/data/redis/RedisFlushMode.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis; import org.springframework.session.SessionRepository; diff --git a/spring-session/src/main/java/org/springframework/session/data/redis/RedisOperationsSessionRepository.java b/spring-session/src/main/java/org/springframework/session/data/redis/RedisOperationsSessionRepository.java index 57d0f6a8..92092a49 100644 --- a/spring-session/src/main/java/org/springframework/session/data/redis/RedisOperationsSessionRepository.java +++ b/spring-session/src/main/java/org/springframework/session/data/redis/RedisOperationsSessionRepository.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session.data.redis; import java.util.Collections; @@ -23,6 +24,7 @@ import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.redis.connection.Message; @@ -245,9 +247,8 @@ import org.springframework.util.Assert; * if the TTL on that key is expired. *

* - * @since 1.0 - * * @author Rob Winch + * @since 1.0 */ public class RedisOperationsSessionRepository implements FindByIndexNameSessionRepository, MessageListener { private static final Log logger = LogFactory.getLog(RedisOperationsSessionRepository.class); @@ -257,22 +258,22 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR static PrincipalNameResolver PRINCIPAL_NAME_RESOLVER = new PrincipalNameResolver(); /** - * The default prefix for each key and channel in Redis used by Spring Session + * The default prefix for each key and channel in Redis used by Spring Session. */ static final String DEFAULT_SPRING_SESSION_REDIS_PREFIX = "spring:session:"; /** - * The key in the Hash representing {@link org.springframework.session.ExpiringSession#getCreationTime()} + * The key in the Hash representing {@link org.springframework.session.ExpiringSession#getCreationTime()}. */ static final String CREATION_TIME_ATTR = "creationTime"; /** - * The key in the Hash representing {@link org.springframework.session.ExpiringSession#getMaxInactiveIntervalInSeconds()} + * The key in the Hash representing {@link org.springframework.session.ExpiringSession#getMaxInactiveIntervalInSeconds()}. */ static final String MAX_INACTIVE_ATTR = "maxInactiveInterval"; /** - * The key in the Hash representing {@link org.springframework.session.ExpiringSession#getLastAccessedTime()} + * The key in the Hash representing {@link org.springframework.session.ExpiringSession#getLastAccessedTime()}. */ static final String LAST_ACCESSED_ATTR = "lastAccessedTime"; @@ -288,7 +289,7 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR */ private String keyPrefix = DEFAULT_SPRING_SESSION_REDIS_PREFIX; - private final RedisOperations sessionRedisOperations; + private final RedisOperations sessionRedisOperations; private final RedisSessionExpirationPolicy expirationPolicy; @@ -376,14 +377,14 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR public void save(RedisSession session) { session.saveDelta(); - if(session.isNew()) { + if (session.isNew()) { String sessionCreatedKey = getSessionCreatedChannel(session.getId()); this.sessionRedisOperations.convertAndSend(sessionCreatedKey, session.delta); session.setNew(false); } } - @Scheduled(cron="0 * * * * *") + @Scheduled(cron = "0 * * * * *") public void cleanupExpiredSessions() { this.expirationPolicy.cleanExpiredSessions(); } @@ -392,16 +393,16 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR return getSession(id, false); } - public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { - if(!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { + public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { + if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } String principalKey = getPrincipalKey(indexValue); - Set sessionIds = sessionRedisOperations.boundSetOps(principalKey).members(); - Map sessions = new HashMap(sessionIds.size()); - for(Object id : sessionIds) { + Set sessionIds = this.sessionRedisOperations.boundSetOps(principalKey).members(); + Map sessions = new HashMap(sessionIds.size()); + for (Object id : sessionIds) { RedisSession session = getSession((String) id); - if(session != null) { + if (session != null) { sessions.put(session.getId(), session); } } @@ -409,21 +410,21 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR } /** - * + * Gets the session. * @param id the session id * @param allowExpired * if true, will also include expired sessions that have not been * deleted. If false, will ensure expired sessions are not * returned. - * @return + * @return the Redis session */ private RedisSession getSession(String id, boolean allowExpired) { Map entries = getSessionBoundHashOperations(id).entries(); - if(entries.isEmpty()) { + if (entries.isEmpty()) { return null; } MapSession loaded = loadSession(id, entries); - if(!allowExpired && loaded.isExpired()) { + if (!allowExpired && loaded.isExpired()) { return null; } RedisSession result = new RedisSession(loaded); @@ -433,15 +434,18 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR private MapSession loadSession(String id, Map entries) { MapSession loaded = new MapSession(id); - for(Map.Entry entry : entries.entrySet()) { + for (Map.Entry entry : entries.entrySet()) { String key = (String) entry.getKey(); - if(CREATION_TIME_ATTR.equals(key)) { + if (CREATION_TIME_ATTR.equals(key)) { loaded.setCreationTime((Long) entry.getValue()); - } else if(MAX_INACTIVE_ATTR.equals(key)) { + } + else if (MAX_INACTIVE_ATTR.equals(key)) { loaded.setMaxInactiveIntervalInSeconds((Integer) entry.getValue()); - } else if(LAST_ACCESSED_ATTR.equals(key)) { + } + else if (LAST_ACCESSED_ATTR.equals(key)) { loaded.setLastAccessedTime((Long) entry.getValue()); - } else if(key.startsWith(SESSION_ATTR_PREFIX)) { + } + else if (key.startsWith(SESSION_ATTR_PREFIX)) { loaded.setAttribute(key.substring(SESSION_ATTR_PREFIX.length()), entry.getValue()); } } @@ -450,12 +454,12 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR public void delete(String sessionId) { RedisSession session = getSession(sessionId, true); - if(session == null) { + if (session == null) { return; } cleanupPrincipalIndex(session); - expirationPolicy.onDelete(session); + this.expirationPolicy.onDelete(session); String expireKey = getExpiredKey(session.getId()); this.sessionRedisOperations.delete(expireKey); @@ -466,8 +470,8 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR public RedisSession createSession() { RedisSession redisSession = new RedisSession(); - if(defaultMaxInactiveInterval != null) { - redisSession.setMaxInactiveIntervalInSeconds(defaultMaxInactiveInterval); + if (this.defaultMaxInactiveInterval != null) { + redisSession.setMaxInactiveIntervalInSeconds(this.defaultMaxInactiveInterval); } return redisSession; } @@ -476,42 +480,43 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR public void onMessage(Message message, byte[] pattern) { byte[] messageChannel = message.getChannel(); byte[] messageBody = message.getBody(); - if(messageChannel == null || messageBody == null) { + if (messageChannel == null || messageBody == null) { return; } String channel = new String(messageChannel); - if(channel.startsWith(getSessionCreatedChannelPrefix())) { + if (channel.startsWith(getSessionCreatedChannelPrefix())) { // TODO: is this thread safe? - Map loaded = (Map) defaultSerializer.deserialize(message.getBody()); + Map loaded = (Map) this.defaultSerializer.deserialize(message.getBody()); handleCreated(loaded, channel); return; } String body = new String(messageBody); - if(!body.startsWith(getExpiredKeyPrefix())) { + if (!body.startsWith(getExpiredKeyPrefix())) { return; } boolean isDeleted = channel.endsWith(":del"); - if(isDeleted || channel.endsWith(":expired")) { + if (isDeleted || channel.endsWith(":expired")) { int beginIndex = body.lastIndexOf(":") + 1; int endIndex = body.length(); String sessionId = body.substring(beginIndex, endIndex); RedisSession session = getSession(sessionId, true); - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Publishing SessionDestroyedEvent for session " + sessionId); } cleanupPrincipalIndex(session); - if(isDeleted) { + if (isDeleted) { handleDeleted(sessionId, session); - } else { + } + else { handleExpired(sessionId, session); } @@ -520,34 +525,36 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR } private void cleanupPrincipalIndex(RedisSession session) { - if(session == null) { + if (session == null) { return; } String sessionId = session.getId(); String principal = PRINCIPAL_NAME_RESOLVER.resolvePrincipal(session); - if(principal != null) { - sessionRedisOperations.boundSetOps(getPrincipalKey(principal)).remove(sessionId); + if (principal != null) { + this.sessionRedisOperations.boundSetOps(getPrincipalKey(principal)).remove(sessionId); } } - public void handleCreated(Map loaded, String channel) { + public void handleCreated(Map loaded, String channel) { String id = channel.substring(channel.lastIndexOf(":") + 1); ExpiringSession session = loadSession(id, loaded); publishEvent(new SessionCreatedEvent(this, session)); } private void handleDeleted(String sessionId, RedisSession session) { - if(session == null) { + if (session == null) { publishEvent(new SessionDeletedEvent(this, sessionId)); - } else { + } + else { publishEvent(new SessionDeletedEvent(this, session)); } } private void handleExpired(String sessionId, RedisSession session) { - if(session == null) { + if (session == null) { publishEvent(new SessionExpiredEvent(this, sessionId)); - } else { + } + else { publishEvent(new SessionExpiredEvent(this, session)); } } @@ -605,7 +612,7 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR } /** - * Gets the {@link BoundHashOperations} to operate on a {@link Session} + * Gets the {@link BoundHashOperations} to operate on a {@link Session}. * @param sessionId the id of the {@link Session} to work with * @return the {@link BoundHashOperations} to operate on a {@link Session} */ @@ -615,17 +622,17 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR } /** - * Gets the key for the specified session attribute + * Gets the key for the specified session attribute. * - * @param attributeName - * @return + * @param attributeName the attribute name + * @return the attribute key name */ static String getSessionAttrNameKey(String attributeName) { return SESSION_ATTR_PREFIX + attributeName; } - private static RedisTemplate createDefaultTemplate(RedisConnectionFactory connectionFactory) { - Assert.notNull(connectionFactory,"connectionFactory cannot be null"); + private static RedisTemplate createDefaultTemplate(RedisConnectionFactory connectionFactory) { + Assert.notNull(connectionFactory, "connectionFactory cannot be null"); RedisTemplate template = new RedisTemplate(); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); @@ -640,13 +647,13 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR * {@link org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession#saveDelta()} is invoked * all the attributes that have been changed will be persisted. * - * @since 1.0 * @author Rob Winch + * @since 1.0 */ final class RedisSession implements ExpiringSession { private final MapSession cached; private Long originalLastAccessTime; - private Map delta = new HashMap(); + private Map delta = new HashMap(); private boolean isNew; private String originalPrincipalName; @@ -655,15 +662,15 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR */ RedisSession() { this(new MapSession()); - delta.put(CREATION_TIME_ATTR, getCreationTime()); - delta.put(MAX_INACTIVE_ATTR, getMaxInactiveIntervalInSeconds()); - delta.put(LAST_ACCESSED_ATTR, getLastAccessedTime()); + this.delta.put(CREATION_TIME_ATTR, getCreationTime()); + this.delta.put(MAX_INACTIVE_ATTR, getMaxInactiveIntervalInSeconds()); + this.delta.put(LAST_ACCESSED_ATTR, getLastAccessedTime()); this.isNew = true; flushImmediateIfNecessary(); } /** - * Creates a new instance from the provided {@link MapSession} + * Creates a new instance from the provided {@link MapSession}. * * @param cached the {@MapSession} that represents the persisted session that was retrieved. Cannot be null. */ @@ -678,64 +685,64 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR } public void setLastAccessedTime(long lastAccessedTime) { - cached.setLastAccessedTime(lastAccessedTime); - delta.put(LAST_ACCESSED_ATTR, getLastAccessedTime()); + this.cached.setLastAccessedTime(lastAccessedTime); + this.delta.put(LAST_ACCESSED_ATTR, getLastAccessedTime()); flushImmediateIfNecessary(); } public boolean isExpired() { - return cached.isExpired(); + return this.cached.isExpired(); } public boolean isNew() { - return isNew; + return this.isNew; } public long getCreationTime() { - return cached.getCreationTime(); + return this.cached.getCreationTime(); } public String getId() { - return cached.getId(); + return this.cached.getId(); } public long getLastAccessedTime() { - return cached.getLastAccessedTime(); + return this.cached.getLastAccessedTime(); } public void setMaxInactiveIntervalInSeconds(int interval) { - cached.setMaxInactiveIntervalInSeconds(interval); - delta.put(MAX_INACTIVE_ATTR, getMaxInactiveIntervalInSeconds()); + this.cached.setMaxInactiveIntervalInSeconds(interval); + this.delta.put(MAX_INACTIVE_ATTR, getMaxInactiveIntervalInSeconds()); flushImmediateIfNecessary(); } public int getMaxInactiveIntervalInSeconds() { - return cached.getMaxInactiveIntervalInSeconds(); + return this.cached.getMaxInactiveIntervalInSeconds(); } @SuppressWarnings("unchecked") public Object getAttribute(String attributeName) { - return cached.getAttribute(attributeName); + return this.cached.getAttribute(attributeName); } public Set getAttributeNames() { - return cached.getAttributeNames(); + return this.cached.getAttributeNames(); } public void setAttribute(String attributeName, Object attributeValue) { - cached.setAttribute(attributeName, attributeValue); - delta.put(getSessionAttrNameKey(attributeName), attributeValue); + this.cached.setAttribute(attributeName, attributeValue); + this.delta.put(getSessionAttrNameKey(attributeName), attributeValue); flushImmediateIfNecessary(); } public void removeAttribute(String attributeName) { - cached.removeAttribute(attributeName); - delta.put(getSessionAttrNameKey(attributeName), null); + this.cached.removeAttribute(attributeName); + this.delta.put(getSessionAttrNameKey(attributeName), null); flushImmediateIfNecessary(); } private void flushImmediateIfNecessary() { - if(redisFlushMode == RedisFlushMode.IMMEDIATE) { + if (RedisOperationsSessionRepository.this.redisFlushMode == RedisFlushMode.IMMEDIATE) { saveDelta(); } } @@ -745,40 +752,43 @@ public class RedisOperationsSessionRepository implements FindByIndexNameSessionR */ private void saveDelta() { String sessionId = getId(); - getSessionBoundHashOperations(sessionId).putAll(delta); + getSessionBoundHashOperations(sessionId).putAll(this.delta); String principalSessionKey = getSessionAttrNameKey(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); String securityPrincipalSessionKey = getSessionAttrNameKey(SPRING_SECURITY_CONTEXT); - if(delta.containsKey(principalSessionKey) || delta.containsKey(securityPrincipalSessionKey)) { - if(originalPrincipalName != null) { - String originalPrincipalRedisKey = getPrincipalKey((String) originalPrincipalName); - sessionRedisOperations.boundSetOps(originalPrincipalRedisKey).remove(sessionId); + if (this.delta.containsKey(principalSessionKey) || this.delta.containsKey(securityPrincipalSessionKey)) { + if (this.originalPrincipalName != null) { + String originalPrincipalRedisKey = getPrincipalKey((String) this.originalPrincipalName); + RedisOperationsSessionRepository.this.sessionRedisOperations.boundSetOps(originalPrincipalRedisKey).remove(sessionId); } String principal = PRINCIPAL_NAME_RESOLVER.resolvePrincipal(this); - originalPrincipalName = principal; - if(principal != null) { + this.originalPrincipalName = principal; + if (principal != null) { String principalRedisKey = getPrincipalKey(principal); - sessionRedisOperations.boundSetOps(principalRedisKey).add(sessionId); + RedisOperationsSessionRepository.this.sessionRedisOperations.boundSetOps(principalRedisKey).add(sessionId); } } - delta = new HashMap(delta.size()); + this.delta = new HashMap(this.delta.size()); - Long originalExpiration = originalLastAccessTime == null ? null : originalLastAccessTime + TimeUnit.SECONDS.toMillis(getMaxInactiveIntervalInSeconds()) ; - expirationPolicy.onExpirationUpdated(originalExpiration, this); + Long originalExpiration = this.originalLastAccessTime == null ? null : this.originalLastAccessTime + TimeUnit.SECONDS.toMillis(getMaxInactiveIntervalInSeconds()); + RedisOperationsSessionRepository.this.expirationPolicy.onExpirationUpdated(originalExpiration, this); } } + /** + * Principal name resolver helper class. + */ static class PrincipalNameResolver { private SpelExpressionParser parser = new SpelExpressionParser(); public String resolvePrincipal(Session session) { String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME); - if(principalName != null) { + if (principalName != null) { return principalName; } Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); - if(authentication != null) { - Expression expression = parser.parseExpression("authentication?.name"); + if (authentication != null) { + Expression expression = this.parser.parseExpression("authentication?.name"); return expression.getValue(authentication, String.class); } return null; diff --git a/spring-session/src/main/java/org/springframework/session/data/redis/RedisSessionExpirationPolicy.java b/spring-session/src/main/java/org/springframework/session/data/redis/RedisSessionExpirationPolicy.java index c8782a26..cb986e8f 100644 --- a/spring-session/src/main/java/org/springframework/session/data/redis/RedisSessionExpirationPolicy.java +++ b/spring-session/src/main/java/org/springframework/session/data/redis/RedisSessionExpirationPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis; import java.util.Calendar; @@ -22,6 +23,7 @@ import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.data.redis.core.RedisOperations; import org.springframework.session.ExpiringSession; @@ -49,12 +51,12 @@ final class RedisSessionExpirationPolicy { private static final Log logger = LogFactory.getLog(RedisSessionExpirationPolicy.class); - private final RedisOperations redis; + private final RedisOperations redis; private final RedisOperationsSessionRepository redisSession; - public RedisSessionExpirationPolicy( - RedisOperations sessionRedisOperations, RedisOperationsSessionRepository redisSession) { + RedisSessionExpirationPolicy( + RedisOperations sessionRedisOperations, RedisOperationsSessionRepository redisSession) { super(); this.redis = sessionRedisOperations; this.redisSession = redisSession; @@ -63,23 +65,23 @@ final class RedisSessionExpirationPolicy { public void onDelete(ExpiringSession session) { long toExpire = roundUpToNextMinute(expiresInMillis(session)); String expireKey = getExpirationKey(toExpire); - redis.boundSetOps(expireKey).remove(session.getId()); + this.redis.boundSetOps(expireKey).remove(session.getId()); } public void onExpirationUpdated(Long originalExpirationTimeInMilli, ExpiringSession session) { String keyToExpire = "expires:" + session.getId(); long toExpire = roundUpToNextMinute(expiresInMillis(session)); - if(originalExpirationTimeInMilli != null) { + if (originalExpirationTimeInMilli != null) { long originalRoundedUp = roundUpToNextMinute(originalExpirationTimeInMilli); - if(toExpire != originalRoundedUp) { + if (toExpire != originalRoundedUp) { String expireKey = getExpirationKey(originalRoundedUp); - redis.boundSetOps(expireKey).remove(keyToExpire); + this.redis.boundSetOps(expireKey).remove(keyToExpire); } } String expireKey = getExpirationKey(toExpire); - BoundSetOperations expireOperations = redis.boundSetOps(expireKey); + BoundSetOperations expireOperations = this.redis.boundSetOps(expireKey); expireOperations.add(keyToExpire); long sessionExpireInSeconds = session.getMaxInactiveIntervalInSeconds(); @@ -87,13 +89,14 @@ final class RedisSessionExpirationPolicy { String sessionKey = getSessionKey(keyToExpire); expireOperations.expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); - if(sessionExpireInSeconds == 0) { - redis.delete(sessionKey); - } else { - redis.boundValueOps(sessionKey).append(""); - redis.boundValueOps(sessionKey).expire(sessionExpireInSeconds, TimeUnit.SECONDS); + if (sessionExpireInSeconds == 0) { + this.redis.delete(sessionKey); } - redis.boundHashOps(getSessionKey(session.getId())).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); + else { + this.redis.boundValueOps(sessionKey).append(""); + this.redis.boundValueOps(sessionKey).expire(sessionExpireInSeconds, TimeUnit.SECONDS); + } + this.redis.boundHashOps(getSessionKey(session.getId())).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); } String getExpirationKey(long expires) { @@ -108,14 +111,14 @@ final class RedisSessionExpirationPolicy { long now = System.currentTimeMillis(); long prevMin = roundDownMinute(now); - if(logger.isDebugEnabled()) { - logger.debug("Cleaning up sessions expiring at "+ new Date(prevMin)); + if (logger.isDebugEnabled()) { + logger.debug("Cleaning up sessions expiring at " + new Date(prevMin)); } String expirationKey = getExpirationKey(prevMin); - Set sessionsToExpire = redis.boundSetOps(expirationKey).members(); - redis.delete(expirationKey); - for(Object session : sessionsToExpire) { + Set sessionsToExpire = this.redis.boundSetOps(expirationKey).members(); + this.redis.delete(expirationKey); + for (Object session : sessionsToExpire) { String sessionKey = getSessionKey((String) session); touch(sessionKey); } @@ -125,10 +128,10 @@ final class RedisSessionExpirationPolicy { * By trying to access the session we only trigger a deletion if it the TTL is expired. This is done to handle * https://github.com/spring-projects/spring-session/issues/93 * - * @param key + * @param key the key */ private void touch(String key) { - redis.hasKey(key); + this.redis.hasKey(key); } static long expiresInMillis(ExpiringSession session) { diff --git a/spring-session/src/main/java/org/springframework/session/data/redis/SessionMessageListener.java b/spring-session/src/main/java/org/springframework/session/data/redis/SessionMessageListener.java index a9ca014b..26111583 100644 --- a/spring-session/src/main/java/org/springframework/session/data/redis/SessionMessageListener.java +++ b/spring-session/src/main/java/org/springframework/session/data/redis/SessionMessageListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.redis.connection.Message; @@ -42,7 +44,7 @@ public class SessionMessageListener implements MessageListener { private final ApplicationEventPublisher eventPublisher; /** - * Creates a new instance + * Creates a new instance. * * @param eventPublisher the {@link ApplicationEventPublisher} to use. Cannot be null. */ @@ -54,15 +56,15 @@ public class SessionMessageListener implements MessageListener { public void onMessage(Message message, byte[] pattern) { byte[] messageChannel = message.getChannel(); byte[] messageBody = message.getBody(); - if(messageChannel == null || messageBody == null) { + if (messageChannel == null || messageBody == null) { return; } String channel = new String(messageChannel); - if(!(channel.endsWith(":del") || channel.endsWith(":expired"))) { + if (!(channel.endsWith(":del") || channel.endsWith(":expired"))) { return; } String body = new String(messageBody); - if(!body.startsWith("spring:session:sessions:")) { + if (!body.startsWith("spring:session:sessions:")) { return; } @@ -70,13 +72,14 @@ public class SessionMessageListener implements MessageListener { int endIndex = body.length(); String sessionId = body.substring(beginIndex, endIndex); - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Publishing SessionDestroyedEvent for session " + sessionId); } - if(channel.endsWith(":del")) { + if (channel.endsWith(":del")) { publishEvent(new SessionDeletedEvent(this, sessionId)); - } else { + } + else { publishEvent(new SessionExpiredEvent(this, sessionId)); } } diff --git a/spring-session/src/main/java/org/springframework/session/data/redis/config/ConfigureNotifyKeyspaceEventsAction.java b/spring-session/src/main/java/org/springframework/session/data/redis/config/ConfigureNotifyKeyspaceEventsAction.java index 2a6ea150..6aef3ad5 100644 --- a/spring-session/src/main/java/org/springframework/session/data/redis/config/ConfigureNotifyKeyspaceEventsAction.java +++ b/spring-session/src/main/java/org/springframework/session/data/redis/config/ConfigureNotifyKeyspaceEventsAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis.config; import java.util.List; @@ -49,17 +50,17 @@ public class ConfigureNotifyKeyspaceEventsAction implements ConfigureRedisAction public void configure(RedisConnection connection) { String notifyOptions = getNotifyOptions(connection); String customizedNotifyOptions = notifyOptions; - if(!customizedNotifyOptions.contains("E")) { + if (!customizedNotifyOptions.contains("E")) { customizedNotifyOptions += "E"; } boolean A = customizedNotifyOptions.contains("A"); - if(!(A || customizedNotifyOptions.contains("g"))) { + if (!(A || customizedNotifyOptions.contains("g"))) { customizedNotifyOptions += "g"; } - if(!(A || customizedNotifyOptions.contains("x"))) { + if (!(A || customizedNotifyOptions.contains("x"))) { customizedNotifyOptions += "x"; } - if(!notifyOptions.equals(customizedNotifyOptions)) { + if (!notifyOptions.equals(customizedNotifyOptions)) { connection.setConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS, customizedNotifyOptions); } } @@ -67,11 +68,12 @@ public class ConfigureNotifyKeyspaceEventsAction implements ConfigureRedisAction private String getNotifyOptions(RedisConnection connection) { try { List config = connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS); - if(config.size() < 2) { + if (config.size() < 2) { return ""; } return config.get(1); - } catch(InvalidDataAccessApiUsageException e) { + } + catch (InvalidDataAccessApiUsageException e) { throw new IllegalStateException("Unable to configure Redis to keyspace notifications. See http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent", e); } } diff --git a/spring-session/src/main/java/org/springframework/session/data/redis/config/ConfigureRedisAction.java b/spring-session/src/main/java/org/springframework/session/data/redis/config/ConfigureRedisAction.java index 28fabbbb..d896e7d0 100644 --- a/spring-session/src/main/java/org/springframework/session/data/redis/config/ConfigureRedisAction.java +++ b/spring-session/src/main/java/org/springframework/session/data/redis/config/ConfigureRedisAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis.config; import org.springframework.data.redis.connection.RedisConnection; diff --git a/spring-session/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSession.java b/spring-session/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSession.java index 1f89b2fe..eee65100 100644 --- a/spring-session/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSession.java +++ b/spring-session/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis.config.annotation.web.http; import java.lang.annotation.Documented; @@ -52,8 +53,8 @@ import org.springframework.session.data.redis.RedisFlushMode; * @since 1.0 * @see EnableSpringHttpSession */ -@Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) -@Target(value={java.lang.annotation.ElementType.TYPE}) +@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) +@Target({java.lang.annotation.ElementType.TYPE}) @Documented @Import(RedisHttpSessionConfiguration.class) @Configuration @@ -96,4 +97,4 @@ public @interface EnableRedisHttpSession { * @since 1.1 */ RedisFlushMode redisFlushMode() default RedisFlushMode.ON_SAVE; -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.java b/spring-session/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.java index e6bcdf19..0d8e24c2 100644 --- a/spring-session/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.java +++ b/spring-session/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis.config.annotation.web.http; import java.util.Arrays; @@ -80,11 +81,11 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); - if (redisTaskExecutor != null) { - container.setTaskExecutor(redisTaskExecutor); + if (this.redisTaskExecutor != null) { + container.setTaskExecutor(this.redisTaskExecutor); } - if (redisSubscriptionExecutor != null) { - container.setSubscriptionExecutor(redisSubscriptionExecutor); + if (this.redisSubscriptionExecutor != null) { + container.setSubscriptionExecutor(this.redisSubscriptionExecutor); } container.addMessageListener(messageListener, Arrays.asList(new PatternTopic("__keyevent@*:del"), new PatternTopic("__keyevent@*:expired"))); @@ -93,12 +94,12 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio } @Bean - public RedisTemplate sessionRedisTemplate(RedisConnectionFactory connectionFactory) { + public RedisTemplate sessionRedisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate template = new RedisTemplate(); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); - if(defaultRedisSerializer != null) { - template.setDefaultSerializer(defaultRedisSerializer); + if (this.defaultRedisSerializer != null) { + template.setDefaultSerializer(this.defaultRedisSerializer); } template.setConnectionFactory(connectionFactory); return template; @@ -108,17 +109,17 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio public RedisOperationsSessionRepository sessionRepository(@Qualifier("sessionRedisTemplate") RedisOperations sessionRedisTemplate, ApplicationEventPublisher applicationEventPublisher) { RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(sessionRedisTemplate); sessionRepository.setApplicationEventPublisher(applicationEventPublisher); - sessionRepository.setDefaultMaxInactiveInterval(maxInactiveIntervalInSeconds); - if(defaultRedisSerializer != null) { - sessionRepository.setDefaultSerializer(defaultRedisSerializer); + sessionRepository.setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); + if (this.defaultRedisSerializer != null) { + sessionRepository.setDefaultSerializer(this.defaultRedisSerializer); } String redisNamespace = getRedisNamespace(); - if(StringUtils.hasText(redisNamespace)) { + if (StringUtils.hasText(redisNamespace)) { sessionRepository.setRedisKeyNamespace(redisNamespace); } - sessionRepository.setRedisFlushMode(redisFlushMode); + sessionRepository.setRedisFlushMode(this.redisFlushMode); return sessionRepository; } @@ -136,45 +137,24 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio } private String getRedisNamespace() { - if(StringUtils.hasText(this.redisNamespace)) { + if (StringUtils.hasText(this.redisNamespace)) { return this.redisNamespace; } - return System.getProperty("spring.session.redis.namespace",""); + return System.getProperty("spring.session.redis.namespace", ""); } public void setImportMetadata(AnnotationMetadata importMetadata) { Map enableAttrMap = importMetadata.getAnnotationAttributes(EnableRedisHttpSession.class.getName()); AnnotationAttributes enableAttrs = AnnotationAttributes.fromMap(enableAttrMap); - maxInactiveIntervalInSeconds = enableAttrs.getNumber("maxInactiveIntervalInSeconds"); + this.maxInactiveIntervalInSeconds = enableAttrs.getNumber("maxInactiveIntervalInSeconds"); this.redisNamespace = enableAttrs.getString("redisNamespace"); this.redisFlushMode = enableAttrs.getEnum("redisFlushMode"); } @Bean public InitializingBean enableRedisKeyspaceNotificationsInitializer(RedisConnectionFactory connectionFactory) { - return new EnableRedisKeyspaceNotificationsInitializer(connectionFactory, configureRedisAction); - } - - /** - * Ensures that Redis is configured to send keyspace notifications. This is important to ensure that expiration and - * deletion of sessions trigger SessionDestroyedEvents. Without the SessionDestroyedEvent resources may not get - * cleaned up properly. For example, the mapping of the Session to WebSocket connections may not get cleaned up. - */ - static class EnableRedisKeyspaceNotificationsInitializer implements InitializingBean { - private final RedisConnectionFactory connectionFactory; - - private ConfigureRedisAction configure; - - EnableRedisKeyspaceNotificationsInitializer(RedisConnectionFactory connectionFactory, ConfigureRedisAction configure) { - this.connectionFactory = connectionFactory; - this.configure = configure; - } - - public void afterPropertiesSet() throws Exception { - RedisConnection connection = connectionFactory.getConnection(); - configure.configure(connection); - } + return new EnableRedisKeyspaceNotificationsInitializer(connectionFactory, this.configureRedisAction); } /** @@ -204,4 +184,26 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio public void setRedisSubscriptionExecutor(Executor redisSubscriptionExecutor) { this.redisSubscriptionExecutor = redisSubscriptionExecutor; } + + /** + * Ensures that Redis is configured to send keyspace notifications. This is important to ensure that expiration and + * deletion of sessions trigger SessionDestroyedEvents. Without the SessionDestroyedEvent resources may not get + * cleaned up properly. For example, the mapping of the Session to WebSocket connections may not get cleaned up. + */ + static class EnableRedisKeyspaceNotificationsInitializer implements InitializingBean { + private final RedisConnectionFactory connectionFactory; + + private ConfigureRedisAction configure; + + EnableRedisKeyspaceNotificationsInitializer(RedisConnectionFactory connectionFactory, ConfigureRedisAction configure) { + this.connectionFactory = connectionFactory; + this.configure = configure; + } + + public void afterPropertiesSet() throws Exception { + RedisConnection connection = this.connectionFactory.getConnection(); + this.configure.configure(connection); + } + } + } diff --git a/spring-session/src/main/java/org/springframework/session/events/AbstractSessionEvent.java b/spring-session/src/main/java/org/springframework/session/events/AbstractSessionEvent.java index 3c78d3b3..c5a52bb7 100644 --- a/spring-session/src/main/java/org/springframework/session/events/AbstractSessionEvent.java +++ b/spring-session/src/main/java/org/springframework/session/events/AbstractSessionEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.events; import org.springframework.context.ApplicationEvent; @@ -38,7 +39,7 @@ public abstract class AbstractSessionEvent extends ApplicationEvent { this.session = null; } - AbstractSessionEvent(Object source, Session session) { + AbstractSessionEvent(Object source, Session session) { super(source); this.session = session; this.sessionId = session.getId(); @@ -54,10 +55,10 @@ public abstract class AbstractSessionEvent extends ApplicationEvent { */ @SuppressWarnings("unchecked") public S getSession() { - return (S) session; + return (S) this.session; } public String getSessionId() { - return sessionId; + return this.sessionId; } } diff --git a/spring-session/src/main/java/org/springframework/session/events/SessionCreatedEvent.java b/spring-session/src/main/java/org/springframework/session/events/SessionCreatedEvent.java index a47231d1..d51ba694 100644 --- a/spring-session/src/main/java/org/springframework/session/events/SessionCreatedEvent.java +++ b/spring-session/src/main/java/org/springframework/session/events/SessionCreatedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.events; import org.springframework.session.Session; @@ -35,6 +36,7 @@ public class SessionCreatedEvent extends AbstractSessionEvent { } /** + * Create a new {@link SessionCreatedEvent}. * @param source The Source of the SessionCreatedEvent * @param session the Session that was created */ @@ -42,4 +44,4 @@ public class SessionCreatedEvent extends AbstractSessionEvent { super(source, session); } -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/events/SessionDeletedEvent.java b/spring-session/src/main/java/org/springframework/session/events/SessionDeletedEvent.java index 1c4ab05b..9d5cd81b 100644 --- a/spring-session/src/main/java/org/springframework/session/events/SessionDeletedEvent.java +++ b/spring-session/src/main/java/org/springframework/session/events/SessionDeletedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.events; import org.springframework.session.Session; @@ -37,4 +38,4 @@ public class SessionDeletedEvent extends SessionDestroyedEvent { public SessionDeletedEvent(Object source, Session session) { super(source, session); } -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/events/SessionDestroyedEvent.java b/spring-session/src/main/java/org/springframework/session/events/SessionDestroyedEvent.java index 6a97f28c..9eacbe43 100644 --- a/spring-session/src/main/java/org/springframework/session/events/SessionDestroyedEvent.java +++ b/spring-session/src/main/java/org/springframework/session/events/SessionDestroyedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.events; import org.springframework.session.Session; @@ -32,10 +33,11 @@ public class SessionDestroyedEvent extends AbstractSessionEvent { } /** + * Create a new {@link SessionDestroyedEvent}. * @param source The Source of the SessionDestoryedEvent * @param session the Session that was created */ public SessionDestroyedEvent(Object source, Session session) { super(source, session); } -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/events/SessionExpiredEvent.java b/spring-session/src/main/java/org/springframework/session/events/SessionExpiredEvent.java index 8323fbe4..3c7bbb07 100644 --- a/spring-session/src/main/java/org/springframework/session/events/SessionExpiredEvent.java +++ b/spring-session/src/main/java/org/springframework/session/events/SessionExpiredEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.events; import org.springframework.session.Session; @@ -37,4 +38,4 @@ public class SessionExpiredEvent extends SessionDestroyedEvent { public SessionExpiredEvent(Object source, Session session) { super(source, session); } -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/hazelcast/SessionEntryListener.java b/spring-session/src/main/java/org/springframework/session/hazelcast/SessionEntryListener.java index 0e712513..249ae42e 100644 --- a/spring-session/src/main/java/org/springframework/session/hazelcast/SessionEntryListener.java +++ b/spring-session/src/main/java/org/springframework/session/hazelcast/SessionEntryListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.hazelcast; +import com.hazelcast.core.EntryEvent; +import com.hazelcast.map.listener.EntryAddedListener; +import com.hazelcast.map.listener.EntryEvictedListener; +import com.hazelcast.map.listener.EntryRemovedListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.context.ApplicationEventPublisher; import org.springframework.session.ExpiringSession; import org.springframework.session.events.SessionCreatedEvent; @@ -24,11 +30,6 @@ import org.springframework.session.events.SessionDeletedEvent; import org.springframework.session.events.SessionExpiredEvent; import org.springframework.util.Assert; -import com.hazelcast.core.EntryEvent; -import com.hazelcast.map.listener.EntryAddedListener; -import com.hazelcast.map.listener.EntryEvictedListener; -import com.hazelcast.map.listener.EntryRemovedListener; - /** * Listen for events on the Hazelcast-backed SessionRepository and * translate those events into the corresponding Spring Session events. @@ -55,21 +56,21 @@ public class SessionEntryListener implements EntryAddedListener event) { - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Session created with id: " + event.getValue().getId()); } this.eventPublisher.publishEvent(new SessionCreatedEvent(this, event.getValue())); } public void entryEvicted(EntryEvent event) { - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Session expired with id: " + event.getOldValue().getId()); } this.eventPublisher.publishEvent(new SessionExpiredEvent(this, event.getOldValue())); } public void entryRemoved(EntryEvent event) { - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Session deleted with id: " + event.getOldValue().getId()); } this.eventPublisher.publishEvent(new SessionDeletedEvent(this, event.getOldValue())); diff --git a/spring-session/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSession.java b/spring-session/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSession.java index 35dd2bd3..ac613806 100644 --- a/spring-session/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSession.java +++ b/spring-session/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.hazelcast.config.annotation.web.http; import java.lang.annotation.Documented; @@ -50,8 +51,8 @@ import org.springframework.session.config.annotation.web.http.EnableSpringHttpSe * @since 1.1 * @see EnableSpringHttpSession */ -@Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) -@Target(value={java.lang.annotation.ElementType.TYPE}) +@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) +@Target({java.lang.annotation.ElementType.TYPE}) @Documented @Import(HazelcastHttpSessionConfiguration.class) @Configuration diff --git a/spring-session/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfiguration.java b/spring-session/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfiguration.java index a0e1df7e..a14208b4 100644 --- a/spring-session/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfiguration.java +++ b/spring-session/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.hazelcast.config.annotation.web.http; import java.util.Collection; @@ -22,6 +23,9 @@ import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; + import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -35,9 +39,6 @@ import org.springframework.session.config.annotation.web.http.SpringHttpSessionC import org.springframework.session.hazelcast.SessionEntryListener; import org.springframework.session.web.http.SessionRepositoryFilter; -import com.hazelcast.core.HazelcastInstance; -import com.hazelcast.core.IMap; - /** * Exposes the {@link SessionRepositoryFilter} as a bean named * "springSessionRepositoryFilter". In order to use this a single @@ -60,11 +61,11 @@ public class HazelcastHttpSessionConfiguration extends SpringHttpSessionConfigur @Bean public SessionRepository sessionRepository(HazelcastInstance hazelcastInstance, SessionEntryListener sessionListener) { - this.sessionsMap = hazelcastInstance.getMap(sessionMapName); + this.sessionsMap = hazelcastInstance.getMap(this.sessionMapName); this.sessionListenerUid = this.sessionsMap.addEntryListener(sessionListener, true); MapSessionRepository sessionRepository = new MapSessionRepository(new ExpiringSessionMap(this.sessionsMap)); - sessionRepository.setDefaultMaxInactiveInterval(maxInactiveIntervalInSeconds); + sessionRepository.setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); return sessionRepository; } @@ -99,69 +100,72 @@ public class HazelcastHttpSessionConfiguration extends SpringHttpSessionConfigur this.sessionMapName = sessionMapName; } + /** + * A wrapper for Hazelcast's {@link IMap} which is used to store the sessions. + */ static class ExpiringSessionMap implements Map { - private IMap delegate; + private IMap delegate; - ExpiringSessionMap(IMap delegate) { + ExpiringSessionMap(IMap delegate) { this.delegate = delegate; } public ExpiringSession put(String key, ExpiringSession value) { - if(value == null) { - return delegate.put(key, value); + if (value == null) { + return this.delegate.put(key, value); } - return delegate.put(key, value, value.getMaxInactiveIntervalInSeconds(), TimeUnit.SECONDS); + return this.delegate.put(key, value, value.getMaxInactiveIntervalInSeconds(), TimeUnit.SECONDS); } public int size() { - return delegate.size(); + return this.delegate.size(); } public boolean isEmpty() { - return delegate.isEmpty(); + return this.delegate.isEmpty(); } public boolean containsKey(Object key) { - return delegate.containsKey(key); + return this.delegate.containsKey(key); } public boolean containsValue(Object value) { - return delegate.containsValue(value); + return this.delegate.containsValue(value); } public ExpiringSession get(Object key) { - return delegate.get(key); + return this.delegate.get(key); } public ExpiringSession remove(Object key) { - return delegate.remove(key); + return this.delegate.remove(key); } public void putAll(Map m) { - delegate.putAll(m); + this.delegate.putAll(m); } public void clear() { - delegate.clear(); + this.delegate.clear(); } public Set keySet() { - return delegate.keySet(); + return this.delegate.keySet(); } public Collection values() { - return delegate.values(); + return this.delegate.values(); } public Set> entrySet() { - return delegate.entrySet(); + return this.delegate.entrySet(); } public boolean equals(Object o) { - return delegate.equals(o); + return this.delegate.equals(o); } public int hashCode() { - return delegate.hashCode(); + return this.delegate.hashCode(); } } } diff --git a/spring-session/src/main/java/org/springframework/session/web/context/AbstractHttpSessionApplicationInitializer.java b/spring-session/src/main/java/org/springframework/session/web/context/AbstractHttpSessionApplicationInitializer.java index 940eab53..00bb0d94 100644 --- a/spring-session/src/main/java/org/springframework/session/web/context/AbstractHttpSessionApplicationInitializer.java +++ b/spring-session/src/main/java/org/springframework/session/web/context/AbstractHttpSessionApplicationInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.context; import java.util.Arrays; @@ -75,6 +76,9 @@ public abstract class AbstractHttpSessionApplicationInitializer implements WebAp private static final String SERVLET_CONTEXT_PREFIX = "org.springframework.web.servlet.FrameworkServlet.CONTEXT."; + /** + * The default name for Spring Session's repository filter. + */ public static final String DEFAULT_FILTER_NAME = "springSessionRepositoryFilter"; private final Class[] configurationClasses; @@ -105,9 +109,9 @@ public abstract class AbstractHttpSessionApplicationInitializer implements WebAp public void onStartup(ServletContext servletContext) throws ServletException { beforeSessionRepositoryFilter(servletContext); - if(configurationClasses != null) { + if (this.configurationClasses != null) { AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext(); - rootAppContext.register(configurationClasses); + rootAppContext.register(this.configurationClasses); servletContext.addListener(new ContextLoaderListener(rootAppContext)); } insertSessionRepositoryFilter(servletContext); @@ -115,14 +119,14 @@ public abstract class AbstractHttpSessionApplicationInitializer implements WebAp } /** - * Registers the springSessionRepositoryFilter + * Registers the springSessionRepositoryFilter. * @param servletContext the {@link ServletContext} */ private void insertSessionRepositoryFilter(ServletContext servletContext) { String filterName = DEFAULT_FILTER_NAME; DelegatingFilterProxy springSessionRepositoryFilter = new DelegatingFilterProxy(filterName); String contextAttribute = getWebApplicationContextAttribute(); - if(contextAttribute != null) { + if (contextAttribute != null) { springSessionRepositoryFilter.setContextAttribute(contextAttribute); } registerFilter(servletContext, true, filterName, springSessionRepositoryFilter); @@ -138,7 +142,7 @@ public abstract class AbstractHttpSessionApplicationInitializer implements WebAp * @param filters * the {@link Filter}s to register */ - protected final void insertFilters(ServletContext servletContext,Filter... filters) { + protected final void insertFilters(ServletContext servletContext, Filter... filters) { registerFilters(servletContext, true, filters); } @@ -152,7 +156,7 @@ public abstract class AbstractHttpSessionApplicationInitializer implements WebAp * @param filters * the {@link Filter}s to register */ - protected final void appendFilters(ServletContext servletContext,Filter... filters) { + protected final void appendFilters(ServletContext servletContext, Filter... filters) { registerFilters(servletContext, false, filters); } @@ -173,8 +177,8 @@ public abstract class AbstractHttpSessionApplicationInitializer implements WebAp private void registerFilters(ServletContext servletContext, boolean insertBeforeOtherFilters, Filter... filters) { Assert.notEmpty(filters, "filters cannot be null or empty"); - for(Filter filter : filters) { - if(filter == null) { + for (Filter filter : filters) { + if (filter == null) { throw new IllegalArgumentException("filters cannot contain null values. Got " + Arrays.asList(filters)); } String filterName = Conventions.getVariableName(filter); @@ -185,15 +189,15 @@ public abstract class AbstractHttpSessionApplicationInitializer implements WebAp /** * Registers the provided filter using the {@link #isAsyncSessionSupported()} and {@link #getSessionDispatcherTypes()}. * - * @param servletContext + * @param servletContext the servlet context * @param insertBeforeOtherFilters should this Filter be inserted before or after other {@link Filter} - * @param filterName - * @param filter + * @param filterName the filter name + * @param filter the filter */ - private final void registerFilter(ServletContext servletContext, boolean insertBeforeOtherFilters, String filterName, Filter filter) { + private void registerFilter(ServletContext servletContext, boolean insertBeforeOtherFilters, String filterName, Filter filter) { Dynamic registration = servletContext.addFilter(filterName, filter); - if(registration == null) { - throw new IllegalStateException("Duplicate Filter registration for '" + filterName +"'. Check to ensure the Filter is only configured once."); + if (registration == null) { + throw new IllegalStateException("Duplicate Filter registration for '" + filterName + "'. Check to ensure the Filter is only configured once."); } registration.setAsyncSupported(isAsyncSessionSupported()); EnumSet dispatcherTypes = getSessionDispatcherTypes(); @@ -217,7 +221,7 @@ public abstract class AbstractHttpSessionApplicationInitializer implements WebAp */ private String getWebApplicationContextAttribute() { String dispatcherServletName = getDispatcherWebApplicationContextSuffix(); - if(dispatcherServletName == null) { + if (dispatcherServletName == null) { return null; } return SERVLET_CONTEXT_PREFIX + dispatcherServletName; diff --git a/spring-session/src/main/java/org/springframework/session/web/http/CookieHttpSessionStrategy.java b/spring-session/src/main/java/org/springframework/session/web/http/CookieHttpSessionStrategy.java index 8c3ebc13..af059f08 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/CookieHttpSessionStrategy.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/CookieHttpSessionStrategy.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session.web.http; import java.io.UnsupportedEncodingException; @@ -150,8 +151,8 @@ import org.springframework.util.Assert; * } * * - * @since 1.0 * @author Rob Winch + * @since 1.0 */ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy, HttpSessionManager { private static final String SESSION_IDS_WRITTEN_ATTR = CookieHttpSessionStrategy.class.getName().concat(".SESSIONS_WRITTEN_ATTR"); @@ -160,27 +161,27 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy static final String DEFAULT_SESSION_ALIAS_PARAM_NAME = "_s"; - private Pattern ALIAS_PATTERN = Pattern.compile("^[\\w-]{1,50}$"); + private static final Pattern ALIAS_PATTERN = Pattern.compile("^[\\w-]{1,50}$"); private String sessionParam = DEFAULT_SESSION_ALIAS_PARAM_NAME; private CookieSerializer cookieSerializer = new DefaultCookieSerializer(); public String getRequestedSessionId(HttpServletRequest request) { - Map sessionIds = getSessionIds(request); + Map sessionIds = getSessionIds(request); String sessionAlias = getCurrentSessionAlias(request); return sessionIds.get(sessionAlias); } public String getCurrentSessionAlias(HttpServletRequest request) { - if(sessionParam == null) { + if (this.sessionParam == null) { return DEFAULT_ALIAS; } - String u = request.getParameter(sessionParam); - if(u == null) { + String u = request.getParameter(this.sessionParam); + if (u == null) { return DEFAULT_ALIAS; } - if(!ALIAS_PATTERN.matcher(u).matches()) { + if (!ALIAS_PATTERN.matcher(u).matches()) { return DEFAULT_ALIAS; } return u; @@ -188,13 +189,13 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy public String getNewSessionAlias(HttpServletRequest request) { Set sessionAliases = getSessionIds(request).keySet(); - if(sessionAliases.isEmpty()) { + if (sessionAliases.isEmpty()) { return DEFAULT_ALIAS; } long lastAlias = Long.decode(DEFAULT_ALIAS); - for(String alias : sessionAliases) { + for (String alias : sessionAliases) { long selectedAlias = safeParse(alias); - if(selectedAlias > lastAlias) { + if (selectedAlias > lastAlias) { lastAlias = selectedAlias; } } @@ -204,30 +205,31 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy private long safeParse(String hex) { try { return Long.decode("0x" + hex); - } catch(NumberFormatException notNumber) { + } + catch (NumberFormatException notNumber) { return 0; } } public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) { Set sessionIdsWritten = getSessionIdsWritten(request); - if(sessionIdsWritten.contains(session.getId())) { + if (sessionIdsWritten.contains(session.getId())) { return; } sessionIdsWritten.add(session.getId()); - Map sessionIds = getSessionIds(request); + Map sessionIds = getSessionIds(request); String sessionAlias = getCurrentSessionAlias(request); sessionIds.put(sessionAlias, session.getId()); String cookieValue = createSessionCookieValue(sessionIds); - cookieSerializer.writeCookieValue(new CookieValue(request,response,cookieValue)); + this.cookieSerializer.writeCookieValue(new CookieValue(request, response, cookieValue)); } @SuppressWarnings("unchecked") private Set getSessionIdsWritten(HttpServletRequest request) { Set sessionsWritten = (Set) request.getAttribute(SESSION_IDS_WRITTEN_ATTR); - if(sessionsWritten == null) { + if (sessionsWritten == null) { sessionsWritten = new HashSet(); request.setAttribute(SESSION_IDS_WRITTEN_ATTR, sessionsWritten); } @@ -235,15 +237,15 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy } private String createSessionCookieValue(Map sessionIds) { - if(sessionIds.isEmpty()) { + if (sessionIds.isEmpty()) { return ""; } - if(sessionIds.size() == 1 && sessionIds.keySet().contains(DEFAULT_ALIAS)) { + if (sessionIds.size() == 1 && sessionIds.keySet().contains(DEFAULT_ALIAS)) { return sessionIds.values().iterator().next(); } StringBuffer buffer = new StringBuffer(); - for(Map.Entry entry : sessionIds.entrySet()) { + for (Map.Entry entry : sessionIds.entrySet()) { String alias = entry.getKey(); String id = entry.getValue(); @@ -252,17 +254,17 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy buffer.append(id); buffer.append(" "); } - buffer.deleteCharAt(buffer.length()-1); + buffer.deleteCharAt(buffer.length() - 1); return buffer.toString(); } public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) { - Map sessionIds = getSessionIds(request); + Map sessionIds = getSessionIds(request); String requestedAlias = getCurrentSessionAlias(request); sessionIds.remove(requestedAlias); String cookieValue = createSessionCookieValue(sessionIds); - cookieSerializer.writeCookieValue(new CookieValue(request,response,cookieValue)); + this.cookieSerializer.writeCookieValue(new CookieValue(request, response, cookieValue)); } /** @@ -290,7 +292,7 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy } /** - * Sets the name of the cookie to be used + * Sets the name of the cookie to be used. * @param cookieName the name of the cookie to be used * @deprecated use {@link #setCookieSerializer(CookieSerializer)} */ @@ -301,18 +303,18 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy this.cookieSerializer = serializer; } - public Map getSessionIds(HttpServletRequest request) { - List cookieValues = cookieSerializer.readCookieValues(request); + public Map getSessionIds(HttpServletRequest request) { + List cookieValues = this.cookieSerializer.readCookieValues(request); String sessionCookieValue = cookieValues.isEmpty() ? "" : cookieValues.iterator().next(); - Map result = new LinkedHashMap(); + Map result = new LinkedHashMap(); StringTokenizer tokens = new StringTokenizer(sessionCookieValue, " "); - if(tokens.countTokens() == 1) { + if (tokens.countTokens() == 1) { result.put(DEFAULT_ALIAS, tokens.nextToken()); return result; } - while(tokens.hasMoreTokens()) { + while (tokens.hasMoreTokens()) { String alias = tokens.nextToken(); - if(!tokens.hasMoreTokens()) { + if (!tokens.hasMoreTokens()) { break; } String id = tokens.nextToken(); @@ -330,46 +332,23 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy return new MultiSessionHttpServletResponse(response, request); } - class MultiSessionHttpServletResponse extends HttpServletResponseWrapper { - private final HttpServletRequest request; - - public MultiSessionHttpServletResponse(HttpServletResponse response, HttpServletRequest request) { - super(response); - this.request = request; - } - - @Override - public String encodeRedirectURL(String url) { - url = super.encodeRedirectURL(url); - return CookieHttpSessionStrategy.this.encodeURL(url, getCurrentSessionAlias(request)); - } - - @Override - public String encodeURL(String url) { - url = super.encodeURL(url); - - String alias = getCurrentSessionAlias(request); - return CookieHttpSessionStrategy.this.encodeURL(url, alias); - } - } - public String encodeURL(String url, String sessionAlias) { String encodedSessionAlias = urlEncode(sessionAlias); int queryStart = url.indexOf("?"); boolean isDefaultAlias = DEFAULT_ALIAS.equals(encodedSessionAlias); - if(queryStart < 0) { - return isDefaultAlias ? url : url + "?" + sessionParam + "=" + encodedSessionAlias; + if (queryStart < 0) { + return isDefaultAlias ? url : url + "?" + this.sessionParam + "=" + encodedSessionAlias; } String path = url.substring(0, queryStart); String query = url.substring(queryStart + 1, url.length()); - String replacement = isDefaultAlias ? "" : "$1"+encodedSessionAlias; - query = query.replaceFirst( "((^|&)" + sessionParam + "=)([^&]+)?", replacement); - if(!isDefaultAlias && url.endsWith(query)) { + String replacement = isDefaultAlias ? "" : "$1" + encodedSessionAlias; + query = query.replaceFirst("((^|&)" + this.sessionParam + "=)([^&]+)?", replacement); + if (!isDefaultAlias && url.endsWith(query)) { // no existing alias - if(!(query.endsWith("&") || query.length() == 0)) { + if (!(query.endsWith("&") || query.length() == 0)) { query += "&"; } - query += sessionParam + "=" + encodedSessionAlias; + query += this.sessionParam + "=" + encodedSessionAlias; } return path + "?" + query; @@ -378,8 +357,36 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy private String urlEncode(String value) { try { return URLEncoder.encode(value, "UTF-8"); - } catch (UnsupportedEncodingException e) { + } + catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } -} \ No newline at end of file + + /** + * A {@link CookieHttpSessionStrategy} aware {@link HttpServletResponseWrapper}. + */ + class MultiSessionHttpServletResponse extends HttpServletResponseWrapper { + private final HttpServletRequest request; + + MultiSessionHttpServletResponse(HttpServletResponse response, HttpServletRequest request) { + super(response); + this.request = request; + } + + @Override + public String encodeRedirectURL(String url) { + url = super.encodeRedirectURL(url); + return CookieHttpSessionStrategy.this.encodeURL(url, getCurrentSessionAlias(this.request)); + } + + @Override + public String encodeURL(String url) { + url = super.encodeURL(url); + + String alias = getCurrentSessionAlias(this.request); + return CookieHttpSessionStrategy.this.encodeURL(url, alias); + } + } + +} diff --git a/spring-session/src/main/java/org/springframework/session/web/http/CookieSerializer.java b/spring-session/src/main/java/org/springframework/session/web/http/CookieSerializer.java index ba49b95e..38e96b16 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/CookieSerializer.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/CookieSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import java.util.List; @@ -32,7 +33,7 @@ public interface CookieSerializer { /** * Writes a given {@link CookieValue} to the provided - * {@link HttpServletResponse} + * {@link HttpServletResponse}. * * @param cookieValue * the {@link CookieValue} to write to @@ -61,13 +62,13 @@ public interface CookieSerializer { * @author Rob Winch * @since 1.1 */ - public class CookieValue { + class CookieValue { private final HttpServletRequest request; private final HttpServletResponse response; private final String cookieValue; /** - * Creates a new instance + * Creates a new instance. * * @param request * the {@link HttpServletRequest} to use. Useful for @@ -92,7 +93,7 @@ public interface CookieSerializer { * @return the request to use. Cannot be null. */ public HttpServletRequest getRequest() { - return request; + return this.request; } /** @@ -100,7 +101,7 @@ public interface CookieSerializer { * @return the response to write to. Cannot be null. */ public HttpServletResponse getResponse() { - return response; + return this.response; } /** @@ -109,7 +110,7 @@ public interface CookieSerializer { * @return the value to be written */ public String getCookieValue() { - return cookieValue; + return this.cookieValue; } } } diff --git a/spring-session/src/main/java/org/springframework/session/web/http/DefaultCookieSerializer.java b/spring-session/src/main/java/org/springframework/session/web/http/DefaultCookieSerializer.java index 36d0814e..b79ff143 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/DefaultCookieSerializer.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/DefaultCookieSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import java.util.ArrayList; @@ -26,7 +27,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** - * The default implementation of {@link CookieSerializer} + * The default implementation of {@link CookieSerializer}. * * @author Rob Winch * @since 1.1 @@ -53,17 +54,17 @@ public class DefaultCookieSerializer implements CookieSerializer { * @see org.springframework.session.web.http.CookieSerializer#readCookieValues(javax.servlet.http.HttpServletRequest) */ public List readCookieValues(HttpServletRequest request) { - Cookie cookies[] = request.getCookies(); + Cookie[] cookies = request.getCookies(); List matchingCookieValues = new ArrayList(); if (cookies != null) { for (Cookie cookie : cookies) { - if (cookieName.equals(cookie.getName())) { + if (this.cookieName.equals(cookie.getName())) { String sessionId = cookie.getValue(); - if(sessionId == null) { + if (sessionId == null) { continue; } - if(jvmRoute != null && sessionId.endsWith(jvmRoute)) { - sessionId = sessionId.substring(0, sessionId.length() - jvmRoute.length()); + if (this.jvmRoute != null && sessionId.endsWith(this.jvmRoute)) { + sessionId = sessionId.substring(0, sessionId.length() - this.jvmRoute.length()); } matchingCookieValues.add(sessionId); } @@ -83,9 +84,9 @@ public class DefaultCookieSerializer implements CookieSerializer { HttpServletResponse response = cookieValue.getResponse(); String requestedCookieValue = cookieValue.getCookieValue(); - String actualCookieValue = jvmRoute == null ? requestedCookieValue : requestedCookieValue + jvmRoute; + String actualCookieValue = this.jvmRoute == null ? requestedCookieValue : requestedCookieValue + this.jvmRoute; - Cookie sessionCookie = new Cookie(cookieName, actualCookieValue); + Cookie sessionCookie = new Cookie(this.cookieName, actualCookieValue); sessionCookie.setSecure(isSecureCookie(request)); sessionCookie.setPath(getCookiePath(request)); String domainName = getDomainName(request); @@ -93,14 +94,15 @@ public class DefaultCookieSerializer implements CookieSerializer { sessionCookie.setDomain(domainName); } - if (useHttpOnlyCookie) { + if (this.useHttpOnlyCookie) { sessionCookie.setHttpOnly(true); } if ("".equals(requestedCookieValue)) { sessionCookie.setMaxAge(0); - } else { - sessionCookie.setMaxAge(cookieMaxAge); + } + else { + sessionCookie.setMaxAge(this.cookieMaxAge); } response.addCookie(sessionCookie); @@ -125,17 +127,17 @@ public class DefaultCookieSerializer implements CookieSerializer { * determines if the cookie should be marked as HTTP Only. */ public void setUseHttpOnlyCookie(boolean useHttpOnlyCookie) { - if(useHttpOnlyCookie && !isServlet3()) { + if (useHttpOnlyCookie && !isServlet3()) { throw new IllegalArgumentException("You cannot set useHttpOnlyCookie to true in pre Servlet 3 environment"); } this.useHttpOnlyCookie = useHttpOnlyCookie; } private boolean isSecureCookie(HttpServletRequest request) { - if (useSecureCookie == null) { + if (this.useSecureCookie == null) { return request.isSecure(); } - return useSecureCookie; + return this.useSecureCookie; } /** @@ -247,11 +249,11 @@ public class DefaultCookieSerializer implements CookieSerializer { } private String getDomainName(HttpServletRequest request) { - if (domainName != null) { - return domainName; + if (this.domainName != null) { + return this.domainName; } - if (domainNamePattern != null) { - Matcher matcher = domainNamePattern.matcher(request.getServerName()); + if (this.domainNamePattern != null) { + Matcher matcher = this.domainNamePattern.matcher(request.getServerName()); if (matcher.matches()) { return matcher.group(1); } @@ -260,22 +262,23 @@ public class DefaultCookieSerializer implements CookieSerializer { } private String getCookiePath(HttpServletRequest request) { - if (cookiePath == null) { + if (this.cookiePath == null) { return request.getContextPath() + "/"; } - return cookiePath; + return this.cookiePath; } /** * Returns true if the Servlet 3 APIs are detected. * - * @return + * @return whether the Servlet 3 APIs are detected */ private boolean isServlet3() { try { ServletRequest.class.getMethod("startAsync"); return true; - } catch (NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { } return false; } diff --git a/spring-session/src/main/java/org/springframework/session/web/http/ExpiringSessionHttpSession.java b/spring-session/src/main/java/org/springframework/session/web/http/ExpiringSessionHttpSession.java index 51717089..b9b6cf53 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/ExpiringSessionHttpSession.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/ExpiringSessionHttpSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import java.util.Collections; @@ -29,6 +30,7 @@ import org.springframework.session.ExpiringSession; /** * Adapts Spring Session's {@link ExpiringSession} to an {@link HttpSession}. * + * @param the {@link ExpiringSession} type * @author Rob Winch * @since 1.1 */ @@ -39,7 +41,7 @@ class ExpiringSessionHttpSession implements HttpSessi private boolean invalidated; private boolean old; - public ExpiringSessionHttpSession(S session, ServletContext servletContext) { + ExpiringSessionHttpSession(S session, ServletContext servletContext) { this.session = session; this.servletContext = servletContext; } @@ -49,33 +51,33 @@ class ExpiringSessionHttpSession implements HttpSessi } public S getSession() { - return session; + return this.session; } public long getCreationTime() { checkState(); - return session.getCreationTime(); + return this.session.getCreationTime(); } public String getId() { - return session.getId(); + return this.session.getId(); } public long getLastAccessedTime() { checkState(); - return session.getLastAccessedTime(); + return this.session.getLastAccessedTime(); } public ServletContext getServletContext() { - return servletContext; + return this.servletContext; } public void setMaxInactiveInterval(int interval) { - session.setMaxInactiveIntervalInSeconds(interval); + this.session.setMaxInactiveIntervalInSeconds(interval); } public int getMaxInactiveInterval() { - return session.getMaxInactiveIntervalInSeconds(); + return this.session.getMaxInactiveIntervalInSeconds(); } public HttpSessionContext getSessionContext() { @@ -84,7 +86,7 @@ class ExpiringSessionHttpSession implements HttpSessi public Object getAttribute(String name) { checkState(); - return session.getAttribute(name); + return this.session.getAttribute(name); } public Object getValue(String name) { @@ -93,18 +95,18 @@ class ExpiringSessionHttpSession implements HttpSessi public Enumeration getAttributeNames() { checkState(); - return Collections.enumeration(session.getAttributeNames()); + return Collections.enumeration(this.session.getAttributeNames()); } public String[] getValueNames() { checkState(); - Set attrs = session.getAttributeNames(); + Set attrs = this.session.getAttributeNames(); return attrs.toArray(new String[0]); } public void setAttribute(String name, Object value) { checkState(); - session.setAttribute(name, value); + this.session.setAttribute(name, value); } public void putValue(String name, Object value) { @@ -113,7 +115,7 @@ class ExpiringSessionHttpSession implements HttpSessi public void removeAttribute(String name) { checkState(); - session.removeAttribute(name); + this.session.removeAttribute(name); } public void removeValue(String name) { @@ -131,11 +133,11 @@ class ExpiringSessionHttpSession implements HttpSessi public boolean isNew() { checkState(); - return !old; + return !this.old; } private void checkState() { - if(invalidated) { + if (this.invalidated) { throw new IllegalStateException("The HttpSession has already be invalidated."); } } diff --git a/spring-session/src/main/java/org/springframework/session/web/http/HeaderHttpSessionStrategy.java b/spring-session/src/main/java/org/springframework/session/web/http/HeaderHttpSessionStrategy.java index e9dfc9f3..77331616 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/HeaderHttpSessionStrategy.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/HeaderHttpSessionStrategy.java @@ -1,26 +1,27 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package org.springframework.session.web.http; -import org.springframework.session.Session; -import org.springframework.util.Assert; +package org.springframework.session.web.http; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.session.Session; +import org.springframework.util.Assert; + /** * A {@link HttpSessionStrategy} that uses a header to obtain the session from. Specifically, this implementation will * allow specifying a header name using {@link HeaderHttpSessionStrategy#setHeaderName(String)}. The default is "x-auth-token". @@ -47,22 +48,22 @@ import javax.servlet.http.HttpServletResponse; * x-auth-token: * * - * @since 1.0 * @author Rob Winch + * @since 1.0 */ public class HeaderHttpSessionStrategy implements HttpSessionStrategy { private String headerName = "x-auth-token"; public String getRequestedSessionId(HttpServletRequest request) { - return request.getHeader(headerName); + return request.getHeader(this.headerName); } public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) { - response.setHeader(headerName, session.getId()); + response.setHeader(this.headerName, session.getId()); } public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) { - response.setHeader(headerName, ""); + response.setHeader(this.headerName, ""); } /** @@ -74,4 +75,4 @@ public class HeaderHttpSessionStrategy implements HttpSessionStrategy { Assert.notNull(headerName, "headerName cannot be null"); this.headerName = headerName; } -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/web/http/HttpSessionManager.java b/spring-session/src/main/java/org/springframework/session/web/http/HttpSessionManager.java index cc6a76f3..a20a964d 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/HttpSessionManager.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/HttpSessionManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import java.util.Map; @@ -39,7 +40,7 @@ public interface HttpSessionManager { /** * Gets a mapping of the session alias to the session id from the - * {@link HttpServletRequest} + * {@link HttpServletRequest}. * * @param request the {@link HttpServletRequest} to obtain the mapping from. Cannot be null. * @return a mapping of the session alias to the session id from the diff --git a/spring-session/src/main/java/org/springframework/session/web/http/HttpSessionStrategy.java b/spring-session/src/main/java/org/springframework/session/web/http/HttpSessionStrategy.java index 003d67ea..aad14698 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/HttpSessionStrategy.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/HttpSessionStrategy.java @@ -1,30 +1,31 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package org.springframework.session.web.http; -import org.springframework.session.Session; +package org.springframework.session.web.http; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.session.Session; + /** * A strategy for mapping HTTP request and responses to a {@link Session}. * - * @since 1.0 * @author Rob Winch + * @since 1.0 */ public interface HttpSessionStrategy { diff --git a/spring-session/src/main/java/org/springframework/session/web/http/MultiHttpSessionStrategy.java b/spring-session/src/main/java/org/springframework/session/web/http/MultiHttpSessionStrategy.java index 522f0cc5..5c0e8212 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/MultiHttpSessionStrategy.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/MultiHttpSessionStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import javax.servlet.http.HttpServletRequest; @@ -28,10 +29,9 @@ import javax.servlet.http.HttpServletResponse; * are active. *

* - * @see CookieHttpSessionStrategy - * * @author Rob Winch * @since 1.0 + * @see CookieHttpSessionStrategy */ public interface MultiHttpSessionStrategy extends HttpSessionStrategy, RequestResponsePostProcessor { -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/web/http/OnCommittedResponseWrapper.java b/spring-session/src/main/java/org/springframework/session/web/http/OnCommittedResponseWrapper.java index 9feb5daf..4d681c31 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/OnCommittedResponseWrapper.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/OnCommittedResponseWrapper.java @@ -1,33 +1,38 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session.web.http; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Locale; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Locale; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; /** * Base class for response wrappers which encapsulate the logic for handling an event when the * {@link javax.servlet.http.HttpServletResponse} is committed. * - * @since 1.0 * @author Rob Winch + * @since 1.0 */ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { private final Log logger = LogFactory.getLog(getClass()); @@ -46,15 +51,16 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { private long contentWritten; /** + * Create a new {@link OnCommittedResponseWrapper}. * @param response the response to be wrapped */ - public OnCommittedResponseWrapper(HttpServletResponse response) { + OnCommittedResponseWrapper(HttpServletResponse response) { super(response); } @Override public void addHeader(String name, String value) { - if("Content-Length".equalsIgnoreCase(name)) { + if ("Content-Length".equalsIgnoreCase(name)) { setContentLength(Long.parseLong(value)); } super.addHeader(name, value); @@ -81,13 +87,14 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { } /** - * Implement the logic for handling the {@link javax.servlet.http.HttpServletResponse} being committed + * Implement the logic for handling the {@link javax.servlet.http.HttpServletResponse} being committed. */ protected abstract void onResponseCommitted(); /** * Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the - * superclass sendError() + * superclass sendError(). + * @param sc the error status code */ @Override public final void sendError(int sc) throws IOException { @@ -97,7 +104,8 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { /** * Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the - * superclass sendError() + * superclass sendError(). + * @param sc the error status code */ @Override public final void sendError(int sc, String msg) throws IOException { @@ -107,7 +115,8 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { /** * Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the - * superclass sendRedirect() + * superclass sendRedirect(). + * @param location the redirect URL location */ @Override public final void sendRedirect(String location) throws IOException { @@ -117,7 +126,8 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { /** * Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the calling - * getOutputStream().close() or getOutputStream().flush() + * getOutputStream().close() or getOutputStream().flush(). + * @throws IOException if an input or output exception occurred */ @Override public ServletOutputStream getOutputStream() throws IOException { @@ -126,7 +136,8 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { /** * Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the - * getWriter().close() or getWriter().flush() + * getWriter().close() or getWriter().flush(). + * @throws IOException if an input or output exception occurred */ @Override public PrintWriter getWriter() throws IOException { @@ -135,7 +146,8 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { /** * Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the - * superclass flushBuffer() + * superclass flushBuffer(). + * @throws IOException if an input or output exception occurred */ @Override public void flushBuffer() throws IOException { @@ -190,25 +202,26 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { * @param contentLengthToWrite the size of the content that is about to be written. */ private void checkContentLength(long contentLengthToWrite) { - contentWritten += contentLengthToWrite; - boolean isBodyFullyWritten = contentLength > 0 && contentWritten >= contentLength; + this.contentWritten += contentLengthToWrite; + boolean isBodyFullyWritten = this.contentLength > 0 && this.contentWritten >= this.contentLength; int bufferSize = getBufferSize(); - boolean requiresFlush = bufferSize > 0 && contentWritten >= bufferSize; - if(isBodyFullyWritten || requiresFlush) { + boolean requiresFlush = bufferSize > 0 && this.contentWritten >= bufferSize; + if (isBodyFullyWritten || requiresFlush) { doOnResponseCommitted(); } } /** * Calls onResponseCommmitted() with the current contents as long as - * {@link #disableOnResponseCommitted()()} was not invoked. + * {@link #disableOnResponseCommitted()} was not invoked. */ private void doOnResponseCommitted() { - if(!disableOnCommitted) { + if (!this.disableOnCommitted) { onResponseCommitted(); disableOnResponseCommitted(); - } else if(logger.isDebugEnabled()){ - logger.debug("Skip invoking on"); + } + else if (this.logger.isDebugEnabled()) { + this.logger.debug("Skip invoking on"); } } @@ -221,195 +234,195 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { private class SaveContextPrintWriter extends PrintWriter { private final PrintWriter delegate; - public SaveContextPrintWriter(PrintWriter delegate) { + SaveContextPrintWriter(PrintWriter delegate) { super(delegate); this.delegate = delegate; } public void flush() { doOnResponseCommitted(); - delegate.flush(); + this.delegate.flush(); } public void close() { doOnResponseCommitted(); - delegate.close(); + this.delegate.close(); } public int hashCode() { - return delegate.hashCode(); + return this.delegate.hashCode(); } public boolean equals(Object obj) { - return delegate.equals(obj); + return this.delegate.equals(obj); } public String toString() { - return getClass().getName() + "[delegate=" + delegate.toString() + "]"; + return getClass().getName() + "[delegate=" + this.delegate.toString() + "]"; } public boolean checkError() { - return delegate.checkError(); + return this.delegate.checkError(); } public void write(int c) { trackContentLength(c); - delegate.write(c); + this.delegate.write(c); } public void write(char[] buf, int off, int len) { checkContentLength(len); - delegate.write(buf, off, len); + this.delegate.write(buf, off, len); } public void write(char[] buf) { trackContentLength(buf); - delegate.write(buf); + this.delegate.write(buf); } public void write(String s, int off, int len) { checkContentLength(len); - delegate.write(s, off, len); + this.delegate.write(s, off, len); } public void write(String s) { trackContentLength(s); - delegate.write(s); + this.delegate.write(s); } public void print(boolean b) { trackContentLength(b); - delegate.print(b); + this.delegate.print(b); } public void print(char c) { trackContentLength(c); - delegate.print(c); + this.delegate.print(c); } public void print(int i) { trackContentLength(i); - delegate.print(i); + this.delegate.print(i); } public void print(long l) { trackContentLength(l); - delegate.print(l); + this.delegate.print(l); } public void print(float f) { trackContentLength(f); - delegate.print(f); + this.delegate.print(f); } public void print(double d) { trackContentLength(d); - delegate.print(d); + this.delegate.print(d); } public void print(char[] s) { trackContentLength(s); - delegate.print(s); + this.delegate.print(s); } public void print(String s) { trackContentLength(s); - delegate.print(s); + this.delegate.print(s); } public void print(Object obj) { trackContentLength(obj); - delegate.print(obj); + this.delegate.print(obj); } public void println() { trackContentLengthLn(); - delegate.println(); + this.delegate.println(); } public void println(boolean x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public void println(char x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public void println(int x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public void println(long x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public void println(float x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public void println(double x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public void println(char[] x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public void println(String x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public void println(Object x) { trackContentLength(x); trackContentLengthLn(); - delegate.println(x); + this.delegate.println(x); } public PrintWriter printf(String format, Object... args) { - return delegate.printf(format, args); + return this.delegate.printf(format, args); } public PrintWriter printf(Locale l, String format, Object... args) { - return delegate.printf(l, format, args); + return this.delegate.printf(l, format, args); } public PrintWriter format(String format, Object... args) { - return delegate.format(format, args); + return this.delegate.format(format, args); } public PrintWriter format(Locale l, String format, Object... args) { - return delegate.format(l, format, args); + return this.delegate.format(l, format, args); } public PrintWriter append(CharSequence csq) { checkContentLength(csq.length()); - return delegate.append(csq); + return this.delegate.append(csq); } public PrintWriter append(CharSequence csq, int start, int end) { checkContentLength(end - start); - return delegate.append(csq, start, end); + return this.delegate.append(csq, start, end); } public PrintWriter append(char c) { trackContentLength(c); - return delegate.append(c); + return this.delegate.append(c); } } @@ -423,7 +436,7 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { private class SaveContextServletOutputStream extends ServletOutputStream { private final ServletOutputStream delegate; - public SaveContextServletOutputStream(ServletOutputStream delegate) { + SaveContextServletOutputStream(ServletOutputStream delegate) { this.delegate = delegate; } @@ -434,116 +447,116 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { public void flush() throws IOException { doOnResponseCommitted(); - delegate.flush(); + this.delegate.flush(); } public void close() throws IOException { doOnResponseCommitted(); - delegate.close(); + this.delegate.close(); } public int hashCode() { - return delegate.hashCode(); + return this.delegate.hashCode(); } public boolean equals(Object obj) { - return delegate.equals(obj); + return this.delegate.equals(obj); } public void print(boolean b) throws IOException { trackContentLength(b); - delegate.print(b); + this.delegate.print(b); } public void print(char c) throws IOException { trackContentLength(c); - delegate.print(c); + this.delegate.print(c); } public void print(double d) throws IOException { trackContentLength(d); - delegate.print(d); + this.delegate.print(d); } public void print(float f) throws IOException { trackContentLength(f); - delegate.print(f); + this.delegate.print(f); } public void print(int i) throws IOException { trackContentLength(i); - delegate.print(i); + this.delegate.print(i); } public void print(long l) throws IOException { trackContentLength(l); - delegate.print(l); + this.delegate.print(l); } public void print(String s) throws IOException { trackContentLength(s); - delegate.print(s); + this.delegate.print(s); } public void println() throws IOException { trackContentLengthLn(); - delegate.println(); + this.delegate.println(); } public void println(boolean b) throws IOException { trackContentLength(b); trackContentLengthLn(); - delegate.println(b); + this.delegate.println(b); } public void println(char c) throws IOException { trackContentLength(c); trackContentLengthLn(); - delegate.println(c); + this.delegate.println(c); } public void println(double d) throws IOException { trackContentLength(d); trackContentLengthLn(); - delegate.println(d); + this.delegate.println(d); } public void println(float f) throws IOException { trackContentLength(f); trackContentLengthLn(); - delegate.println(f); + this.delegate.println(f); } public void println(int i) throws IOException { trackContentLength(i); trackContentLengthLn(); - delegate.println(i); + this.delegate.println(i); } public void println(long l) throws IOException { trackContentLength(l); trackContentLengthLn(); - delegate.println(l); + this.delegate.println(l); } public void println(String s) throws IOException { trackContentLength(s); trackContentLengthLn(); - delegate.println(s); + this.delegate.println(s); } public void write(byte[] b) throws IOException { trackContentLength(b); - delegate.write(b); + this.delegate.write(b); } public void write(byte[] b, int off, int len) throws IOException { checkContentLength(len); - delegate.write(b, off, len); + this.delegate.write(b, off, len); } public String toString() { - return getClass().getName() + "[delegate=" + delegate.toString() + "]"; + return getClass().getName() + "[delegate=" + this.delegate.toString() + "]"; } } -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/web/http/OncePerRequestFilter.java b/spring-session/src/main/java/org/springframework/session/web/http/OncePerRequestFilter.java index 871af861..29bf864d 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/OncePerRequestFilter.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/OncePerRequestFilter.java @@ -1,31 +1,38 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session.web.http; -import javax.servlet.*; +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; /** * Allows for easily ensuring that a request is only invoked once per request. This is a simplified version of spring-web's * OncePerRequestFilter and copied to reduce the foot print required to use the session support. * - * @since 1.0 * @author Rob Winch + * @since 1.0 */ abstract class OncePerRequestFilter implements Filter { /** @@ -41,6 +48,11 @@ abstract class OncePerRequestFilter implements Filter { * This {@code doFilter} implementation stores a request attribute for * "already filtered", proceeding without filtering again if the * attribute is already there. + * @param request the request + * @param response the response + * @param filterChain the filter chain + * @throws ServletException if request is not HTTP request + * @throws IOException in case of I/O operation exception */ public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { @@ -50,7 +62,7 @@ abstract class OncePerRequestFilter implements Filter { } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; - boolean hasAlreadyFilteredAttribute = request.getAttribute(alreadyFilteredAttributeName) != null; + boolean hasAlreadyFilteredAttribute = request.getAttribute(this.alreadyFilteredAttributeName) != null; if (hasAlreadyFilteredAttribute) { @@ -60,13 +72,13 @@ abstract class OncePerRequestFilter implements Filter { } else { // Do invoke this filter... - request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE); + request.setAttribute(this.alreadyFilteredAttributeName, Boolean.TRUE); try { doFilterInternal(httpRequest, httpResponse, filterChain); } finally { // Remove the "already filtered" request attribute for this request. - request.removeAttribute(alreadyFilteredAttributeName); + request.removeAttribute(this.alreadyFilteredAttributeName); } } } @@ -88,7 +100,9 @@ abstract class OncePerRequestFilter implements Filter { HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException; - public void init(FilterConfig config) {} + public void init(FilterConfig config) { + } - public void destroy() {} + public void destroy() { + } } diff --git a/spring-session/src/main/java/org/springframework/session/web/http/RequestResponsePostProcessor.java b/spring-session/src/main/java/org/springframework/session/web/http/RequestResponsePostProcessor.java index 9c44effd..617e37de 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/RequestResponsePostProcessor.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/RequestResponsePostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import javax.servlet.http.HttpServletRequest; diff --git a/spring-session/src/main/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapter.java b/spring-session/src/main/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapter.java index aa4566cd..e05a722a 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapter.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import java.util.List; @@ -51,16 +52,17 @@ public class SessionEventHttpSessionListenerAdapter implements ApplicationListen * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent) */ public void onApplicationEvent(AbstractSessionEvent event) { - if(listeners.isEmpty()) { + if (this.listeners.isEmpty()) { return; } HttpSessionEvent httpSessionEvent = createHttpSessionEvent(event); - for(HttpSessionListener listener : listeners) { - if(event instanceof SessionDestroyedEvent) { + for (HttpSessionListener listener : this.listeners) { + if (event instanceof SessionDestroyedEvent) { listener.sessionDestroyed(httpSessionEvent); - } else if(event instanceof SessionCreatedEvent) { + } + else if (event instanceof SessionCreatedEvent) { listener.sessionCreated(httpSessionEvent); } } @@ -68,7 +70,7 @@ public class SessionEventHttpSessionListenerAdapter implements ApplicationListen private HttpSessionEvent createHttpSessionEvent(AbstractSessionEvent event) { ExpiringSession session = event.getSession(); - HttpSession httpSession = new ExpiringSessionHttpSession(session, context); + HttpSession httpSession = new ExpiringSessionHttpSession(session, this.context); HttpSessionEvent httpSessionEvent = new HttpSessionEvent(httpSession); return httpSessionEvent; } diff --git a/spring-session/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java b/spring-session/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java index ae765dfa..d838e4b8 100644 --- a/spring-session/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java +++ b/spring-session/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java @@ -1,18 +1,19 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.session.web.http; import java.io.IOException; @@ -30,6 +31,7 @@ import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.core.annotation.Order; import org.springframework.session.ExpiringSession; import org.springframework.session.Session; @@ -58,6 +60,7 @@ import org.springframework.session.SessionRepository; * to ensure the session is overridden and persisted properly. *

* + * @param the {@link ExpiringSession} type. * @since 1.0 * @author Rob Winch */ @@ -67,8 +70,14 @@ public class SessionRepositoryFilter extends OncePerR private static final Log SESSION_LOGGER = LogFactory.getLog(SESSION_LOGGER_NAME); + /** + * The session repository request attribute name. + */ public static final String SESSION_REPOSITORY_ATTR = SessionRepository.class.getName(); + /** + * The default filter order. + */ public static final int DEFAULT_ORDER = Integer.MIN_VALUE + 50; private final SessionRepository sessionRepository; @@ -78,12 +87,12 @@ public class SessionRepositoryFilter extends OncePerR private MultiHttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy(); /** - * Creates a new instance + * Creates a new instance. * * @param sessionRepository the SessionRepository to use. Cannot be null. */ public SessionRepositoryFilter(SessionRepository sessionRepository) { - if(sessionRepository == null) { + if (sessionRepository == null) { throw new IllegalArgumentException("sessionRepository cannot be null"); } this.sessionRepository = sessionRepository; @@ -95,7 +104,7 @@ public class SessionRepositoryFilter extends OncePerR * @param httpSessionStrategy the {@link HttpSessionStrategy} to use. Cannot be null. */ public void setHttpSessionStrategy(HttpSessionStrategy httpSessionStrategy) { - if(httpSessionStrategy == null) { + if (httpSessionStrategy == null) { throw new IllegalArgumentException("httpSessionStrategy cannot be null"); } this.httpSessionStrategy = new MultiHttpSessionStrategyAdapter(httpSessionStrategy); @@ -107,24 +116,25 @@ public class SessionRepositoryFilter extends OncePerR * @param httpSessionStrategy the {@link MultiHttpSessionStrategy} to use. Cannot be null. */ public void setHttpSessionStrategy(MultiHttpSessionStrategy httpSessionStrategy) { - if(httpSessionStrategy == null) { + if (httpSessionStrategy == null) { throw new IllegalArgumentException("httpSessionStrategy cannot be null"); } this.httpSessionStrategy = httpSessionStrategy; } protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - request.setAttribute(SESSION_REPOSITORY_ATTR, sessionRepository); + request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository); - SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(request, response, servletContext); - SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(wrappedRequest,response); + SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(request, response, this.servletContext); + SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(wrappedRequest, response); - HttpServletRequest strategyRequest = httpSessionStrategy.wrapRequest(wrappedRequest, wrappedResponse); - HttpServletResponse strategyResponse = httpSessionStrategy.wrapResponse(wrappedRequest, wrappedResponse); + HttpServletRequest strategyRequest = this.httpSessionStrategy.wrapRequest(wrappedRequest, wrappedResponse); + HttpServletResponse strategyResponse = this.httpSessionStrategy.wrapResponse(wrappedRequest, wrappedResponse); try { filterChain.doFilter(strategyRequest, strategyResponse); - } finally { + } + finally { wrappedRequest.commitSession(); } } @@ -144,11 +154,13 @@ public class SessionRepositoryFilter extends OncePerR private final SessionRepositoryRequestWrapper request; /** + * Create a new {@link SessionRepositoryResponseWrapper}. + * @param request the request to be wrapped * @param response the response to be wrapped */ - public SessionRepositoryResponseWrapper(SessionRepositoryRequestWrapper request, HttpServletResponse response) { + SessionRepositoryResponseWrapper(SessionRepositoryRequestWrapper request, HttpServletResponse response) { super(response); - if(request == null) { + if (request == null) { throw new IllegalArgumentException("request cannot be null"); } this.request = request; @@ -156,7 +168,7 @@ public class SessionRepositoryFilter extends OncePerR @Override protected void onResponseCommitted() { - request.commitSession(); + this.request.commitSession(); } } @@ -185,29 +197,31 @@ public class SessionRepositoryFilter extends OncePerR */ private void commitSession() { HttpSessionWrapper wrappedSession = getCurrentSession(); - if(wrappedSession == null) { - if(isInvalidateClientSession()) { - httpSessionStrategy.onInvalidateSession(this, response); + if (wrappedSession == null) { + if (isInvalidateClientSession()) { + SessionRepositoryFilter.this.httpSessionStrategy.onInvalidateSession(this, this.response); } - } else { + } + else { S session = wrappedSession.getSession(); - sessionRepository.save(session); - if(!isRequestedSessionIdValid() || !session.getId().equals(getRequestedSessionId())) { - httpSessionStrategy.onNewSession(session, this, response); + SessionRepositoryFilter.this.sessionRepository.save(session); + if (!isRequestedSessionIdValid() || !session.getId().equals(getRequestedSessionId())) { + SessionRepositoryFilter.this.httpSessionStrategy.onNewSession(session, this, this.response); } } } @SuppressWarnings("unchecked") private HttpSessionWrapper getCurrentSession() { - return (HttpSessionWrapper) getAttribute(CURRENT_SESSION_ATTR); + return (HttpSessionWrapper) getAttribute(this.CURRENT_SESSION_ATTR); } private void setCurrentSession(HttpSessionWrapper currentSession) { - if(currentSession == null) { - removeAttribute(CURRENT_SESSION_ATTR); - } else { - setAttribute(CURRENT_SESSION_ATTR, currentSession); + if (currentSession == null) { + removeAttribute(this.CURRENT_SESSION_ATTR); + } + else { + setAttribute(this.CURRENT_SESSION_ATTR, currentSession); } } @@ -215,21 +229,21 @@ public class SessionRepositoryFilter extends OncePerR public String changeSessionId() { HttpSession session = getSession(false); - if(session == null) { + if (session == null) { throw new IllegalStateException("Cannot change session ID. There is no session associated with this request."); } // eagerly get session attributes in case implementation lazily loads them - Map attrs = new HashMap(); + Map attrs = new HashMap(); Enumeration iAttrNames = session.getAttributeNames(); - while(iAttrNames.hasMoreElements()) { + while (iAttrNames.hasMoreElements()) { String attrName = iAttrNames.nextElement(); Object value = session.getAttribute(attrName); attrs.put(attrName, value); } - sessionRepository.delete(session.getId()); + SessionRepositoryFilter.this.sessionRepository.delete(session.getId()); HttpSessionWrapper original = getCurrentSession(); setCurrentSession(null); @@ -237,7 +251,7 @@ public class SessionRepositoryFilter extends OncePerR original.setSession(newSession.getSession()); newSession.setMaxInactiveInterval(session.getMaxInactiveInterval()); - for(Map.Entry attr : attrs.entrySet()) { + for (Map.Entry attr : attrs.entrySet()) { String attrName = attr.getKey(); Object attrValue = attr.getValue(); newSession.setAttribute(attrName, attrValue); @@ -246,29 +260,29 @@ public class SessionRepositoryFilter extends OncePerR } public boolean isRequestedSessionIdValid() { - if(requestedSessionIdValid == null) { + if (this.requestedSessionIdValid == null) { String sessionId = getRequestedSessionId(); S session = sessionId == null ? null : getSession(sessionId); return isRequestedSessionIdValid(session); } - return requestedSessionIdValid; + return this.requestedSessionIdValid; } private boolean isRequestedSessionIdValid(S session) { - if(requestedSessionIdValid == null) { - requestedSessionIdValid = session != null; + if (this.requestedSessionIdValid == null) { + this.requestedSessionIdValid = session != null; } - return requestedSessionIdValid; + return this.requestedSessionIdValid; } private boolean isInvalidateClientSession() { - return getCurrentSession() == null && requestedSessionInvalidated; + return getCurrentSession() == null && this.requestedSessionInvalidated; } private S getSession(String sessionId) { - S session = sessionRepository.getSession(sessionId); - if(session == null) { + S session = SessionRepositoryFilter.this.sessionRepository.getSession(sessionId); + if (session == null) { return null; } session.setLastAccessedTime(System.currentTimeMillis()); @@ -278,13 +292,13 @@ public class SessionRepositoryFilter extends OncePerR @Override public HttpSessionWrapper getSession(boolean create) { HttpSessionWrapper currentSession = getCurrentSession(); - if(currentSession != null) { + if (currentSession != null) { return currentSession; } String requestedSessionId = getRequestedSessionId(); - if(requestedSessionId != null) { + if (requestedSessionId != null) { S session = getSession(requestedSessionId); - if(session != null) { + if (session != null) { this.requestedSessionIdValid = true; currentSession = new HttpSessionWrapper(session, getServletContext()); currentSession.setNew(false); @@ -292,15 +306,15 @@ public class SessionRepositoryFilter extends OncePerR return currentSession; } } - if(!create) { + if (!create) { return null; } - if(SESSION_LOGGER.isDebugEnabled()) { + if (SESSION_LOGGER.isDebugEnabled()) { SESSION_LOGGER .debug("A new session was created. To help you troubleshoot where the session was created we provided a StackTrace (this is not an error). You can prevent this from appearing by disabling DEBUG logging for " + SESSION_LOGGER_NAME, new RuntimeException("For debugging purposes only (not an error)")); } - S session = sessionRepository.createSession(); + S session = SessionRepositoryFilter.this.sessionRepository.createSession(); session.setLastAccessedTime(System.currentTimeMillis()); currentSession = new HttpSessionWrapper(session, getServletContext()); setCurrentSession(currentSession); @@ -308,8 +322,8 @@ public class SessionRepositoryFilter extends OncePerR } public ServletContext getServletContext() { - if(servletContext != null) { - return servletContext; + if (this.servletContext != null) { + return this.servletContext; } // Servlet 3.0+ return super.getServletContext(); @@ -322,7 +336,7 @@ public class SessionRepositoryFilter extends OncePerR @Override public String getRequestedSessionId() { - return httpSessionStrategy.getRequestedSessionId(this); + return SessionRepositoryFilter.this.httpSessionStrategy.getRequestedSessionId(this); } /** @@ -333,38 +347,45 @@ public class SessionRepositoryFilter extends OncePerR */ private final class HttpSessionWrapper extends ExpiringSessionHttpSession { - public HttpSessionWrapper(S session, ServletContext servletContext) { + HttpSessionWrapper(S session, ServletContext servletContext) { super(session, servletContext); } public void invalidate() { super.invalidate(); - requestedSessionInvalidated = true; + SessionRepositoryRequestWrapper.this.requestedSessionInvalidated = true; setCurrentSession(null); - sessionRepository.delete(getId()); + SessionRepositoryFilter.this.sessionRepository.delete(getId()); } } } + /** + * A delegating implementation of {@link MultiHttpSessionStrategy}. + */ static class MultiHttpSessionStrategyAdapter implements MultiHttpSessionStrategy { private HttpSessionStrategy delegate; - public MultiHttpSessionStrategyAdapter(HttpSessionStrategy delegate) { + /** + * Create a new {@link MultiHttpSessionStrategyAdapter} instance. + * @param delegate the delegate HTTP session strategy + */ + MultiHttpSessionStrategyAdapter(HttpSessionStrategy delegate) { this.delegate = delegate; } public String getRequestedSessionId(HttpServletRequest request) { - return delegate.getRequestedSessionId(request); + return this.delegate.getRequestedSessionId(request); } public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) { - delegate.onNewSession(session, request, response); + this.delegate.onNewSession(session, request, response); } public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) { - delegate.onInvalidateSession(request, response); + this.delegate.onInvalidateSession(request, response); } public HttpServletRequest wrapRequest(HttpServletRequest request, diff --git a/spring-session/src/main/java/org/springframework/session/web/socket/config/annotation/AbstractSessionWebSocketMessageBrokerConfigurer.java b/spring-session/src/main/java/org/springframework/session/web/socket/config/annotation/AbstractSessionWebSocketMessageBrokerConfigurer.java index 2e239fe9..d7cd9912 100644 --- a/spring-session/src/main/java/org/springframework/session/web/socket/config/annotation/AbstractSessionWebSocketMessageBrokerConfigurer.java +++ b/spring-session/src/main/java/org/springframework/session/web/socket/config/annotation/AbstractSessionWebSocketMessageBrokerConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.socket.config.annotation; import org.springframework.beans.factory.annotation.Autowired; @@ -69,11 +70,10 @@ import org.springframework.web.util.UrlPathHelper; * } * * - * @author Rob Winch - * @since 1.0 - * * @param * the type of ExpiringSession + * @author Rob Winch + * @since 1.0 */ public abstract class AbstractSessionWebSocketMessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer { @@ -90,7 +90,7 @@ public abstract class AbstractSessionWebSocketMessageBrokerConfigurer sessionRepositoryInterceptor() { - return new SessionRepositoryMessageInterceptor(sessionRepository); + return new SessionRepositoryMessageInterceptor(this.sessionRepository); } + /** + * A {@link StompEndpointRegistry} that applies {@link HandshakeInterceptor}. + */ static class SessionStompEndpointRegistry implements StompEndpointRegistry { private final WebMvcStompEndpointRegistry registry; private final HandshakeInterceptor interceptor; - public SessionStompEndpointRegistry(WebMvcStompEndpointRegistry registry, + SessionStompEndpointRegistry(WebMvcStompEndpointRegistry registry, HandshakeInterceptor interceptor) { this.registry = registry; this.interceptor = interceptor; } public StompWebSocketEndpointRegistration addEndpoint(String... paths) { - StompWebSocketEndpointRegistration endpoints = registry.addEndpoint(paths); - endpoints.addInterceptors(interceptor); + StompWebSocketEndpointRegistration endpoints = this.registry.addEndpoint(paths); + endpoints.addInterceptors(this.interceptor); return endpoints; } @@ -159,4 +162,4 @@ public abstract class AbstractSessionWebSocketMessageBrokerConfigurer> httpSessionIdToWsSessions = new ConcurrentHashMap>(); + private final ConcurrentHashMap> httpSessionIdToWsSessions = new ConcurrentHashMap>(); public void onApplicationEvent(ApplicationEvent event) { - if(event instanceof SessionDestroyedEvent) { + if (event instanceof SessionDestroyedEvent) { SessionDestroyedEvent e = (SessionDestroyedEvent) event; closeWsSessions(e.getSessionId()); - } else if(event instanceof SessionConnectEvent) { + } + else if (event instanceof SessionConnectEvent) { SessionConnectEvent e = (SessionConnectEvent) event; afterConnectionEstablished(e.getWebSocketSession()); - } else if(event instanceof SessionDisconnectEvent) { + } + else if (event instanceof SessionDisconnectEvent) { SessionDisconnectEvent e = (SessionDisconnectEvent) event; Map sessionAttributes = SimpMessageHeaderAccessor.getSessionAttributes(e.getMessage().getHeaders()); String httpSessionId = sessionAttributes == null ? null : SessionRepositoryMessageInterceptor.getSessionId(sessionAttributes); @@ -70,7 +74,7 @@ public final class WebSocketRegistryListener implements ApplicationListener sessions = httpSessionIdToWsSessions.get(httpSessionId); - if(sessions != null) { + Map sessions = this.httpSessionIdToWsSessions.get(httpSessionId); + if (sessions != null) { boolean result = sessions.remove(wsSessionId) != null; - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Removal of " + wsSessionId + " was " + result); } - if(sessions.isEmpty()) { - httpSessionIdToWsSessions.remove(httpSessionId); - if(logger.isDebugEnabled()) { + if (sessions.isEmpty()) { + this.httpSessionIdToWsSessions.remove(httpSessionId); + if (logger.isDebugEnabled()) { logger.debug("Removed the corresponding HTTP Session for " + wsSessionId + " since it contained no WebSocket mappings"); } } @@ -104,30 +108,31 @@ public final class WebSocketRegistryListener implements ApplicationListener sessions = httpSessionIdToWsSessions.get(httpSessionId); - if(sessions == null) { + Map sessions = this.httpSessionIdToWsSessions.get(httpSessionId); + if (sessions == null) { sessions = - new ConcurrentHashMap(); - httpSessionIdToWsSessions.putIfAbsent(httpSessionId, sessions); - sessions = httpSessionIdToWsSessions.get(httpSessionId); + new ConcurrentHashMap(); + this.httpSessionIdToWsSessions.putIfAbsent(httpSessionId, sessions); + sessions = this.httpSessionIdToWsSessions.get(httpSessionId); } sessions.put(wsSession.getId(), wsSession); } private void closeWsSessions(String httpSessionId) { - Map sessionsToClose = httpSessionIdToWsSessions.remove(httpSessionId); - if(sessionsToClose == null) { + Map sessionsToClose = this.httpSessionIdToWsSessions.remove(httpSessionId); + if (sessionsToClose == null) { return; } - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Closing WebSocket connections associated to expired HTTP Session " + httpSessionId); } - for(WebSocketSession toClose : sessionsToClose.values()) { + for (WebSocketSession toClose : sessionsToClose.values()) { try { toClose.close(SESSION_EXPIRED_STATUS); - } catch (IOException e) { - logger.debug("Failed to close WebSocketSession (this is nothing to worry about but for debugging only)",e); + } + catch (IOException e) { + logger.debug("Failed to close WebSocketSession (this is nothing to worry about but for debugging only)", e); } } } -} \ No newline at end of file +} diff --git a/spring-session/src/main/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptor.java b/spring-session/src/main/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptor.java index f36352fd..b331729a 100644 --- a/spring-session/src/main/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptor.java +++ b/spring-session/src/main/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.socket.server; import java.util.EnumSet; @@ -62,6 +63,7 @@ import org.springframework.web.socket.server.HandshakeInterceptor; * . *

* + * @param the {@link ExpiringSession} type * @author Rob Winch * @since 1.0 */ @@ -75,7 +77,7 @@ public final class SessionRepositoryMessageInterceptor matchingMessageTypes; /** - * Creates a new instance + * Creates a new instance. * * @param sessionRepository the {@link SessionRepository} to use. Cannot be null. */ @@ -105,27 +107,27 @@ public final class SessionRepositoryMessageInterceptor matchingMessageTypes) { - Assert.notEmpty(matchingMessageTypes,"matchingMessageTypes cannot be null or empty"); + Assert.notEmpty(matchingMessageTypes, "matchingMessageTypes cannot be null or empty"); this.matchingMessageTypes = matchingMessageTypes; } @Override public Message preSend(Message message, MessageChannel channel) { - if(message == null) { + if (message == null) { return message; } SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders()); - if(!this.matchingMessageTypes.contains(messageType)) { + if (!this.matchingMessageTypes.contains(messageType)) { return super.preSend(message, channel); } Map sessionHeaders = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders()); String sessionId = sessionHeaders == null ? null : (String) sessionHeaders.get(SPRING_SESSION_ID_ATTR_NAME); if (sessionId != null) { - S session = sessionRepository.getSession(sessionId); + S session = this.sessionRepository.getSession(sessionId); if (session != null) { // update the last accessed time session.setLastAccessedTime(System.currentTimeMillis()); - sessionRepository.save(session); + this.sessionRepository.save(session); } } return super.preSend(message, channel); @@ -156,4 +158,4 @@ public final class SessionRepositoryMessageInterceptor attributes, String sessionId) { attributes.put(SPRING_SESSION_ID_ATTR_NAME, sessionId); } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/MapSessionRepositoryTests.java b/spring-session/src/test/java/org/springframework/session/MapSessionRepositoryTests.java index da15f14e..475d780f 100644 --- a/spring-session/src/test/java/org/springframework/session/MapSessionRepositoryTests.java +++ b/spring-session/src/test/java/org/springframework/session/MapSessionRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session; -import static org.assertj.core.api.Assertions.*; +package org.springframework.session; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class MapSessionRepositoryTests { MapSessionRepository repository; @@ -29,22 +30,22 @@ public class MapSessionRepositoryTests { @Before public void setup() { - repository = new MapSessionRepository(); - session = new MapSession(); + this.repository = new MapSessionRepository(); + this.session = new MapSession(); } @Test public void getSessionExpired() { - session.setMaxInactiveIntervalInSeconds(1); - session.setLastAccessedTime(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)); - repository.save(session); + this.session.setMaxInactiveIntervalInSeconds(1); + this.session.setLastAccessedTime(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)); + this.repository.save(this.session); - assertThat(repository.getSession(session.getId())).isNull(); + assertThat(this.repository.getSession(this.session.getId())).isNull(); } @Test public void createSessionDefaultExpiration() { - ExpiringSession session = repository.createSession(); + ExpiringSession session = this.repository.createSession(); assertThat(session).isInstanceOf(MapSession.class); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds()); @@ -53,10 +54,10 @@ public class MapSessionRepositoryTests { @Test public void createSessionCustomDefaultExpiration() { final int expectedMaxInterval = new MapSession().getMaxInactiveIntervalInSeconds() + 10; - repository.setDefaultMaxInactiveInterval(expectedMaxInterval); + this.repository.setDefaultMaxInactiveInterval(expectedMaxInterval); - ExpiringSession session = repository.createSession(); + ExpiringSession session = this.repository.createSession(); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInterval); } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/MapSessionTests.java b/spring-session/src/test/java/org/springframework/session/MapSessionTests.java index af7880b5..3088495a 100644 --- a/spring-session/src/test/java/org/springframework/session/MapSessionTests.java +++ b/spring-session/src/test/java/org/springframework/session/MapSessionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,23 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session; -import static org.assertj.core.api.Assertions.*; +package org.springframework.session; import java.util.Set; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class MapSessionTests { private MapSession session; @Before public void setup() { - session = new MapSession(); - session.setLastAccessedTime(1413258262962L); + this.session = new MapSession(); + this.session.setLastAccessedTime(1413258262962L); } @Test(expected = IllegalArgumentException.class) @@ -43,45 +44,45 @@ public class MapSessionTests { @Test public void setAttributeNullObjectRemoves() { String attr = "attr"; - session.setAttribute(attr, new Object()); - session.setAttribute(attr, null); - assertThat(session.getAttributeNames()).isEmpty(); + this.session.setAttribute(attr, new Object()); + this.session.setAttribute(attr, null); + assertThat(this.session.getAttributeNames()).isEmpty(); } @Test public void equalsNonSessionFalse() { - assertThat(session.equals(new Object())).isFalse(); + assertThat(this.session.equals(new Object())).isFalse(); } @Test public void equalsCustomSession() { CustomSession other = new CustomSession(); - session.setId(other.getId()); - assertThat(session.equals(other)).isTrue(); + this.session.setId(other.getId()); + assertThat(this.session.equals(other)).isTrue(); } @Test public void hashCodeEqualsIdHashCode() { - session.setId("constantId"); - assertThat(session.hashCode()).isEqualTo(session.getId().hashCode()); + this.session.setId("constantId"); + assertThat(this.session.hashCode()).isEqualTo(this.session.getId().hashCode()); } @Test public void isExpiredExact() { long now = 1413260062962L; - assertThat(session.isExpired(now)).isTrue(); + assertThat(this.session.isExpired(now)).isTrue(); } @Test public void isExpiredOneMsTooSoon() { long now = 1413260062961L; - assertThat(session.isExpired(now)).isFalse(); + assertThat(this.session.isExpired(now)).isFalse(); } @Test public void isExpiredOneMsAfter() { long now = 1413260062963L; - assertThat(session.isExpired(now)).isTrue(); + assertThat(this.session.isExpired(now)).isTrue(); } static class CustomSession implements ExpiringSession { @@ -131,4 +132,4 @@ public class MapSessionTests { } } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomCookieSerializerTests.java b/spring-session/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomCookieSerializerTests.java index 339d4ad7..0f4a13bf 100644 --- a/spring-session/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomCookieSerializerTests.java +++ b/spring-session/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomCookieSerializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.config.annotation.web.http; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +package org.springframework.session.config.annotation.web.http; import java.io.IOException; import java.util.Arrays; @@ -32,6 +27,7 @@ import javax.servlet.http.HttpServletRequest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -47,6 +43,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + /** * @author Rob Winch * @@ -70,22 +72,22 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests { @Before public void setup() { - chain = new MockFilterChain(); + this.chain = new MockFilterChain(); } @Test public void usesReadSessionIds() throws Exception { String sessionId = "sessionId"; - when(cookieSerializer.readCookieValues(any(HttpServletRequest.class))).thenReturn(Arrays.asList(sessionId)); + given(this.cookieSerializer.readCookieValues(any(HttpServletRequest.class))).willReturn(Arrays.asList(sessionId)); - sessionRepositoryFilter.doFilter(request, response, chain); + this.sessionRepositoryFilter.doFilter(this.request, this.response, this.chain); assertThat(getRequest().getRequestedSessionId()).isEqualTo(sessionId); } @Test public void usesWrite() throws Exception { - sessionRepositoryFilter.doFilter(request, response, new MockFilterChain() { + this.sessionRepositoryFilter.doFilter(this.request, this.response, new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) @@ -95,11 +97,11 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests { } }); - verify(cookieSerializer).writeCookieValue(any(CookieValue.class)); + verify(this.cookieSerializer).writeCookieValue(any(CookieValue.class)); } private HttpServletRequest getRequest() { - return (HttpServletRequest) chain.getRequest(); + return (HttpServletRequest) this.chain.getRequest(); } @EnableSpringHttpSession diff --git a/spring-session/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomMultiHttpSessionStrategyTests.java b/spring-session/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomMultiHttpSessionStrategyTests.java index 5d92c0ee..1624776a 100644 --- a/spring-session/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomMultiHttpSessionStrategyTests.java +++ b/spring-session/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomMultiHttpSessionStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.config.annotation.web.http; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +package org.springframework.session.config.annotation.web.http; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -26,6 +22,7 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -40,6 +37,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + /** * @author Rob Winch * @@ -63,18 +65,18 @@ public class EnableSpringHttpSessionCustomMultiHttpSessionStrategyTests { @Before public void setup() { - chain = new MockFilterChain(); + this.chain = new MockFilterChain(); } @Test public void wrapRequestAndResponseUsed() throws Exception { - when(strategy.wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(request); - when(strategy.wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(response); + given(this.strategy.wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(this.request); + given(this.strategy.wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(this.response); - sessionRepositoryFilter.doFilter(request, response, chain); + this.sessionRepositoryFilter.doFilter(this.request, this.response, this.chain); - verify(strategy).wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class)); - verify(strategy).wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class)); + verify(this.strategy).wrapRequest(any(HttpServletRequest.class), any(HttpServletResponse.class)); + verify(this.strategy).wrapResponse(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @EnableSpringHttpSession diff --git a/spring-session/src/test/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepositoryTest.java b/spring-session/src/test/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepositoryTest.java index bb4607cf..17c61e51 100644 --- a/spring-session/src/test/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepositoryTest.java +++ b/spring-session/src/test/java/org/springframework/session/data/gemfire/AbstractGemFireOperationsSessionRepositoryTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,24 +16,6 @@ package org.springframework.session.data.gemfire; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Fail.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; -import static org.mockito.Matchers.same; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.session.data.gemfire.AbstractGemFireOperationsSessionRepository.GemFireSession; -import static org.springframework.session.data.gemfire.AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; @@ -48,6 +30,11 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; +import com.gemstone.gemfire.cache.AttributesMutator; +import com.gemstone.gemfire.cache.EntryEvent; +import com.gemstone.gemfire.cache.Region; +import edu.umd.cs.mtc.MultithreadedTestCase; +import edu.umd.cs.mtc.TestFramework; import org.apache.commons.logging.Log; import org.junit.Before; import org.junit.Rule; @@ -58,6 +45,7 @@ import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; + import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.gemfire.GemfireOperations; @@ -72,18 +60,28 @@ import org.springframework.session.events.SessionDeletedEvent; import org.springframework.session.events.SessionDestroyedEvent; import org.springframework.session.events.SessionExpiredEvent; -import com.gemstone.gemfire.cache.AttributesMutator; -import com.gemstone.gemfire.cache.EntryEvent; -import com.gemstone.gemfire.cache.Region; - -import edu.umd.cs.mtc.MultithreadedTestCase; -import edu.umd.cs.mtc.TestFramework; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willAnswer; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isA; +import static org.mockito.Matchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * The AbstractGemFireOperationsSessionRepositoryTest class is a test suite of test cases testing the contract * and functionality of the AbstractGemFireOperationsSessionRepository class. * * @author John Blum + * @since 1.1.0 * @see org.junit.Rule * @see org.junit.Test * @see org.junit.rules.ExpectedException @@ -97,7 +95,6 @@ import edu.umd.cs.mtc.TestFramework; * @see org.springframework.session.data.gemfire.AbstractGemFireOperationsSessionRepository * @see edu.umd.cs.mtc.MultithreadedTestCase * @see edu.umd.cs.mtc.TestFramework - * @since 1.1.0 */ @RunWith(MockitoJUnitRunner.class) public class AbstractGemFireOperationsSessionRepositoryTest { @@ -117,9 +114,10 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Before public void setup() { - sessionRepository = new TestGemFireOperationsSessionRepository(mockGemfireOperations) { - @Override Log newLogger() { - return mockLog; + this.sessionRepository = new TestGemFireOperationsSessionRepository(this.mockGemfireOperations) { + @Override + Log newLogger() { + return AbstractGemFireOperationsSessionRepositoryTest.this.mockLog; } }; } @@ -142,18 +140,18 @@ public class AbstractGemFireOperationsSessionRepositoryTest { ExpiringSession mockSession = mock(ExpiringSession.class, sessionId); - when(mockSession.getId()).thenReturn(sessionId); - when(mockSession.getCreationTime()).thenReturn(creationTime); - when(mockSession.getLastAccessedTime()).thenReturn(lastAccessedTime); - when(mockSession.getMaxInactiveIntervalInSeconds()).thenReturn(maxInactiveIntervalInSeconds); + given(mockSession.getId()).willReturn(sessionId); + given(mockSession.getCreationTime()).willReturn(creationTime); + given(mockSession.getLastAccessedTime()).willReturn(lastAccessedTime); + given(mockSession.getMaxInactiveIntervalInSeconds()).willReturn(maxInactiveIntervalInSeconds); return mockSession; } @Test public void constructGemFireOperationsSessionRepositoryWithNullTemplate() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("GemfireOperations must not be null"); + this.expectedException.expect(IllegalArgumentException.class); + this.expectedException.expectMessage("GemfireOperations must not be null"); new TestGemFireOperationsSessionRepository(null); } @@ -161,11 +159,11 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @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); - when(mockRegion.getFullPath()).thenReturn("/Example"); - when(mockRegion.getAttributesMutator()).thenReturn(mockAttributesMutator); + given(mockRegion.getFullPath()).willReturn("/Example"); + given(mockRegion.getAttributesMutator()).willReturn(mockAttributesMutator); GemfireTemplate template = new GemfireTemplate(mockRegion); @@ -196,24 +194,24 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void maxInactiveIntervalInSecondsAllowsNegativeValuesAndExtremelyLargeValues() { - assertThat(sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo( + assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS); - sessionRepository.setMaxInactiveIntervalInSeconds(-1); + this.sessionRepository.setMaxInactiveIntervalInSeconds(-1); - assertThat(sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(-1); + assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(-1); - sessionRepository.setMaxInactiveIntervalInSeconds(Integer.MIN_VALUE); + this.sessionRepository.setMaxInactiveIntervalInSeconds(Integer.MIN_VALUE); - assertThat(sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MIN_VALUE); + assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MIN_VALUE); - sessionRepository.setMaxInactiveIntervalInSeconds(3600); + this.sessionRepository.setMaxInactiveIntervalInSeconds(3600); - assertThat(sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(3600); + assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(3600); - sessionRepository.setMaxInactiveIntervalInSeconds(Integer.MAX_VALUE); + this.sessionRepository.setMaxInactiveIntervalInSeconds(Integer.MAX_VALUE); - assertThat(sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MAX_VALUE); + assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MAX_VALUE); } @Test @@ -222,11 +220,11 @@ public class AbstractGemFireOperationsSessionRepositoryTest { final String sessionId = "abc123"; final ExpiringSession mockSession = mock(ExpiringSession.class); - when(mockSession.getId()).thenReturn(sessionId); + given(mockSession.getId()).willReturn(sessionId); ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -234,23 +232,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isEqualTo(mockSession); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn(sessionId); - when(mockEntryEvent.getNewValue()).thenReturn(mockSession); + given(mockEntryEvent.getKey()).willReturn(sessionId); + given(mockEntryEvent.getNewValue()).willReturn(mockSession); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.afterCreate(mockEntryEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.afterCreate(mockEntryEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockEntryEvent, times(1)).getKey(); verify(mockEntryEvent, times(2)).getNewValue(); @@ -266,7 +264,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -274,23 +272,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn(sessionId); - when(mockEntryEvent.getNewValue()).thenReturn(null); + given(mockEntryEvent.getKey()).willReturn(sessionId); + given(mockEntryEvent.getNewValue()).willReturn(null); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.afterCreate(mockEntryEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.afterCreate(mockEntryEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockEntryEvent, times(1)).getKey(); verify(mockEntryEvent, times(2)).getNewValue(); @@ -301,16 +299,17 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void afterCreatedWithNonSessionTypeDoesNotPublishSessionCreatedEvent() { - TestGemFireOperationsSessionRepository sessionRepository = new TestGemFireOperationsSessionRepository(mockGemfireOperations) { - @Override protected void handleCreated(String sessionId, ExpiringSession session) { + TestGemFireOperationsSessionRepository sessionRepository = new TestGemFireOperationsSessionRepository(this.mockGemfireOperations) { + @Override + protected void handleCreated(String sessionId, ExpiringSession session) { fail("handleCreated(..) should not have been called"); } }; EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn("abc123"); - when(mockEntryEvent.getNewValue()).thenReturn(new Tombstone()); + given(mockEntryEvent.getKey()).willReturn("abc123"); + given(mockEntryEvent.getNewValue()).willReturn(new Tombstone()); sessionRepository.afterCreate((EntryEvent) mockEntryEvent); @@ -325,11 +324,11 @@ public class AbstractGemFireOperationsSessionRepositoryTest { final String sessionId = "def456"; final ExpiringSession mockSession = mock(ExpiringSession.class); - when(mockSession.getId()).thenReturn(sessionId); + given(mockSession.getId()).willReturn(sessionId); ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -337,23 +336,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isEqualTo(mockSession); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn(sessionId); - when(mockEntryEvent.getOldValue()).thenReturn(mockSession); + given(mockEntryEvent.getKey()).willReturn(sessionId); + given(mockEntryEvent.getOldValue()).willReturn(mockSession); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.afterDestroy(mockEntryEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.afterDestroy(mockEntryEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockEntryEvent, times(1)).getKey(); verify(mockEntryEvent, never()).getNewValue(); @@ -369,7 +368,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -377,23 +376,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn(sessionId); - when(mockEntryEvent.getOldValue()).thenReturn(null); + given(mockEntryEvent.getKey()).willReturn(sessionId); + given(mockEntryEvent.getOldValue()).willReturn(null); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.afterDestroy(mockEntryEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.afterDestroy(mockEntryEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockEntryEvent, times(1)).getKey(); verify(mockEntryEvent, never()).getNewValue(); @@ -408,7 +407,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -416,23 +415,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn(sessionId); - when(mockEntryEvent.getOldValue()).thenReturn(new Tombstone()); + given(mockEntryEvent.getKey()).willReturn(sessionId); + given(mockEntryEvent.getOldValue()).willReturn(new Tombstone()); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.afterDestroy((EntryEvent) mockEntryEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.afterDestroy((EntryEvent) mockEntryEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockEntryEvent, times(1)).getKey(); verify(mockEntryEvent, never()).getNewValue(); @@ -446,11 +445,11 @@ public class AbstractGemFireOperationsSessionRepositoryTest { final String sessionId = "ghi789"; final ExpiringSession mockSession = mock(ExpiringSession.class); - when(mockSession.getId()).thenReturn(sessionId); + given(mockSession.getId()).willReturn(sessionId); ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -458,23 +457,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isEqualTo(mockSession); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn(sessionId); - when(mockEntryEvent.getOldValue()).thenReturn(mockSession); + given(mockEntryEvent.getKey()).willReturn(sessionId); + given(mockEntryEvent.getOldValue()).willReturn(mockSession); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.afterInvalidate(mockEntryEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.afterInvalidate(mockEntryEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockEntryEvent, times(1)).getKey(); verify(mockEntryEvent, never()).getNewValue(); @@ -490,7 +489,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -498,23 +497,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn(sessionId); - when(mockEntryEvent.getOldValue()).thenReturn(null); + given(mockEntryEvent.getKey()).willReturn(sessionId); + given(mockEntryEvent.getOldValue()).willReturn(null); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.afterInvalidate(mockEntryEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.afterInvalidate(mockEntryEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockEntryEvent, times(1)).getKey(); verify(mockEntryEvent, never()).getNewValue(); @@ -529,7 +528,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -537,23 +536,23 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); EntryEvent mockEntryEvent = mock(EntryEvent.class); - when(mockEntryEvent.getKey()).thenReturn(sessionId); - when(mockEntryEvent.getOldValue()).thenReturn(new Tombstone()); + given(mockEntryEvent.getKey()).willReturn(sessionId); + given(mockEntryEvent.getOldValue()).willReturn(new Tombstone()); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.afterInvalidate((EntryEvent) mockEntryEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.afterInvalidate((EntryEvent) mockEntryEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockEntryEvent, times(1)).getKey(); verify(mockEntryEvent, never()).getNewValue(); @@ -566,11 +565,11 @@ public class AbstractGemFireOperationsSessionRepositoryTest { final String sessionId = "abc123"; final ExpiringSession mockSession = mock(ExpiringSession.class); - when(mockSession.getId()).thenReturn(sessionId); + given(mockSession.getId()).willReturn(sessionId); ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -578,18 +577,18 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isEqualTo(mockSession); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.handleDeleted(sessionId, mockSession); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.handleDeleted(sessionId, mockSession); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockSession, times(1)).getId(); verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); @@ -601,7 +600,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -609,18 +608,18 @@ public class AbstractGemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isEqualTo(sessionRepository); + assertThat(sessionEvent.getSource()).isEqualTo(AbstractGemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(sessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); + }).given(mockApplicationEventPublisher).publishEvent(isA(ApplicationEvent.class)); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.handleDeleted(sessionId, null); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.handleDeleted(sessionId, null); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); } @@ -631,16 +630,16 @@ public class AbstractGemFireOperationsSessionRepositoryTest { ApplicationEventPublisher mockApplicationEventPublisher = mock(ApplicationEventPublisher.class); - doThrow(new IllegalStateException("test")).when(mockApplicationEventPublisher) + willThrow(new IllegalStateException("test")).given(mockApplicationEventPublisher) .publishEvent(any(ApplicationEvent.class)); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.publishEvent(mockApplicationEvent); + this.sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); + this.sessionRepository.publishEvent(mockApplicationEvent); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); verify(mockApplicationEventPublisher, times(1)).publishEvent(eq(mockApplicationEvent)); - verify(mockLog, times(1)).error(eq(String.format("error occurred publishing event (%1$s)", mockApplicationEvent)), + verify(this.mockLog, times(1)).error(eq(String.format("error occurred publishing event (%1$s)", mockApplicationEvent)), isA(IllegalStateException.class)); } @@ -648,7 +647,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void constructGemFireSessionWithDefaultInitialization() { final long beforeOrAtCreationTime = System.currentTimeMillis(); - GemFireSession session = new GemFireSession(); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession(); assertThat(session.getId()).isNotNull(); assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); @@ -662,7 +662,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void constructGemFireSessionWithId() { final long beforeOrAtCreationTime = System.currentTimeMillis(); - GemFireSession session = new GemFireSession("1"); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); assertThat(session.getId()).isEqualTo("1"); assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); @@ -674,19 +675,20 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void constructGemFireSessionWithSession() { - final long expectedCreationTime = 1l; - final long expectedLastAccessTime = 2l; + final long expectedCreationTime = 1L; + final long expectedLastAccessTime = 2L; ExpiringSession mockSession = mockSession("2", expectedCreationTime, expectedLastAccessTime, MAX_INACTIVE_INTERVAL_IN_SECONDS); Set expectedAttributedNames = asSet("attrOne", "attrTwo"); - when(mockSession.getAttributeNames()).thenReturn(expectedAttributedNames); - when(mockSession.getAttribute(eq("attrOne"))).thenReturn("testOne"); - when(mockSession.getAttribute(eq("attrTwo"))).thenReturn("testTwo"); + given(mockSession.getAttributeNames()).willReturn(expectedAttributedNames); + given(mockSession.getAttribute(eq("attrOne"))).willReturn("testOne"); + given(mockSession.getAttribute(eq("attrTwo"))).willReturn("testTwo"); - GemFireSession gemfireSession = new GemFireSession(mockSession); + AbstractGemFireOperationsSessionRepository.GemFireSession gemfireSession = + new AbstractGemFireOperationsSessionRepository.GemFireSession(mockSession); assertThat(gemfireSession.getId()).isEqualTo("2"); assertThat(gemfireSession.getCreationTime()).isEqualTo(expectedCreationTime); @@ -707,23 +709,24 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void constructGemFireSessionWithNullSession() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The ExpiringSession to copy cannot be null"); - new GemFireSession((ExpiringSession) null); + this.expectedException.expect(IllegalArgumentException.class); + this.expectedException.expectMessage("The ExpiringSession to copy cannot be null"); + new AbstractGemFireOperationsSessionRepository.GemFireSession((ExpiringSession) null); } @Test public void constructGemFireSessionWithUnspecifiedId() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("ID must be specified"); - new GemFireSession(" "); + this.expectedException.expect(IllegalArgumentException.class); + this.expectedException.expectMessage("ID must be specified"); + new AbstractGemFireOperationsSessionRepository.GemFireSession(" "); } @Test public void createNewGemFireSession() { final long beforeOrAtCreationTime = System.currentTimeMillis(); - GemFireSession session = GemFireSession.create(120); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + AbstractGemFireOperationsSessionRepository.GemFireSession.create(120); assertThat(session).isNotNull(); assertThat(session.getId()).isNotNull(); @@ -736,15 +739,16 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void fromExistingSession() { - final long expectedCreationTime = 1l; - final long expectedLastAccessedTime = 2l; + final long expectedCreationTime = 1L; + final long expectedLastAccessedTime = 2L; ExpiringSession mockSession = mockSession("4", expectedCreationTime, expectedLastAccessedTime, MAX_INACTIVE_INTERVAL_IN_SECONDS); - when(mockSession.getAttributeNames()).thenReturn(Collections.emptySet()); + given(mockSession.getAttributeNames()).willReturn(Collections.emptySet()); - GemFireSession gemfireSession = GemFireSession.from(mockSession); + AbstractGemFireOperationsSessionRepository.GemFireSession gemfireSession = + AbstractGemFireOperationsSessionRepository.GemFireSession.from(mockSession); assertThat(gemfireSession).isNotNull(); assertThat(gemfireSession.getId()).isEqualTo("4"); @@ -766,7 +770,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void setGetAndRemoveAttribute() { - GemFireSession session = GemFireSession.create(60); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + AbstractGemFireOperationsSessionRepository.GemFireSession.create(60); assertThat(session).isNotNull(); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(60); @@ -801,7 +806,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void isExpiredIsFalseWhenMaxInactiveIntervalIsNegative() { final int expectedMaxInactiveIntervalInSeconds = -1; - GemFireSession session = GemFireSession.create(expectedMaxInactiveIntervalInSeconds); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + AbstractGemFireOperationsSessionRepository.GemFireSession.create(expectedMaxInactiveIntervalInSeconds); assertThat(session).isNotNull(); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); @@ -812,7 +818,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void isExpiredIsFalseWhenSessionIsActive() { final int expectedMaxInactiveIntervalInSeconds = (int) TimeUnit.HOURS.toSeconds(2); - GemFireSession session = GemFireSession.create(expectedMaxInactiveIntervalInSeconds); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + AbstractGemFireOperationsSessionRepository.GemFireSession.create(expectedMaxInactiveIntervalInSeconds); assertThat(session).isNotNull(); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); @@ -829,7 +836,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void isExpiredIsTrueWhenSessionIsInactive() { final int expectedMaxInactiveIntervalInSeconds = 60; - GemFireSession session = GemFireSession.create(expectedMaxInactiveIntervalInSeconds); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + AbstractGemFireOperationsSessionRepository.GemFireSession.create(expectedMaxInactiveIntervalInSeconds); assertThat(session).isNotNull(); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(expectedMaxInactiveIntervalInSeconds); @@ -844,7 +852,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void setAndGetPrincipalName() { - GemFireSession session = GemFireSession.create(0); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + AbstractGemFireOperationsSessionRepository.GemFireSession.create(0); assertThat(session).isNotNull(); assertThat(session.getPrincipalName()).isNull(); @@ -869,14 +878,16 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionToData() throws Exception { @SuppressWarnings("serial") - GemFireSession session = new GemFireSession("1") { - @Override void writeObject(Object obj, DataOutput out) throws IOException { - assertThat(obj).isInstanceOf(GemFireSessionAttributes.class); - assertThat(out).isNotNull(); - } - }; + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession("1") { + @Override + void writeObject(Object obj, DataOutput out) throws IOException { + assertThat(obj).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes.class); + assertThat(out).isNotNull(); + } + }; - session.setLastAccessedTime(123l); + session.setLastAccessedTime(123L); session.setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); session.setPrincipalName("jblum"); @@ -894,8 +905,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionFromData() throws Exception { - final long expectedCreationTime = 1l; - final long expectedLastAccessedTime = 2l; + final long expectedCreationTime = 1L; + final long expectedLastAccessedTime = 2L; final int expectedMaxInactiveIntervalInSeconds = (int) TimeUnit.HOURS.toSeconds(6); @@ -903,24 +914,27 @@ public class AbstractGemFireOperationsSessionRepositoryTest { DataInput mockDataInput = mock(DataInput.class); - when(mockDataInput.readUTF()).thenReturn("2").thenReturn(expectedPrincipalName); - when(mockDataInput.readLong()).thenReturn(expectedCreationTime).thenReturn(expectedLastAccessedTime); - when(mockDataInput.readInt()).thenReturn(expectedMaxInactiveIntervalInSeconds); + given(mockDataInput.readUTF()).willReturn("2").willReturn(expectedPrincipalName); + given(mockDataInput.readLong()).willReturn(expectedCreationTime).willReturn(expectedLastAccessedTime); + given(mockDataInput.readInt()).willReturn(expectedMaxInactiveIntervalInSeconds); @SuppressWarnings("serial") - GemFireSession session = new GemFireSession("1") { - @Override @SuppressWarnings("unchecked") - T readObject(DataInput in) throws ClassNotFoundException, IOException { - assertThat(in).isNotNull(); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession("1") { + @Override + @SuppressWarnings("unchecked") + T readObject(DataInput in) throws ClassNotFoundException, IOException { + assertThat(in).isNotNull(); - GemFireSessionAttributes sessionAttributes = new GemFireSessionAttributes(); + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); - sessionAttributes.setAttribute("attrOne", "testOne"); - sessionAttributes.setAttribute("attrTwo", "testTwo"); + sessionAttributes.setAttribute("attrOne", "testOne"); + sessionAttributes.setAttribute("attrTwo", "testTwo"); - return (T) sessionAttributes; - } - }; + return (T) sessionAttributes; + } + }; session.fromData(mockDataInput); @@ -950,12 +964,14 @@ public class AbstractGemFireOperationsSessionRepositoryTest { final long beforeOrAtCreationTime = System.currentTimeMillis(); @SuppressWarnings("serial") - GemFireSession expectedSession = new GemFireSession("123") { - @Override void writeObject(Object obj, DataOutput out) throws IOException { - assertThat(obj).isInstanceOf(GemFireSessionAttributes.class); - assertThat(out).isNotNull(); - } - }; + AbstractGemFireOperationsSessionRepository.GemFireSession expectedSession = + new AbstractGemFireOperationsSessionRepository.GemFireSession("123") { + @Override + void writeObject(Object obj, DataOutput out) throws IOException { + assertThat(obj).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes.class); + assertThat(out).isNotNull(); + } + }; assertThat(expectedSession.getId()).isEqualTo("123"); assertThat(expectedSession.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); @@ -968,12 +984,14 @@ public class AbstractGemFireOperationsSessionRepositoryTest { expectedSession.toData(new DataOutputStream(outBytes)); @SuppressWarnings("serial") - GemFireSession deserializedSession = new GemFireSession("0") { - @SuppressWarnings("unchecked") - @Override T readObject(DataInput in) throws ClassNotFoundException, IOException { - return (T) new GemFireSessionAttributes(); - } - }; + AbstractGemFireOperationsSessionRepository.GemFireSession deserializedSession = + new AbstractGemFireOperationsSessionRepository.GemFireSession("0") { + @Override + @SuppressWarnings("unchecked") + T readObject(DataInput in) throws ClassNotFoundException, IOException { + return (T) new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); + } + }; deserializedSession.fromData(new DataInputStream(new ByteArrayInputStream(outBytes.toByteArray()))); @@ -987,12 +1005,13 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void hasDeltaWhenNoSessionChangesIsFalse() { - assertThat(new GemFireSession().hasDelta()).isFalse(); + assertThat(new AbstractGemFireOperationsSessionRepository.GemFireSession().hasDelta()).isFalse(); } @Test public void hasDeltaWhenSessionAttributesChangeIsTrue() { - GemFireSession session = new GemFireSession(); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession(); assertThat(session.hasDelta()).isFalse(); @@ -1003,9 +1022,10 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void hasDeltaWhenSessionLastAccessedTimeIsUpdatedIsTrue() { - final long expectedLastAccessTime = 1l; + final long expectedLastAccessTime = 1L; - GemFireSession session = new GemFireSession(); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession(); assertThat(session.getLastAccessedTime()).isNotEqualTo(expectedLastAccessTime); assertThat(session.hasDelta()).isFalse(); @@ -1025,7 +1045,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void hasDeltaWhenSessionMaxInactiveIntervalInSecondsIsUpdatedIsTrue() { final int expectedMaxInactiveIntervalInSeconds = 300; - GemFireSession session = new GemFireSession(); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession(); assertThat(session.getMaxInactiveIntervalInSeconds()).isNotEqualTo(expectedMaxInactiveIntervalInSeconds); assertThat(session.hasDelta()).isFalse(); @@ -1046,14 +1067,16 @@ public class AbstractGemFireOperationsSessionRepositoryTest { final DataOutput mockDataOutput = mock(DataOutput.class); @SuppressWarnings("serial") - GemFireSession session = new GemFireSession() { - @Override void writeObject(Object obj, DataOutput out) throws IOException { - assertThat(String.valueOf(obj)).isEqualTo("test"); - assertThat(out).isSameAs(mockDataOutput); - } - }; + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession() { + @Override + void writeObject(Object obj, DataOutput out) throws IOException { + assertThat(String.valueOf(obj)).isEqualTo("test"); + assertThat(out).isSameAs(mockDataOutput); + } + }; - session.setLastAccessedTime(1l); + session.setLastAccessedTime(1L); session.setMaxInactiveIntervalInSeconds(300); session.setAttribute("attrOne", "test"); @@ -1063,7 +1086,7 @@ public class AbstractGemFireOperationsSessionRepositoryTest { assertThat(session.hasDelta()).isFalse(); - verify(mockDataOutput, times(1)).writeLong(eq(1l)); + verify(mockDataOutput, times(1)).writeLong(eq(1L)); verify(mockDataOutput, times(1)).writeInt(eq(300)); verify(mockDataOutput, times(1)).writeInt(eq(1)); verify(mockDataOutput, times(1)).writeUTF(eq("attrOne")); @@ -1073,22 +1096,24 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void sessionFromDelta() throws Exception { final DataInput mockDataInput = mock(DataInput.class); - when(mockDataInput.readLong()).thenReturn(1l); - when(mockDataInput.readInt()).thenReturn(600).thenReturn(0); + given(mockDataInput.readLong()).willReturn(1L); + given(mockDataInput.readInt()).willReturn(600).willReturn(0); @SuppressWarnings("serial") - GemFireSession session = new GemFireSession() { - @Override @SuppressWarnings("unchecked") - T readObject(DataInput in) throws ClassNotFoundException, IOException { - assertThat(in).isSameAs(mockDataInput); - return (T) "test"; - } - }; + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession() { + @Override + @SuppressWarnings("unchecked") + T readObject(DataInput in) throws ClassNotFoundException, IOException { + assertThat(in).isSameAs(mockDataInput); + return (T) "test"; + } + }; session.fromDelta(mockDataInput); assertThat(session.hasDelta()).isFalse(); - assertThat(session.getLastAccessedTime()).isEqualTo(1l); + assertThat(session.getLastAccessedTime()).isEqualTo(1L); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(600); assertThat(session.getAttributeNames().isEmpty()).isTrue(); @@ -1101,8 +1126,10 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void sessionComparisons() { final long twoHoursAgo = (System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2)); - GemFireSession sessionOne = new GemFireSession(mockSession("1", twoHoursAgo, MAX_INACTIVE_INTERVAL_IN_SECONDS)); - GemFireSession sessionTwo = new GemFireSession("2"); + AbstractGemFireOperationsSessionRepository.GemFireSession sessionOne = + new AbstractGemFireOperationsSessionRepository.GemFireSession(mockSession("1", twoHoursAgo, MAX_INACTIVE_INTERVAL_IN_SECONDS)); + AbstractGemFireOperationsSessionRepository.GemFireSession sessionTwo = + new AbstractGemFireOperationsSessionRepository.GemFireSession("2"); assertThat(sessionOne.getCreationTime()).isEqualTo(twoHoursAgo); assertThat(sessionTwo.getCreationTime()).isGreaterThan(twoHoursAgo); @@ -1113,15 +1140,17 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionEqualsDifferentSessionBasedOnId() { - GemFireSession sessionOne = new GemFireSession("1"); + AbstractGemFireOperationsSessionRepository.GemFireSession sessionOne = + new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); - sessionOne.setLastAccessedTime(12345l); + sessionOne.setLastAccessedTime(12345L); sessionOne.setMaxInactiveIntervalInSeconds(120); sessionOne.setPrincipalName("jblum"); - GemFireSession sessionTwo = new GemFireSession("1"); + AbstractGemFireOperationsSessionRepository.GemFireSession sessionTwo = + new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); - sessionTwo.setLastAccessedTime(67890l); + sessionTwo.setLastAccessedTime(67890L); sessionTwo.setMaxInactiveIntervalInSeconds(300); sessionTwo.setPrincipalName("rwinch"); @@ -1134,7 +1163,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionHashCodeIsNotEqualToStringIdHashCode() { - GemFireSession session = new GemFireSession("1"); + AbstractGemFireOperationsSessionRepository.GemFireSession session = + new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); assertThat(session.getId()).isEqualTo("1"); assertThat(session.hashCode()).isNotEqualTo("1".hashCode()); @@ -1144,11 +1174,12 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void sessionAttributesFromSession() { Session mockSession = mock(Session.class); - when(mockSession.getAttributeNames()).thenReturn(asSet("attrOne", "attrTwo")); - when(mockSession.getAttribute(eq("attrOne"))).thenReturn("testOne"); - when(mockSession.getAttribute(eq("attrTwo"))).thenReturn("testTwo"); + given(mockSession.getAttributeNames()).willReturn(asSet("attrOne", "attrTwo")); + given(mockSession.getAttribute(eq("attrOne"))).willReturn("testOne"); + given(mockSession.getAttribute(eq("attrTwo"))).willReturn("testTwo"); - GemFireSessionAttributes sessionAttributes = new GemFireSessionAttributes(); + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); assertThat(sessionAttributes.getAttributeNames().isEmpty()).isTrue(); @@ -1166,12 +1197,14 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesFromSessionAttributes() { - GemFireSessionAttributes source = new GemFireSessionAttributes(); + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes source = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); source.setAttribute("attrOne", "testOne"); source.setAttribute("attrTwo", "testTwo"); - GemFireSessionAttributes target = new GemFireSessionAttributes(); + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes target = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); assertThat(target.getAttributeNames().isEmpty()).isTrue(); @@ -1188,13 +1221,15 @@ public class AbstractGemFireOperationsSessionRepositoryTest { final DataOutput mockDataOutput = mock(DataOutput.class); @SuppressWarnings("serial") - GemFireSessionAttributes sessionAttributes = new GemFireSessionAttributes() { - private int count = 0; - @Override void writeObject(Object obj, DataOutput out) throws IOException { - assertThat(Arrays.asList("testOne", "testTwo").get(count++)).isEqualTo(String.valueOf(obj)); - assertThat(out).isSameAs(mockDataOutput); - } - }; + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes() { + private int count = 0; + @Override + void writeObject(Object obj, DataOutput out) throws IOException { + assertThat(Arrays.asList("testOne", "testTwo").get(count++)).isEqualTo(String.valueOf(obj)); + assertThat(out).isSameAs(mockDataOutput); + } + }; sessionAttributes.setAttribute("attrOne", "testOne"); sessionAttributes.setAttribute("attrTwo", "testTwo"); @@ -1210,18 +1245,20 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void sessionAttributesFromData() throws Exception { final DataInput mockDataInput = mock(DataInput.class); - when(mockDataInput.readInt()).thenReturn(2); - when(mockDataInput.readUTF()).thenReturn("attrOne").thenReturn("attrTwo"); + given(mockDataInput.readInt()).willReturn(2); + given(mockDataInput.readUTF()).willReturn("attrOne").willReturn("attrTwo"); @SuppressWarnings("serial") - GemFireSessionAttributes sessionAttributes = new GemFireSessionAttributes() { - private int count = 0; - @Override @SuppressWarnings("unchecked") - T readObject(DataInput in) throws ClassNotFoundException, IOException { - assertThat(in).isSameAs(mockDataInput); - return (T) Arrays.asList("testOne", "testTwo").get(count++); - } - }; + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes() { + private int count = 0; + @Override + @SuppressWarnings("unchecked") + T readObject(DataInput in) throws ClassNotFoundException, IOException { + assertThat(in).isSameAs(mockDataInput); + return (T) Arrays.asList("testOne", "testTwo").get(count++); + } + }; assertThat(sessionAttributes.getAttributeNames().isEmpty()).isTrue(); @@ -1238,12 +1275,13 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesHasDeltaIsFalse() { - assertThat(new GemFireSessionAttributes().hasDelta()).isFalse(); + assertThat(new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes().hasDelta()).isFalse(); } @Test public void sessionAttributesHasDeltaIsTrue() { - GemFireSessionAttributes sessionAttributes = new GemFireSessionAttributes(); + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); assertThat(sessionAttributes.hasDelta()).isFalse(); @@ -1258,13 +1296,15 @@ public class AbstractGemFireOperationsSessionRepositoryTest { final DataOutput mockDataOutput = mock(DataOutput.class); @SuppressWarnings("serial") - GemFireSessionAttributes sessionAttributes = new 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(out).isSameAs(mockDataOutput); - } - }; + 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(out).isSameAs(mockDataOutput); + } + }; sessionAttributes.setAttribute("attrOne", "testOne"); sessionAttributes.setAttribute("attrTwo", "testTwo"); @@ -1304,18 +1344,20 @@ public class AbstractGemFireOperationsSessionRepositoryTest { public void sessionAttributesFromDelta() throws Exception { final DataInput mockDataInput = mock(DataInput.class); - when(mockDataInput.readInt()).thenReturn(2); - when(mockDataInput.readUTF()).thenReturn("attrOne").thenReturn("attrTwo"); + given(mockDataInput.readInt()).willReturn(2); + given(mockDataInput.readUTF()).willReturn("attrOne").willReturn("attrTwo"); @SuppressWarnings("serial") - GemFireSessionAttributes sessionAttributes = new GemFireSessionAttributes() { - private int count = 0; - @Override @SuppressWarnings("unchecked") - T readObject(DataInput in) throws ClassNotFoundException, IOException { - assertThat(in).isSameAs(mockDataInput); - return (T) Arrays.asList("testOne", "testTwo", "testThree").get(count++); - } - }; + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes() { + private int count = 0; + @Override + @SuppressWarnings("unchecked") + T readObject(DataInput in) throws ClassNotFoundException, IOException { + assertThat(in).isSameAs(mockDataInput); + return (T) Arrays.asList("testOne", "testTwo", "testThree").get(count++); + } + }; sessionAttributes.setAttribute("attrOne", "one"); sessionAttributes.setAttribute("attrTwo", "two"); @@ -1338,8 +1380,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { verify(mockDataInput, times(2)).readUTF(); reset(mockDataInput); - when(mockDataInput.readInt()).thenReturn(1); - when(mockDataInput.readUTF()).thenReturn("attrTwo"); + given(mockDataInput.readInt()).willReturn(1); + given(mockDataInput.readUTF()).willReturn("attrTwo"); sessionAttributes.setAttribute("attrOne", "one"); sessionAttributes.setAttribute("attrTwo", "two"); @@ -1364,7 +1406,8 @@ public class AbstractGemFireOperationsSessionRepositoryTest { @Test public void sessionAttributesEntrySetIteratesAttributeNameValues() { - GemFireSessionAttributes sessionAttributes = new GemFireSessionAttributes(); + AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes sessionAttributes = + new AbstractGemFireOperationsSessionRepository.GemFireSessionAttributes(); sessionAttributes.setAttribute("keyOne", "valueOne"); sessionAttributes.setAttribute("keyTwo", "valueTwo"); @@ -1420,27 +1463,27 @@ public class AbstractGemFireOperationsSessionRepositoryTest { private final long beforeOrAtCreationTime = System.currentTimeMillis(); - private GemFireSession session; + private AbstractGemFireOperationsSessionRepository.GemFireSession session; private volatile long expectedCreationTime; @Override public void initialize() { - session = new GemFireSession("1"); + this.session = new AbstractGemFireOperationsSessionRepository.GemFireSession("1"); - assertThat(session).isNotNull(); - assertThat(session.getId()).isEqualTo("1"); - assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); - assertThat(session.getLastAccessedTime()).isEqualTo(session.getCreationTime()); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(0); - assertThat(session.getPrincipalName()).isNull(); - assertThat(session.getAttributeNames().isEmpty()).isTrue(); + assertThat(this.session).isNotNull(); + assertThat(this.session.getId()).isEqualTo("1"); + assertThat(this.session.getCreationTime()).isGreaterThanOrEqualTo(this.beforeOrAtCreationTime); + assertThat(this.session.getLastAccessedTime()).isEqualTo(this.session.getCreationTime()); + assertThat(this.session.getMaxInactiveIntervalInSeconds()).isEqualTo(0); + assertThat(this.session.getPrincipalName()).isNull(); + assertThat(this.session.getAttributeNames().isEmpty()).isTrue(); - expectedCreationTime = session.getCreationTime(); + this.expectedCreationTime = this.session.getCreationTime(); - session.setLastAccessedTime(0l); - session.setMaxInactiveIntervalInSeconds(60); - session.setPrincipalName("jblum"); + this.session.setLastAccessedTime(0L); + this.session.setMaxInactiveIntervalInSeconds(60); + this.session.setPrincipalName("jblum"); } public void thread1() { @@ -1448,35 +1491,35 @@ public class AbstractGemFireOperationsSessionRepositoryTest { Thread.currentThread().setName("HTTP Request Processing Thread 1"); - assertThat(session).isNotNull(); - assertThat(session.getId()).isEqualTo("1"); - assertThat(session.getCreationTime()).isEqualTo(expectedCreationTime); - assertThat(session.getLastAccessedTime()).isEqualTo(0l); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(60); - assertThat(session.getPrincipalName()).isEqualTo("jblum"); - assertThat(session.getAttributeNames().size()).isEqualTo(1); - assertThat(String.valueOf(session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME))).isEqualTo("jblum"); + 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.getPrincipalName()).isEqualTo("jblum"); + assertThat(this.session.getAttributeNames().size()).isEqualTo(1); + assertThat(String.valueOf(this.session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME))).isEqualTo("jblum"); - session.setAttribute("tennis", "ping"); - session.setAttribute("junk", "test"); - session.setLastAccessedTime(1l); - session.setMaxInactiveIntervalInSeconds(120); - session.setPrincipalName("rwinch"); + this.session.setAttribute("tennis", "ping"); + this.session.setAttribute("junk", "test"); + this.session.setLastAccessedTime(1L); + this.session.setMaxInactiveIntervalInSeconds(120); + this.session.setPrincipalName("rwinch"); waitForTick(2); - assertThat(session).isNotNull(); - assertThat(session.getId()).isEqualTo("1"); - assertThat(session.getCreationTime()).isEqualTo(expectedCreationTime); - assertThat(session.getLastAccessedTime()).isEqualTo(2l); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(180); - assertThat(session.getPrincipalName()).isEqualTo("ogierke"); - assertThat(session.getAttributeNames().size()).isEqualTo(3); - assertThat(session.getAttributeNames().containsAll(asSet("tennis", "greeting"))).isTrue(); - assertThat(session.getAttributeNames().contains("junk")).isFalse(); - assertThat(session.getAttribute("junk")).isNull(); - assertThat(String.valueOf(session.getAttribute("tennis"))).isEqualTo("pong"); - assertThat(String.valueOf(session.getAttribute("greeting"))).isEqualTo("hello"); + 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.getAttributeNames().contains("junk")).isFalse(); + assertThat(this.session.getAttribute("junk")).isNull(); + assertThat(String.valueOf(this.session.getAttribute("tennis"))).isEqualTo("pong"); + assertThat(String.valueOf(this.session.getAttribute("greeting"))).isEqualTo("hello"); } public void thread2() { @@ -1487,28 +1530,28 @@ public class AbstractGemFireOperationsSessionRepositoryTest { waitForTick(1); assertTick(1); - assertThat(session).isNotNull(); - assertThat(session.getId()).isEqualTo("1"); - assertThat(session.getCreationTime()).isEqualTo(expectedCreationTime); - assertThat(session.getLastAccessedTime()).isEqualTo(1l); - assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(120); - assertThat(session.getPrincipalName()).isEqualTo("rwinch"); - assertThat(session.getAttributeNames().size()).isEqualTo(3); - assertThat(session.getAttributeNames().containsAll(asSet("tennis", "junk"))).isTrue(); - assertThat(String.valueOf(session.getAttribute("junk"))).isEqualTo("test"); - assertThat(String.valueOf(session.getAttribute("tennis"))).isEqualTo("ping"); + 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.getPrincipalName()).isEqualTo("rwinch"); + assertThat(this.session.getAttributeNames().size()).isEqualTo(3); + assertThat(this.session.getAttributeNames().containsAll(asSet("tennis", "junk"))).isTrue(); + assertThat(String.valueOf(this.session.getAttribute("junk"))).isEqualTo("test"); + assertThat(String.valueOf(this.session.getAttribute("tennis"))).isEqualTo("ping"); - session.setAttribute("tennis", "pong"); - session.setAttribute("greeting", "hello"); - session.removeAttribute("junk"); - session.setLastAccessedTime(2l); - session.setMaxInactiveIntervalInSeconds(180); - session.setPrincipalName("ogierke"); + 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"); } @Override public void finish() { - session = null; + this.session = null; } } diff --git a/spring-session/src/test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryTest.java b/spring-session/src/test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryTest.java index ee23dd0c..9a4c35aa 100644 --- a/spring-session/src/test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryTest.java +++ b/spring-session/src/test/java/org/springframework/session/data/gemfire/GemFireOperationsSessionRepositoryTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,27 +16,14 @@ package org.springframework.session.data.gemfire; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; -import static org.mockito.Matchers.same; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME; -import static org.springframework.session.data.gemfire.GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY; -import static org.springframework.session.data.gemfire.GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY; -import static org.springframework.session.data.gemfire.GemFireOperationsSessionRepository.GemFireSession; - import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; +import com.gemstone.gemfire.cache.AttributesMutator; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.query.SelectResults; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -45,23 +32,34 @@ import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; + 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.events.AbstractSessionEvent; import org.springframework.session.events.SessionDeletedEvent; -import com.gemstone.gemfire.cache.AttributesMutator; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.query.SelectResults; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willAnswer; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isA; +import static org.mockito.Matchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * The GemFireOperationsSessionRepositoryTest class is a test suite of test cases testing the contract and functionality * of the GemFireOperationsSessionRepository class. * * @author John Blum + * @since 1.1.0 * @see org.junit.Test * @see org.junit.runner.RunWith * @see org.mockito.Mock @@ -69,7 +67,6 @@ import com.gemstone.gemfire.cache.query.SelectResults; * @see org.mockito.runners.MockitoJUnitRunner * @see org.springframework.session.data.gemfire.GemFireOperationsSessionRepository * @see com.gemstone.gemfire.cache.Region - * @since 1.1.0 */ @RunWith(MockitoJUnitRunner.class) public class GemFireOperationsSessionRepositoryTest { @@ -92,25 +89,25 @@ public class GemFireOperationsSessionRepositoryTest { @Before public void setup() throws Exception { - when(mockRegion.getAttributesMutator()).thenReturn(mockAttributesMutator); - when(mockRegion.getFullPath()).thenReturn("/Example"); - when(mockTemplate.getRegion()).thenReturn(mockRegion); + given(this.mockRegion.getAttributesMutator()).willReturn(this.mockAttributesMutator); + given(this.mockRegion.getFullPath()).willReturn("/Example"); + given(this.mockTemplate.getRegion()).willReturn(this.mockRegion); - sessionRepository = new GemFireOperationsSessionRepository(mockTemplate); - sessionRepository.setApplicationEventPublisher(mockApplicationEventPublisher); - sessionRepository.setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); - sessionRepository.afterPropertiesSet(); + this.sessionRepository = new GemFireOperationsSessionRepository(this.mockTemplate); + this.sessionRepository.setApplicationEventPublisher(this.mockApplicationEventPublisher); + this.sessionRepository.setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); + this.sessionRepository.afterPropertiesSet(); - assertThat(sessionRepository.getApplicationEventPublisher()).isSameAs(mockApplicationEventPublisher); - assertThat(sessionRepository.getFullyQualifiedRegionName()).isEqualTo("/Example"); - assertThat(sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); + assertThat(this.sessionRepository.getApplicationEventPublisher()).isSameAs(this.mockApplicationEventPublisher); + assertThat(this.sessionRepository.getFullyQualifiedRegionName()).isEqualTo("/Example"); + assertThat(this.sessionRepository.getMaxInactiveIntervalInSeconds()).isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); } @After public void tearDown() { - verify(mockAttributesMutator, times(1)).addCacheListener(same(sessionRepository)); - verify(mockRegion, times(1)).getFullPath(); - verify(mockTemplate, times(1)).getRegion(); + verify(this.mockAttributesMutator, times(1)).addCacheListener(same(this.sessionRepository)); + verify(this.mockRegion, times(1)).getFullPath(); + verify(this.mockTemplate, times(1)).getRegion(); } @Test @@ -118,27 +115,27 @@ public class GemFireOperationsSessionRepositoryTest { public void findByIndexNameValueFindsMatchingSession() { ExpiringSession mockSession = mock(ExpiringSession.class, "MockSession"); - when(mockSession.getId()).thenReturn("1"); + given(mockSession.getId()).willReturn("1"); SelectResults mockSelectResults = mock(SelectResults.class); - when(mockSelectResults.asList()).thenReturn(Collections.singletonList(mockSession)); + given(mockSelectResults.asList()).willReturn(Collections.singletonList(mockSession)); String indexName = "vip"; String indexValue = "rwinch"; - String expectedQql = String.format(FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY, - sessionRepository.getFullyQualifiedRegionName(), indexName); + String expectedQql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY, + this.sessionRepository.getFullyQualifiedRegionName(), indexName); - when(mockTemplate.find(eq(expectedQql), eq(indexValue))).thenReturn(mockSelectResults); + given(this.mockTemplate.find(eq(expectedQql), eq(indexValue))).willReturn(mockSelectResults); - Map sessions = sessionRepository.findByIndexNameAndIndexValue(indexName, indexValue); + Map sessions = this.sessionRepository.findByIndexNameAndIndexValue(indexName, indexValue); assertThat(sessions).isNotNull(); assertThat(sessions.size()).isEqualTo(1); assertThat(sessions.get("1")).isEqualTo(mockSession); - verify(mockTemplate, times(1)).find(eq(expectedQql), eq(indexValue)); + verify(this.mockTemplate, times(1)).find(eq(expectedQql), eq(indexValue)); verify(mockSelectResults, times(1)).asList(); verify(mockSession, times(1)).getId(); } @@ -150,23 +147,23 @@ public class GemFireOperationsSessionRepositoryTest { ExpiringSession mockSessionTwo = mock(ExpiringSession.class, "MockSessionTwo"); ExpiringSession mockSessionThree = mock(ExpiringSession.class, "MockSessionThree"); - when(mockSessionOne.getId()).thenReturn("1"); - when(mockSessionTwo.getId()).thenReturn("2"); - when(mockSessionThree.getId()).thenReturn("3"); + given(mockSessionOne.getId()).willReturn("1"); + given(mockSessionTwo.getId()).willReturn("2"); + given(mockSessionThree.getId()).willReturn("3"); SelectResults mockSelectResults = mock(SelectResults.class); - when(mockSelectResults.asList()).thenReturn(Arrays.asList(mockSessionOne, mockSessionTwo, mockSessionThree)); + given(mockSelectResults.asList()).willReturn(Arrays.asList(mockSessionOne, mockSessionTwo, mockSessionThree)); String principalName = "jblum"; - String expectedOql = String.format(FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY, - sessionRepository.getFullyQualifiedRegionName()); + String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY, + this.sessionRepository.getFullyQualifiedRegionName()); - when(mockTemplate.find(eq(expectedOql), eq(principalName))).thenReturn(mockSelectResults); + given(this.mockTemplate.find(eq(expectedOql), eq(principalName))).willReturn(mockSelectResults); - Map sessions = sessionRepository.findByIndexNameAndIndexValue( - PRINCIPAL_NAME_INDEX_NAME, principalName); + Map sessions = this.sessionRepository.findByIndexNameAndIndexValue( + FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName); assertThat(sessions).isNotNull(); assertThat(sessions.size()).isEqualTo(3); @@ -174,7 +171,7 @@ public class GemFireOperationsSessionRepositoryTest { assertThat(sessions.get("2")).isEqualTo(mockSessionTwo); assertThat(sessions.get("3")).isEqualTo(mockSessionThree); - verify(mockTemplate, times(1)).find(eq(expectedOql), eq(principalName)); + verify(this.mockTemplate, times(1)).find(eq(expectedOql), eq(principalName)); verify(mockSelectResults, times(1)).asList(); verify(mockSessionOne, times(1)).getId(); verify(mockSessionTwo, times(1)).getId(); @@ -186,30 +183,30 @@ public class GemFireOperationsSessionRepositoryTest { public void findByPrincipalNameReturnsNoMatchingSessions() { SelectResults mockSelectResults = mock(SelectResults.class); - when(mockSelectResults.asList()).thenReturn(Collections.emptyList()); + given(mockSelectResults.asList()).willReturn(Collections.emptyList()); String principalName = "jblum"; - String expectedOql = String.format(FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY, - sessionRepository.getFullyQualifiedRegionName()); + String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY, + this.sessionRepository.getFullyQualifiedRegionName()); - when(mockTemplate.find(eq(expectedOql), eq(principalName))).thenReturn(mockSelectResults); + given(this.mockTemplate.find(eq(expectedOql), eq(principalName))).willReturn(mockSelectResults); - Map sessions = sessionRepository.findByIndexNameAndIndexValue( - PRINCIPAL_NAME_INDEX_NAME, principalName); + Map sessions = this.sessionRepository.findByIndexNameAndIndexValue( + FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName); assertThat(sessions).isNotNull(); assertThat(sessions.isEmpty()).isTrue(); - verify(mockTemplate, times(1)).find(eq(expectedOql), eq(principalName)); + verify(this.mockTemplate, times(1)).find(eq(expectedOql), eq(principalName)); verify(mockSelectResults, times(1)).asList(); } @Test public void prepareQueryReturnsPrincipalNameOql() { - String actualQql = sessionRepository.prepareQuery(PRINCIPAL_NAME_INDEX_NAME); - String expectedOql = String.format(FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY, - sessionRepository.getFullyQualifiedRegionName()); + String actualQql = this.sessionRepository.prepareQuery(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); + String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_PRINCIPAL_NAME_QUERY, + this.sessionRepository.getFullyQualifiedRegionName()); assertThat(actualQql).isEqualTo(expectedOql); } @@ -217,9 +214,9 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void prepareQueryReturnsIndexNameValueOql() { String attributeName = "testAttributeName"; - String actualOql = sessionRepository.prepareQuery(attributeName); - String expectedOql = String.format(FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY, - sessionRepository.getFullyQualifiedRegionName(), attributeName); + String actualOql = this.sessionRepository.prepareQuery(attributeName); + String expectedOql = String.format(GemFireOperationsSessionRepository.FIND_SESSIONS_BY_INDEX_NAME_VALUE_QUERY, + this.sessionRepository.getFullyQualifiedRegionName(), attributeName); assertThat(actualOql).isEqualTo(expectedOql); } @@ -228,9 +225,9 @@ public class GemFireOperationsSessionRepositoryTest { public void createProperlyInitializedSession() { final long beforeOrAtCreationTime = System.currentTimeMillis(); - ExpiringSession session = sessionRepository.createSession(); + ExpiringSession session = this.sessionRepository.createSession(); - assertThat(session).isInstanceOf(GemFireSession.class); + assertThat(session).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class); assertThat(session.getId()).isNotNull(); assertThat(session.getAttributeNames().isEmpty()).isTrue(); assertThat(session.getCreationTime()).isGreaterThanOrEqualTo(beforeOrAtCreationTime); @@ -244,12 +241,12 @@ public class GemFireOperationsSessionRepositoryTest { final ExpiringSession mockSession = mock(ExpiringSession.class); - when(mockSession.isExpired()).thenReturn(true); - when(mockSession.getId()).thenReturn(expectedSessionId); - when(mockTemplate.get(eq(expectedSessionId))).thenReturn(mockSession); - when(mockTemplate.remove(eq(expectedSessionId))).thenReturn(mockSession); + 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); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(final InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -257,21 +254,21 @@ public class GemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isSameAs(sessionRepository); + assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isSameAs(mockSession); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(any(ApplicationEvent.class)); + }).given(this.mockApplicationEventPublisher).publishEvent(any(ApplicationEvent.class)); - assertThat(sessionRepository.getSession(expectedSessionId)).isNull(); + assertThat(this.sessionRepository.getSession(expectedSessionId)).isNull(); - verify(mockTemplate, times(1)).get(eq(expectedSessionId)); - verify(mockTemplate, times(1)).remove(eq(expectedSessionId)); + verify(this.mockTemplate, times(1)).get(eq(expectedSessionId)); + verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId)); verify(mockSession, times(1)).isExpired(); verify(mockSession, times(2)).getId(); - verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); + verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); } @Test @@ -283,15 +280,15 @@ public class GemFireOperationsSessionRepositoryTest { ExpiringSession mockSession = mock(ExpiringSession.class); - when(mockSession.isExpired()).thenReturn(false); - when(mockSession.getId()).thenReturn(expectedId); - when(mockSession.getCreationTime()).thenReturn(expectedCreationTime); - when(mockSession.getLastAccessedTime()).thenReturn(currentLastAccessedTime); - when(mockSession.getAttributeNames()).thenReturn(Collections.singleton("attrOne")); - when(mockSession.getAttribute(eq("attrOne"))).thenReturn("test"); - when(mockTemplate.get(eq(expectedId))).thenReturn(mockSession); + given(mockSession.isExpired()).willReturn(false); + given(mockSession.getId()).willReturn(expectedId); + given(mockSession.getCreationTime()).willReturn(expectedCreationTime); + given(mockSession.getLastAccessedTime()).willReturn(currentLastAccessedTime); + given(mockSession.getAttributeNames()).willReturn(Collections.singleton("attrOne")); + given(mockSession.getAttribute(eq("attrOne"))).willReturn("test"); + given(this.mockTemplate.get(eq(expectedId))).willReturn(mockSession); - ExpiringSession actualSession = sessionRepository.getSession(expectedId); + ExpiringSession actualSession = this.sessionRepository.getSession(expectedId); assertThat(actualSession).isNotSameAs(mockSession); assertThat(actualSession.getId()).isEqualTo(expectedId); @@ -301,7 +298,7 @@ public class GemFireOperationsSessionRepositoryTest { assertThat(actualSession.getAttributeNames()).isEqualTo(Collections.singleton("attrOne")); assertThat(String.valueOf(actualSession.getAttribute("attrOne"))).isEqualTo("test"); - verify(mockTemplate, times(1)).get(eq(expectedId)); + verify(this.mockTemplate, times(1)).get(eq(expectedId)); verify(mockSession, times(1)).isExpired(); verify(mockSession, times(1)).getId(); verify(mockSession, times(1)).getCreationTime(); @@ -312,8 +309,8 @@ public class GemFireOperationsSessionRepositoryTest { @Test public void getSessionReturnsNull() { - when(mockTemplate.get(anyString())).thenReturn(null); - assertThat(sessionRepository.getSession("1")).isNull(); + given(this.mockTemplate.get(anyString())).willReturn(null); + assertThat(this.sessionRepository.getSession("1")).isNull(); } @Test @@ -325,14 +322,14 @@ public class GemFireOperationsSessionRepositoryTest { ExpiringSession mockSession = mock(ExpiringSession.class); - when(mockSession.getId()).thenReturn(expectedSessionId); - when(mockSession.getCreationTime()).thenReturn(expectedCreationTime); - when(mockSession.getLastAccessedTime()).thenReturn(expectedLastAccessTime); - when(mockSession.getMaxInactiveIntervalInSeconds()).thenReturn(MAX_INACTIVE_INTERVAL_IN_SECONDS); - when(mockSession.getAttributeNames()).thenReturn(Collections.emptySet()); + 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()); - when(mockTemplate.put(eq(expectedSessionId), isA(GemFireSession.class))) - .thenAnswer(new Answer() { + given(this.mockTemplate.put(eq(expectedSessionId), isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class))) + .willAnswer(new Answer() { public ExpiringSession answer(final InvocationOnMock invocation) throws Throwable { ExpiringSession session = invocation.getArgumentAt(1, ExpiringSession.class); @@ -347,14 +344,14 @@ public class GemFireOperationsSessionRepositoryTest { } }); - sessionRepository.save(mockSession); + 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)).getAttributeNames(); - verify(mockTemplate, times(1)).put(eq(expectedSessionId), isA(GemFireSession.class)); + verify(this.mockTemplate, times(1)).put(eq(expectedSessionId), isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class)); } @Test @@ -363,10 +360,10 @@ public class GemFireOperationsSessionRepositoryTest { final ExpiringSession mockSession = mock(ExpiringSession.class); - when(mockSession.getId()).thenReturn(expectedSessionId); - when(mockTemplate.remove(eq(expectedSessionId))).thenReturn(mockSession); + given(mockSession.getId()).willReturn(expectedSessionId); + given(this.mockTemplate.remove(eq(expectedSessionId))).willReturn(mockSession); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(final InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -374,28 +371,28 @@ public class GemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isSameAs(sessionRepository); + assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isSameAs(mockSession); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class)); + }).given(this.mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class)); - sessionRepository.delete(expectedSessionId); + this.sessionRepository.delete(expectedSessionId); verify(mockSession, times(1)).getId(); - verify(mockTemplate, times(1)).remove(eq(expectedSessionId)); - verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); + verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId)); + verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); } @Test public void deleteRemovesNonExistingSessionAndHandlesDelete() { final String expectedSessionId = "1"; - when(mockTemplate.remove(anyString())).thenReturn(null); + given(this.mockTemplate.remove(anyString())).willReturn(null); - doAnswer(new Answer() { + willAnswer(new Answer() { public Void answer(final InvocationOnMock invocation) throws Throwable { ApplicationEvent applicationEvent = invocation.getArgumentAt(0, ApplicationEvent.class); @@ -403,18 +400,18 @@ public class GemFireOperationsSessionRepositoryTest { AbstractSessionEvent sessionEvent = (AbstractSessionEvent) applicationEvent; - assertThat(sessionEvent.getSource()).isSameAs(sessionRepository); + assertThat(sessionEvent.getSource()).isSameAs(GemFireOperationsSessionRepositoryTest.this.sessionRepository); assertThat(sessionEvent.getSession()).isNull(); assertThat(sessionEvent.getSessionId()).isEqualTo(expectedSessionId); return null; } - }).when(mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class)); + }).given(this.mockApplicationEventPublisher).publishEvent(isA(SessionDeletedEvent.class)); - sessionRepository.delete(expectedSessionId); + this.sessionRepository.delete(expectedSessionId); - verify(mockTemplate, times(1)).remove(eq(expectedSessionId)); - verify(mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); + verify(this.mockTemplate, times(1)).remove(eq(expectedSessionId)); + verify(this.mockApplicationEventPublisher, times(1)).publishEvent(isA(SessionDeletedEvent.class)); } protected abstract class GemfireOperationsAccessor extends GemfireAccessor implements GemfireOperations { diff --git a/spring-session/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfigurationTest.java b/spring-session/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfigurationTest.java index 585e319a..9de41070 100644 --- a/spring-session/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfigurationTest.java +++ b/spring-session/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfigurationTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,35 +16,36 @@ package org.springframework.session.data.gemfire.config.annotation.web.http; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.springframework.core.type.AnnotationMetadata; -import org.springframework.data.gemfire.GemfireOperations; -import org.springframework.data.gemfire.GemfireTemplate; -import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; - import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.GemFireCache; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.RegionShortcut; import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.ClientRegionShortcut; +import org.junit.Before; +import org.junit.Test; + +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.data.gemfire.GemfireOperations; +import org.springframework.data.gemfire.GemfireTemplate; +import org.springframework.session.data.gemfire.GemFireOperationsSessionRepository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * The GemFireHttpSessionConfigurationTest class is a test suite of test cases testing the contract and functionality * of the {@link GemFireHttpSessionConfiguration} class. * * @author John Blum + * @since 1.1.0 * @see org.junit.Test * @see org.mockito.Mockito * @see org.springframework.data.gemfire.GemfireOperations @@ -55,7 +56,6 @@ import com.gemstone.gemfire.cache.client.ClientRegionShortcut; * @see com.gemstone.gemfire.cache.GemFireCache * @see com.gemstone.gemfire.cache.Region * @see com.gemstone.gemfire.cache.client.ClientCache - * @since 1.1.0 */ public class GemFireHttpSessionConfigurationTest { @@ -67,119 +67,119 @@ public class GemFireHttpSessionConfigurationTest { @Before public void setup() { - gemfireConfiguration = new GemFireHttpSessionConfiguration(); + this.gemfireConfiguration = new GemFireHttpSessionConfiguration(); } @Test public void setAndGetBeanClassLoader() { - assertThat(gemfireConfiguration.getBeanClassLoader()).isNull(); + assertThat(this.gemfireConfiguration.getBeanClassLoader()).isNull(); - gemfireConfiguration.setBeanClassLoader(Thread.currentThread().getContextClassLoader()); + this.gemfireConfiguration.setBeanClassLoader(Thread.currentThread().getContextClassLoader()); - assertThat(gemfireConfiguration.getBeanClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader()); + assertThat(this.gemfireConfiguration.getBeanClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader()); - gemfireConfiguration.setBeanClassLoader(null); + this.gemfireConfiguration.setBeanClassLoader(null); - assertThat(gemfireConfiguration.getBeanClassLoader()).isNull(); + assertThat(this.gemfireConfiguration.getBeanClassLoader()).isNull(); } @Test public void setAndGetClientRegionShortcut() { - assertThat(gemfireConfiguration.getClientRegionShortcut()).isEqualTo( + assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT); - gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY); + this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY); - assertThat(gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY); + assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY); - gemfireConfiguration.setClientRegionShortcut(null); + this.gemfireConfiguration.setClientRegionShortcut(null); - assertThat(gemfireConfiguration.getClientRegionShortcut()).isEqualTo( + assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_CLIENT_REGION_SHORTCUT); } @Test public void setAndGetIndexableSessionAttributes() { - assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo( + assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_INDEXABLE_SESSION_ATTRIBUTES); - gemfireConfiguration.setIndexableSessionAttributes(toArray("one", "two", "three")); + this.gemfireConfiguration.setIndexableSessionAttributes(toArray("one", "two", "three")); - assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three")); - assertThat(gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()) + assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three")); + assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()) .isEqualTo("'one', 'two', 'three'"); - gemfireConfiguration.setIndexableSessionAttributes(toArray("one")); + this.gemfireConfiguration.setIndexableSessionAttributes(toArray("one")); - assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one")); - assertThat(gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("'one'"); + assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one")); + assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("'one'"); - gemfireConfiguration.setIndexableSessionAttributes(null); + this.gemfireConfiguration.setIndexableSessionAttributes(null); - assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo( + assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_INDEXABLE_SESSION_ATTRIBUTES); - assertThat(gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("*"); + assertThat(this.gemfireConfiguration.getIndexableSessionAttributesAsGemFireIndexExpression()).isEqualTo("*"); } @Test public void setAndGetMaxInactiveIntervalInSeconds() { - assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo( + assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS); - gemfireConfiguration.setMaxInactiveIntervalInSeconds(300); + this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(300); - assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(300); + assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(300); - gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MAX_VALUE); + this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MAX_VALUE); - assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MAX_VALUE); + assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MAX_VALUE); - gemfireConfiguration.setMaxInactiveIntervalInSeconds(-1); + this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(-1); - assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(-1); + assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(-1); - gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MIN_VALUE); + this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(Integer.MIN_VALUE); - assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MIN_VALUE); + assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(Integer.MIN_VALUE); } @Test public void setAndGetServerRegionShortcut() { - assertThat(gemfireConfiguration.getServerRegionShortcut()).isEqualTo( + assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT); - gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PERSISTENT); + this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PERSISTENT); - assertThat(gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE_PERSISTENT); + assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE_PERSISTENT); - gemfireConfiguration.setServerRegionShortcut(null); + this.gemfireConfiguration.setServerRegionShortcut(null); - assertThat(gemfireConfiguration.getServerRegionShortcut()).isEqualTo( + assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_SERVER_REGION_SHORTCUT); } @Test public void setAndGetSpringSessionGemFireRegionName() { - assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( + assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); - gemfireConfiguration.setSpringSessionGemFireRegionName("test"); + this.gemfireConfiguration.setSpringSessionGemFireRegionName("test"); - assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("test"); + assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("test"); - gemfireConfiguration.setSpringSessionGemFireRegionName(" "); + this.gemfireConfiguration.setSpringSessionGemFireRegionName(" "); - assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( + assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); - gemfireConfiguration.setSpringSessionGemFireRegionName(""); + this.gemfireConfiguration.setSpringSessionGemFireRegionName(""); - assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( + assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); - gemfireConfiguration.setSpringSessionGemFireRegionName(null); + this.gemfireConfiguration.setSpringSessionGemFireRegionName(null); - assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( + assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo( GemFireHttpSessionConfiguration.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); } @@ -195,16 +195,16 @@ public class GemFireHttpSessionConfigurationTest { annotationAttributes.put("serverRegionShortcut", RegionShortcut.REPLICATE); annotationAttributes.put("regionName", "TEST"); - when(mockAnnotationMetadata.getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName()))) - .thenReturn(annotationAttributes); + given(mockAnnotationMetadata.getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName()))) + .willReturn(annotationAttributes); - gemfireConfiguration.setImportMetadata(mockAnnotationMetadata); + this.gemfireConfiguration.setImportMetadata(mockAnnotationMetadata); - assertThat(gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY); - assertThat(gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three")); - assertThat(gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(600); - assertThat(gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE); - assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("TEST"); + assertThat(this.gemfireConfiguration.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.CACHING_PROXY); + assertThat(this.gemfireConfiguration.getIndexableSessionAttributes()).isEqualTo(toArray("one", "two", "three")); + assertThat(this.gemfireConfiguration.getMaxInactiveIntervalInSeconds()).isEqualTo(600); + assertThat(this.gemfireConfiguration.getServerRegionShortcut()).isEqualTo(RegionShortcut.REPLICATE); + assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("TEST"); verify(mockAnnotationMetadata, times(1)).getAnnotationAttributes(eq(EnableGemFireHttpSession.class.getName())); } @@ -214,9 +214,9 @@ public class GemFireHttpSessionConfigurationTest { GemfireOperations mockGemfireOperations = mock(GemfireOperations.class, "testCreateAndInitializeSpringSessionRepositoryBean"); - gemfireConfiguration.setMaxInactiveIntervalInSeconds(120); + this.gemfireConfiguration.setMaxInactiveIntervalInSeconds(120); - GemFireOperationsSessionRepository sessionRepository = gemfireConfiguration.sessionRepository( + GemFireOperationsSessionRepository sessionRepository = this.gemfireConfiguration.sessionRepository( mockGemfireOperations); assertThat(sessionRepository).isNotNull(); @@ -228,15 +228,15 @@ public class GemFireHttpSessionConfigurationTest { @SuppressWarnings("unchecked") public void createAndInitializeSpringSessionGemFireRegionTemplate() { GemFireCache mockGemFireCache = mock(GemFireCache.class); - Region mockRegion = mock(Region.class); + Region mockRegion = mock(Region.class); - when(mockGemFireCache.getRegion(eq("Example"))).thenReturn(mockRegion); + given(mockGemFireCache.getRegion(eq("Example"))).willReturn(mockRegion); - gemfireConfiguration.setSpringSessionGemFireRegionName("Example"); + this.gemfireConfiguration.setSpringSessionGemFireRegionName("Example"); - GemfireTemplate template = gemfireConfiguration.sessionRegionTemplate(mockGemFireCache); + GemfireTemplate template = this.gemfireConfiguration.sessionRegionTemplate(mockGemFireCache); - assertThat(gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("Example"); + assertThat(this.gemfireConfiguration.getSpringSessionGemFireRegionName()).isEqualTo("Example"); assertThat(template).isNotNull(); assertThat(template.getRegion()).isSameAs(mockRegion); @@ -248,24 +248,24 @@ public class GemFireHttpSessionConfigurationTest { Cache mockCache = mock(Cache.class, "testExpirationIsAllowed.MockCache"); ClientCache mockClientCache = mock(ClientCache.class, "testExpirationIsAllowed.MockClientCache"); - gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY); - gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE); + this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY); + this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE); - assertThat(gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue(); + assertThat(this.gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue(); - gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW); + this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW); - assertThat(gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue(); + assertThat(this.gemfireConfiguration.isExpirationAllowed(mockCache)).isTrue(); - gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY); - gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY); + this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.CACHING_PROXY); + this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY); - assertThat(gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue(); + assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue(); - gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW); - gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PROXY); + this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT_OVERFLOW); + this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.REPLICATE_PROXY); - assertThat(gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue(); + assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isTrue(); } @Test @@ -273,15 +273,15 @@ public class GemFireHttpSessionConfigurationTest { Cache mockCache = mock(Cache.class, "testExpirationIsAllowed.MockCache"); ClientCache mockClientCache = mock(ClientCache.class, "testExpirationIsAllowed.MockClientCache"); - gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY); - gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION); + this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.PROXY); + this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION); - assertThat(gemfireConfiguration.isExpirationAllowed(mockClientCache)).isFalse(); + assertThat(this.gemfireConfiguration.isExpirationAllowed(mockClientCache)).isFalse(); - gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL); - gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY); + this.gemfireConfiguration.setClientRegionShortcut(ClientRegionShortcut.LOCAL); + this.gemfireConfiguration.setServerRegionShortcut(RegionShortcut.PARTITION_PROXY); - assertThat(gemfireConfiguration.isExpirationAllowed(mockCache)).isFalse(); + assertThat(this.gemfireConfiguration.isExpirationAllowed(mockCache)).isFalse(); } } diff --git a/spring-session/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBeanTest.java b/spring-session/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBeanTest.java index 144b4f4a..f617506a 100644 --- a/spring-session/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBeanTest.java +++ b/spring-session/src/test/java/org/springframework/session/data/gemfire/config/annotation/web/http/support/GemFireCacheTypeAwareRegionFactoryBeanTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,19 +16,6 @@ package org.springframework.session.data.gemfire.config.annotation.web.http.support; -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.runners.MockitoJUnitRunner; -import org.springframework.data.gemfire.client.Interest; -import org.springframework.session.ExpiringSession; - import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.GemFireCache; import com.gemstone.gemfire.cache.InterestResultPolicy; @@ -37,12 +24,26 @@ import com.gemstone.gemfire.cache.RegionAttributes; import com.gemstone.gemfire.cache.RegionShortcut; import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.ClientRegionShortcut; +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.runners.MockitoJUnitRunner; + +import org.springframework.data.gemfire.client.Interest; +import org.springframework.session.ExpiringSession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; /** * The GemFireCacheTypeAwareRegionFactoryBeanTest class is a test suite of test cases testing the contract * and functionality of the GemFireCacheTypeAwareRegionFactoryBean class. * * @author John Blum + * @since 1.1.0 * @see org.junit.Rule * @see org.junit.Test * @see org.mockito.Mockito @@ -55,7 +56,6 @@ import com.gemstone.gemfire.cache.client.ClientRegionShortcut; * @see com.gemstone.gemfire.cache.RegionShortcut * @see com.gemstone.gemfire.cache.client.ClientCache * @see com.gemstone.gemfire.cache.client.ClientRegionShortcut - * @since 1.1.0 */ @RunWith(MockitoJUnitRunner.class) public class GemFireCacheTypeAwareRegionFactoryBeanTest { @@ -64,66 +64,70 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { public ExpectedException expectedException = ExpectedException.none(); @Mock - Region mockClientRegion; + Region mockClientRegion; @Mock - Region mockServerRegion; + Region mockServerRegion; @Mock ClientCache mockClientCache; - private GemFireCacheTypeAwareRegionFactoryBean regionFactoryBean; + private GemFireCacheTypeAwareRegionFactoryBean regionFactoryBean; @Before public void setup() { - regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean(); + this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean(); } @Test public void afterPropertiesSetCreatesClientRegionForClientCache() throws Exception { - regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean() { - @Override protected Region newClientRegion(GemFireCache gemfireCache) throws Exception { - assertThat(gemfireCache).isSameAs(mockClientCache); - return mockClientRegion; + this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean() { + @Override + protected Region newClientRegion(GemFireCache gemfireCache) throws Exception { + assertThat(gemfireCache).isSameAs(GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache); + return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion; } - @Override protected Region newServerRegion(final GemFireCache gemfireCache) throws Exception { - assertThat(gemfireCache).isSameAs(mockClientCache); - return mockServerRegion; + @Override + protected Region newServerRegion(final GemFireCache gemfireCache) throws Exception { + assertThat(gemfireCache).isSameAs(GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache); + return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockServerRegion; } }; - regionFactoryBean.setGemfireCache(mockClientCache); - regionFactoryBean.afterPropertiesSet(); + this.regionFactoryBean.setGemfireCache(this.mockClientCache); + this.regionFactoryBean.afterPropertiesSet(); - assertThat(regionFactoryBean.getGemfireCache()).isSameAs(mockClientCache); - assertThat(regionFactoryBean.getObject()).isEqualTo(mockClientRegion); + assertThat(this.regionFactoryBean.getGemfireCache()).isSameAs(this.mockClientCache); + assertThat(this.regionFactoryBean.getObject()).isEqualTo(this.mockClientRegion); } @Test public void afterPropertiesSetCreatesServerRegionForPeerCache() throws Exception { final Cache mockCache = mock(Cache.class); - regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean() { - @Override protected Region newClientRegion(GemFireCache gemfireCache) throws Exception { + this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean() { + @Override + protected Region newClientRegion(GemFireCache gemfireCache) throws Exception { assertThat(gemfireCache).isSameAs(mockCache); - return mockClientRegion; + return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion; } - @Override protected Region newServerRegion(final GemFireCache gemfireCache) throws Exception { + @Override + protected Region newServerRegion(final GemFireCache gemfireCache) throws Exception { assertThat(gemfireCache).isSameAs(mockCache); - return mockServerRegion; + return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockServerRegion; } }; - regionFactoryBean.setGemfireCache(mockCache); - regionFactoryBean.afterPropertiesSet(); + this.regionFactoryBean.setGemfireCache(mockCache); + this.regionFactoryBean.afterPropertiesSet(); - assertThat(regionFactoryBean.getGemfireCache()).isSameAs(mockCache); - assertThat(regionFactoryBean.getObject()).isEqualTo(mockServerRegion); + assertThat(this.regionFactoryBean.getGemfireCache()).isSameAs(mockCache); + assertThat(this.regionFactoryBean.getObject()).isEqualTo(this.mockServerRegion); } @Test public void allKeysInterestRegistration() { - Interest[] interests = regionFactoryBean.registerInterests(true); + Interest[] interests = this.regionFactoryBean.registerInterests(true); assertThat(interests).isNotNull(); assertThat(interests.length).isEqualTo(1); @@ -135,7 +139,7 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test public void emptyInterestsRegistration() { - Interest[] interests = regionFactoryBean.registerInterests(false); + Interest[] interests = this.regionFactoryBean.registerInterests(false); assertThat(interests).isNotNull(); assertThat(interests.length).isEqualTo(0); @@ -143,26 +147,26 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { @Test public void getObjectTypeBeforeInitializationIsRegionClass() { - assertThat(regionFactoryBean.getObjectType()).isEqualTo(Region.class); + assertThat(this.regionFactoryBean.getObjectType()).isEqualTo(Region.class); } @Test public void isSingletonIsTrue() { - assertThat(regionFactoryBean.isSingleton()).isTrue(); + assertThat(this.regionFactoryBean.isSingleton()).isTrue(); } @Test public void setAndGetClientRegionShortcut() { - assertThat(regionFactoryBean.getClientRegionShortcut()).isEqualTo( + assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT); - regionFactoryBean.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT); + this.regionFactoryBean.setClientRegionShortcut(ClientRegionShortcut.LOCAL_PERSISTENT); - assertThat(regionFactoryBean.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.LOCAL_PERSISTENT); + assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo(ClientRegionShortcut.LOCAL_PERSISTENT); - regionFactoryBean.setClientRegionShortcut(null); + this.regionFactoryBean.setClientRegionShortcut(null); - assertThat(regionFactoryBean.getClientRegionShortcut()).isEqualTo( + assertThat(this.regionFactoryBean.getClientRegionShortcut()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_CLIENT_REGION_SHORTCUT); } @@ -170,78 +174,78 @@ public class GemFireCacheTypeAwareRegionFactoryBeanTest { public void setAndGetGemfireCache() { Cache mockCache = mock(Cache.class); - regionFactoryBean.setGemfireCache(mockCache); + this.regionFactoryBean.setGemfireCache(mockCache); - assertThat(regionFactoryBean.getGemfireCache()).isEqualTo(mockCache); + assertThat(this.regionFactoryBean.getGemfireCache()).isEqualTo(mockCache); } @Test public void setGemfireCacheToNullThrowsIllegalArgumentException() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The GemFireCache reference must not be null"); - regionFactoryBean.setGemfireCache(null); + this.expectedException.expect(IllegalArgumentException.class); + this.expectedException.expectMessage("The GemFireCache reference must not be null"); + this.regionFactoryBean.setGemfireCache(null); } @Test public void getGemfireCacheWhenNullThrowsIllegalStateException() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("A reference to a GemFireCache was not properly configured"); - regionFactoryBean.getGemfireCache(); + this.expectedException.expect(IllegalStateException.class); + this.expectedException.expectMessage("A reference to a GemFireCache was not properly configured"); + this.regionFactoryBean.getGemfireCache(); } @Test @SuppressWarnings("unchecked") public void setAndGetRegionAttributes() { - RegionAttributes mockRegionAttributes = mock(RegionAttributes.class); + RegionAttributes mockRegionAttributes = mock(RegionAttributes.class); - assertThat(regionFactoryBean.getRegionAttributes()).isNull(); + assertThat(this.regionFactoryBean.getRegionAttributes()).isNull(); - regionFactoryBean.setRegionAttributes(mockRegionAttributes); + this.regionFactoryBean.setRegionAttributes(mockRegionAttributes); - assertThat(regionFactoryBean.getRegionAttributes()).isSameAs(mockRegionAttributes); + assertThat(this.regionFactoryBean.getRegionAttributes()).isSameAs(mockRegionAttributes); - regionFactoryBean.setRegionAttributes(null); + this.regionFactoryBean.setRegionAttributes(null); - assertThat(regionFactoryBean.getRegionAttributes()).isNull(); + assertThat(this.regionFactoryBean.getRegionAttributes()).isNull(); } @Test public void setAndGetRegionName() { - assertThat(regionFactoryBean.getRegionName()).isEqualTo( + assertThat(this.regionFactoryBean.getRegionName()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); - regionFactoryBean.setRegionName("Example"); + this.regionFactoryBean.setRegionName("Example"); - assertThat(regionFactoryBean.getRegionName()).isEqualTo("Example"); + assertThat(this.regionFactoryBean.getRegionName()).isEqualTo("Example"); - regionFactoryBean.setRegionName(" "); + this.regionFactoryBean.setRegionName(" "); - assertThat(regionFactoryBean.getRegionName()).isEqualTo( + assertThat(this.regionFactoryBean.getRegionName()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); - regionFactoryBean.setRegionName(""); + this.regionFactoryBean.setRegionName(""); - assertThat(regionFactoryBean.getRegionName()).isEqualTo( + assertThat(this.regionFactoryBean.getRegionName()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); - regionFactoryBean.setRegionName(null); + this.regionFactoryBean.setRegionName(null); - assertThat(regionFactoryBean.getRegionName()).isEqualTo( + assertThat(this.regionFactoryBean.getRegionName()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SPRING_SESSION_GEMFIRE_REGION_NAME); } @Test public void setAndGetServerRegionShortcut() { - assertThat(regionFactoryBean.getServerRegionShortcut()).isEqualTo( + assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT); - regionFactoryBean.setServerRegionShortcut(RegionShortcut.LOCAL_PERSISTENT); + this.regionFactoryBean.setServerRegionShortcut(RegionShortcut.LOCAL_PERSISTENT); - assertThat(regionFactoryBean.getServerRegionShortcut()).isEqualTo(RegionShortcut.LOCAL_PERSISTENT); + assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo(RegionShortcut.LOCAL_PERSISTENT); - regionFactoryBean.setServerRegionShortcut(null); + this.regionFactoryBean.setServerRegionShortcut(null); - assertThat(regionFactoryBean.getServerRegionShortcut()).isEqualTo( + assertThat(this.regionFactoryBean.getServerRegionShortcut()).isEqualTo( GemFireCacheTypeAwareRegionFactoryBean.DEFAULT_SERVER_REGION_SHORTCUT); } diff --git a/spring-session/src/test/java/org/springframework/session/data/gemfire/support/GemFireUtilsTest.java b/spring-session/src/test/java/org/springframework/session/data/gemfire/support/GemFireUtilsTest.java index b993ecb2..e5d1aebc 100644 --- a/spring-session/src/test/java/org/springframework/session/data/gemfire/support/GemFireUtilsTest.java +++ b/spring-session/src/test/java/org/springframework/session/data/gemfire/support/GemFireUtilsTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,32 +16,31 @@ package org.springframework.session.data.gemfire.support; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.io.Closeable; import java.io.IOException; -import org.junit.Test; - import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.GemFireCache; import com.gemstone.gemfire.cache.RegionShortcut; import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.ClientRegionShortcut; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * The GemFireUtilsTest class is a test suite of test cases testing the contract and functionality of the GemFireUtils * utility class. * * @author John Blum + * @since 1.1.0 * @see org.junit.Test * @see org.mockito.Mockito * @see org.springframework.session.data.gemfire.support.GemFireUtils - * @since 1.1.0 */ public class GemFireUtilsTest { @@ -55,7 +54,7 @@ public class GemFireUtilsTest { @Test public void closeNonNullCloseableObjectThrowingIOExceptionReturnsFalse() throws IOException { Closeable mockCloseable = mock(Closeable.class); - doThrow(new IOException("test")).when(mockCloseable).close(); + willThrow(new IOException("test")).given(mockCloseable).close(); assertThat(GemFireUtils.close(mockCloseable)).isFalse(); verify(mockCloseable, times(1)).close(); } diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryTests.java index 2a2df369..d4a2790c 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,23 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; -import static org.springframework.session.data.redis.RedisOperationsSessionRepository.CREATION_TIME_ATTR; -import static org.springframework.session.data.redis.RedisOperationsSessionRepository.LAST_ACCESSED_ATTR; -import static org.springframework.session.data.redis.RedisOperationsSessionRepository.MAX_INACTIVE_ATTR; -import static org.springframework.session.data.redis.RedisOperationsSessionRepository.getSessionAttrNameKey; +package org.springframework.session.data.redis; import java.util.Arrays; import java.util.Collections; @@ -46,6 +31,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.redis.connection.DefaultMessage; import org.springframework.data.redis.connection.RedisConnection; @@ -68,9 +54,20 @@ import org.springframework.session.data.redis.RedisOperationsSessionRepository.P import org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession; import org.springframework.session.events.AbstractSessionEvent; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; @RunWith(MockitoJUnitRunner.class) -@SuppressWarnings({"unchecked","rawtypes"}) +@SuppressWarnings({"unchecked", "rawtypes"}) public class RedisOperationsSessionRepositoryTests { static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT"; @@ -79,7 +76,7 @@ public class RedisOperationsSessionRepositoryTests { @Mock RedisConnection connection; @Mock - RedisOperations redisOperations; + RedisOperations redisOperations; @Mock BoundValueOperations boundValueOperations; @Mock @@ -93,7 +90,7 @@ public class RedisOperationsSessionRepositoryTests { @Captor ArgumentCaptor event; @Captor - ArgumentCaptor> delta; + ArgumentCaptor> delta; private MapSession cached; @@ -102,166 +99,166 @@ public class RedisOperationsSessionRepositoryTests { @Before public void setup() { - this.redisRepository = new RedisOperationsSessionRepository(redisOperations); - this.redisRepository.setDefaultSerializer(defaultSerializer); + this.redisRepository = new RedisOperationsSessionRepository(this.redisOperations); + this.redisRepository.setDefaultSerializer(this.defaultSerializer); - cached = new MapSession(); - cached.setId("session-id"); - cached.setCreationTime(1404360000000L); - cached.setLastAccessedTime(1404360000000L); + this.cached = new MapSession(); + this.cached.setId("session-id"); + this.cached.setCreationTime(1404360000000L); + this.cached.setLastAccessedTime(1404360000000L); } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void constructorNullConnectionFactory() { - new RedisOperationsSessionRepository((RedisConnectionFactory)null); + new RedisOperationsSessionRepository((RedisConnectionFactory) null); } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void setApplicationEventPublisherNull() { - redisRepository.setApplicationEventPublisher(null); + this.redisRepository.setApplicationEventPublisher(null); } // gh-61 @Test public void constructorConnectionFactory() { - redisRepository = new RedisOperationsSessionRepository(factory); - RedisSession session = redisRepository.createSession(); + this.redisRepository = new RedisOperationsSessionRepository(this.factory); + RedisSession session = this.redisRepository.createSession(); - when(factory.getConnection()).thenReturn(connection); + given(this.factory.getConnection()).willReturn(this.connection); - redisRepository.save(session); + this.redisRepository.save(session); } @Test public void createSessionDefaultMaxInactiveInterval() throws Exception { - ExpiringSession session = redisRepository.createSession(); + ExpiringSession session = this.redisRepository.createSession(); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(new MapSession().getMaxInactiveIntervalInSeconds()); } @Test public void createSessionCustomMaxInactiveInterval() throws Exception { int interval = 1; - redisRepository.setDefaultMaxInactiveInterval(interval); - ExpiringSession session = redisRepository.createSession(); + this.redisRepository.setDefaultMaxInactiveInterval(interval); + ExpiringSession session = this.redisRepository.createSession(); assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(interval); } @Test public void saveNewSession() { - RedisSession session = redisRepository.createSession(); - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + RedisSession session = this.redisRepository.createSession(); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.save(session); + this.redisRepository.save(session); - Map delta = getDelta(); + Map delta = getDelta(); assertThat(delta.size()).isEqualTo(3); - Object creationTime = delta.get(CREATION_TIME_ATTR); + Object creationTime = delta.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR); assertThat(creationTime).isEqualTo(session.getCreationTime()); - assertThat(delta.get(MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); - assertThat(delta.get(LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime()); + assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); + assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime()); } @Test public void saveJavadocSummary() { - RedisSession session = redisRepository.createSession(); + RedisSession session = this.redisRepository.createSession(); String sessionKey = "spring:session:sessions:" + session.getId(); String backgroundExpireKey = "spring:session:expirations:" + RedisSessionExpirationPolicy.roundUpToNextMinute(RedisSessionExpirationPolicy.expiresInMillis(session)); String destroyedTriggerKey = "spring:session:sessions:expires:" + session.getId(); - when(redisOperations.boundHashOps(sessionKey)).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(backgroundExpireKey)).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(destroyedTriggerKey)).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(sessionKey)).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(backgroundExpireKey)).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(destroyedTriggerKey)).willReturn(this.boundValueOperations); - redisRepository.save(session); + this.redisRepository.save(session); // the actual data in the session expires 5 minutes after expiration so the data can be accessed in expiration events // if the session is retrieved and expired it will not be returned since getSession checks if it is expired long fiveMinutesAfterExpires = session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5); - verify(boundHashOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); - verify(boundSetOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); - verify(boundSetOperations).add("expires:" + session.getId()); - verify(boundValueOperations).expire(1800L, TimeUnit.SECONDS); - verify(boundValueOperations).append(""); + verify(this.boundHashOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); + verify(this.boundSetOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); + verify(this.boundSetOperations).add("expires:" + session.getId()); + verify(this.boundValueOperations).expire(1800L, TimeUnit.SECONDS); + verify(this.boundValueOperations).append(""); } @Test public void saveJavadoc() { - RedisSession session = redisRepository.new RedisSession(cached); + RedisSession session = this.redisRepository.new RedisSession(this.cached); - when(redisOperations.boundHashOps("spring:session:sessions:session-id")).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps("spring:session:expirations:1404361860000")).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps("spring:session:sessions:expires:session-id")).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps("spring:session:sessions:session-id")).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps("spring:session:expirations:1404361860000")).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps("spring:session:sessions:expires:session-id")).willReturn(this.boundValueOperations); - redisRepository.save(session); + this.redisRepository.save(session); // the actual data in the session expires 5 minutes after expiration so the data can be accessed in expiration events // if the session is retrieved and expired it will not be returned since getSession checks if it is expired - verify(boundHashOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS); + verify(this.boundHashOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS); } @Test public void saveLastAccessChanged() { - RedisSession session = redisRepository.new RedisSession(new MapSession(cached)); + RedisSession session = this.redisRepository.new RedisSession(new MapSession(this.cached)); session.setLastAccessedTime(12345678L); - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.save(session); + this.redisRepository.save(session); - assertThat(getDelta()).isEqualTo(map(LAST_ACCESSED_ATTR, session.getLastAccessedTime())); + assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, session.getLastAccessedTime())); } @Test public void saveSetAttribute() { String attrName = "attrName"; - RedisSession session = redisRepository.new RedisSession(new MapSession()); + RedisSession session = this.redisRepository.new RedisSession(new MapSession()); session.setAttribute(attrName, "attrValue"); - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.save(session); + this.redisRepository.save(session); - assertThat(getDelta()).isEqualTo(map(getSessionAttrNameKey(attrName), session.getAttribute(attrName))); + assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName))); } @Test public void saveRemoveAttribute() { String attrName = "attrName"; - RedisSession session = redisRepository.new RedisSession(new MapSession()); + RedisSession session = this.redisRepository.new RedisSession(new MapSession()); session.removeAttribute(attrName); - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.save(session); + this.redisRepository.save(session); - assertThat(getDelta()).isEqualTo(map(getSessionAttrNameKey(attrName), null)); + assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null)); } @Test public void saveExpired() { - RedisSession session = redisRepository.new RedisSession(new MapSession()); + RedisSession session = this.redisRepository.new RedisSession(new MapSession()); session.setMaxInactiveIntervalInSeconds(0); - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.save(session); + this.redisRepository.save(session); String id = session.getId(); - verify(redisOperations,atLeastOnce()).delete(getKey("expires:"+id)); - verify(redisOperations,never()).boundValueOps(getKey("expires:"+id)); + verify(this.redisOperations, atLeastOnce()).delete(getKey("expires:" + id)); + verify(this.redisOperations, never()).boundValueOps(getKey("expires:" + id)); } @Test public void redisSessionGetAttributes() { String attrName = "attrName"; - RedisSession session = redisRepository.new RedisSession(); + RedisSession session = this.redisRepository.new RedisSession(); assertThat(session.getAttributeNames()).isEmpty(); session.setAttribute(attrName, "attrValue"); assertThat(session.getAttributeNames()).containsOnly(attrName); @@ -275,44 +272,44 @@ public class RedisOperationsSessionRepositoryTests { MapSession expected = new MapSession(); expected.setLastAccessedTime(System.currentTimeMillis() - 60000); expected.setAttribute(attrName, "attrValue"); - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); Map map = map( - getSessionAttrNameKey(attrName), expected.getAttribute(attrName), - CREATION_TIME_ATTR, expected.getCreationTime(), - MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(), - LAST_ACCESSED_ATTR, expected.getLastAccessedTime()); - when(boundHashOperations.entries()).thenReturn(map); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); + RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName), + RedisOperationsSessionRepository.CREATION_TIME_ATTR, expected.getCreationTime(), + RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(), + RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, expected.getLastAccessedTime()); + given(this.boundHashOperations.entries()).willReturn(map); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); String id = expected.getId(); - redisRepository.delete(id); + this.redisRepository.delete(id); - assertThat(getDelta().get(MAX_INACTIVE_ATTR)).isEqualTo(0); - verify(redisOperations,atLeastOnce()).delete(getKey("expires:"+id)); - verify(redisOperations,never()).boundValueOps(getKey("expires:"+id)); + assertThat(getDelta().get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(0); + verify(this.redisOperations, atLeastOnce()).delete(getKey("expires:" + id)); + verify(this.redisOperations, never()).boundValueOps(getKey("expires:" + id)); } @Test public void deleteNullSession() { - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); String id = "abc"; - redisRepository.delete(id); - verify(redisOperations,times(0)).delete(anyString()); - verify(redisOperations,times(0)).delete(anyString()); + this.redisRepository.delete(id); + verify(this.redisOperations, times(0)).delete(anyString()); + verify(this.redisOperations, times(0)).delete(anyString()); } @Test public void getSessionNotFound() { String id = "abc"; - when(redisOperations.boundHashOps(getKey(id))).thenReturn(boundHashOperations); - when(boundHashOperations.entries()).thenReturn(map()); + given(this.redisOperations.boundHashOps(getKey(id))).willReturn(this.boundHashOperations); + given(this.boundHashOperations.entries()).willReturn(map()); - assertThat(redisRepository.getSession(id)).isNull(); + assertThat(this.redisRepository.getSession(id)).isNull(); } @Test @@ -321,15 +318,15 @@ public class RedisOperationsSessionRepositoryTests { MapSession expected = new MapSession(); expected.setLastAccessedTime(System.currentTimeMillis() - 60000); expected.setAttribute(attrName, "attrValue"); - when(redisOperations.boundHashOps(getKey(expected.getId()))).thenReturn(boundHashOperations); + given(this.redisOperations.boundHashOps(getKey(expected.getId()))).willReturn(this.boundHashOperations); Map map = map( - getSessionAttrNameKey(attrName), expected.getAttribute(attrName), - CREATION_TIME_ATTR, expected.getCreationTime(), - MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(), - LAST_ACCESSED_ATTR, expected.getLastAccessedTime()); - when(boundHashOperations.entries()).thenReturn(map); + RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName), + RedisOperationsSessionRepository.CREATION_TIME_ATTR, expected.getCreationTime(), + RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, expected.getMaxInactiveIntervalInSeconds(), + RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, expected.getLastAccessedTime()); + given(this.boundHashOperations.entries()).willReturn(map); - RedisSession session = redisRepository.getSession(expected.getId()); + RedisSession session = this.redisRepository.getSession(expected.getId()); assertThat(session.getId()).isEqualTo(expected.getId()); assertThat(session.getAttributeNames()).isEqualTo(expected.getAttributeNames()); assertThat(session.getAttribute(attrName)).isEqualTo(expected.getAttribute(attrName)); @@ -342,27 +339,27 @@ public class RedisOperationsSessionRepositoryTests { @Test public void getSessionExpired() { String expiredId = "expired-id"; - when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations); + given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations); Map map = map( - MAX_INACTIVE_ATTR, 1, - LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)); - when(boundHashOperations.entries()).thenReturn(map); + RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1, + RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)); + given(this.boundHashOperations.entries()).willReturn(map); - assertThat(redisRepository.getSession(expiredId)).isNull(); + assertThat(this.redisRepository.getSession(expiredId)).isNull(); } @Test public void findByPrincipalNameExpired() { String expiredId = "expired-id"; - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(boundSetOperations.members()).thenReturn(Collections.singleton(expiredId)); - when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.boundSetOperations.members()).willReturn(Collections.singleton(expiredId)); + given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations); Map map = map( - MAX_INACTIVE_ATTR, 1, - LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)); - when(boundHashOperations.entries()).thenReturn(map); + RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, 1, + RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)); + given(this.boundHashOperations.entries()).willReturn(map); - assertThat(redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal")).isEmpty(); + assertThat(this.redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal")).isEmpty(); } @Test @@ -371,16 +368,16 @@ public class RedisOperationsSessionRepositoryTests { long createdTime = lastAccessed - 10; int maxInactive = 3600; String sessionId = "some-id"; - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(boundSetOperations.members()).thenReturn(Collections.singleton(sessionId)); - when(redisOperations.boundHashOps(getKey(sessionId))).thenReturn(boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.boundSetOperations.members()).willReturn(Collections.singleton(sessionId)); + given(this.redisOperations.boundHashOps(getKey(sessionId))).willReturn(this.boundHashOperations); Map map = map( - CREATION_TIME_ATTR, createdTime, - MAX_INACTIVE_ATTR, maxInactive, - LAST_ACCESSED_ATTR, lastAccessed); - when(boundHashOperations.entries()).thenReturn(map); + RedisOperationsSessionRepository.CREATION_TIME_ATTR, createdTime, + RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, maxInactive, + RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, lastAccessed); + given(this.boundHashOperations.entries()).willReturn(map); - Map sessionIdToSessions = redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"); + Map sessionIdToSessions = this.redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"); assertThat(sessionIdToSessions).hasSize(1); RedisSession session = sessionIdToSessions.get(sessionId); @@ -394,62 +391,62 @@ public class RedisOperationsSessionRepositoryTests { @Test public void cleanupExpiredSessions() { String expiredId = "expired-id"; - when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); + given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); - Set expiredIds = new HashSet(Arrays.asList("expired-key1","expired-key2")); - when(boundSetOperations.members()).thenReturn(expiredIds); + Set expiredIds = new HashSet(Arrays.asList("expired-key1", "expired-key2")); + given(this.boundSetOperations.members()).willReturn(expiredIds); - redisRepository.cleanupExpiredSessions(); + this.redisRepository.cleanupExpiredSessions(); - for(Object id : expiredIds) { + for (Object id : expiredIds) { String expiredKey = "spring:session:sessions:" + id; // https://github.com/spring-projects/spring-session/issues/93 - verify(redisOperations).hasKey(expiredKey); + verify(this.redisOperations).hasKey(expiredKey); } } @Test public void onMessageCreated() throws Exception { - MapSession session = cached; + MapSession session = this.cached; byte[] pattern = "".getBytes("UTF-8"); String channel = "spring:session:event:created:" + session.getId(); JdkSerializationRedisSerializer defaultSerailizer = new JdkSerializationRedisSerializer(); - redisRepository.setDefaultSerializer(defaultSerailizer); + this.redisRepository.setDefaultSerializer(defaultSerailizer); byte[] body = defaultSerailizer.serialize(new HashMap()); DefaultMessage message = new DefaultMessage(channel.getBytes("UTF-8"), body); - redisRepository.setApplicationEventPublisher(publisher); + this.redisRepository.setApplicationEventPublisher(this.publisher); - redisRepository.onMessage(message, pattern); + this.redisRepository.onMessage(message, pattern); - verify(publisher).publishEvent(event.capture()); - assertThat(event.getValue().getSessionId()).isEqualTo(session.getId()); + verify(this.publisher).publishEvent(this.event.capture()); + assertThat(this.event.getValue().getSessionId()).isEqualTo(session.getId()); } // gh-309 @Test public void onMessageCreatedCustomSerializer() throws Exception { - MapSession session = cached; + MapSession session = this.cached; byte[] pattern = "".getBytes("UTF-8"); byte[] body = new byte[0]; String channel = "spring:session:event:created:" + session.getId(); - when(defaultSerializer.deserialize(body)).thenReturn(new HashMap()); + given(this.defaultSerializer.deserialize(body)).willReturn(new HashMap()); DefaultMessage message = new DefaultMessage(channel.getBytes("UTF-8"), body); - redisRepository.setApplicationEventPublisher(publisher); + this.redisRepository.setApplicationEventPublisher(this.publisher); - redisRepository.onMessage(message, pattern); + this.redisRepository.onMessage(message, pattern); - verify(publisher).publishEvent(event.capture()); - assertThat(event.getValue().getSessionId()).isEqualTo(session.getId()); - verify(defaultSerializer).deserialize(body); + verify(this.publisher).publishEvent(this.event.capture()); + assertThat(this.event.getValue().getSessionId()).isEqualTo(session.getId()); + verify(this.defaultSerializer).deserialize(body); } @Test public void resolvePrincipalIndex() { PrincipalNameResolver resolver = RedisOperationsSessionRepository.PRINCIPAL_NAME_RESOLVER; String username = "username"; - RedisSession session = redisRepository.createSession(); + RedisSession session = this.redisRepository.createSession(); session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); assertThat(resolver.resolvePrincipal(session)).isEqualTo(username); @@ -464,7 +461,7 @@ public class RedisOperationsSessionRepositoryTests { PrincipalNameResolver resolver = RedisOperationsSessionRepository.PRINCIPAL_NAME_RESOLVER; - RedisSession session = redisRepository.createSession(); + RedisSession session = this.redisRepository.createSession(); session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, context); assertThat(resolver.resolvePrincipal(session)).isEqualTo(principal); @@ -472,128 +469,128 @@ public class RedisOperationsSessionRepositoryTests { @Test public void flushModeOnSaveCreate() { - redisRepository.createSession(); + this.redisRepository.createSession(); - verifyZeroInteractions(boundHashOperations); + verifyZeroInteractions(this.boundHashOperations); } @Test public void flushModeOnSaveSetAttribute() { - RedisSession session = redisRepository.createSession(); + RedisSession session = this.redisRepository.createSession(); session.setAttribute("something", "here"); - verifyZeroInteractions(boundHashOperations); + verifyZeroInteractions(this.boundHashOperations); } @Test public void flushModeOnSaveRemoveAttribute() { - RedisSession session = redisRepository.createSession(); + RedisSession session = this.redisRepository.createSession(); session.removeAttribute("remove"); - verifyZeroInteractions(boundHashOperations); + verifyZeroInteractions(this.boundHashOperations); } @Test public void flushModeOnSaveSetLastAccessedTime() { - RedisSession session = redisRepository.createSession(); + RedisSession session = this.redisRepository.createSession(); session.setLastAccessedTime(1L); - verifyZeroInteractions(boundHashOperations); + verifyZeroInteractions(this.boundHashOperations); } @Test public void flushModeOnSaveSetMaxInactiveIntervalInSeconds() { - RedisSession session = redisRepository.createSession(); + RedisSession session = this.redisRepository.createSession(); session.setMaxInactiveIntervalInSeconds(1); - verifyZeroInteractions(boundHashOperations); + verifyZeroInteractions(this.boundHashOperations); } @Test public void flushModeImmediateCreate() { - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); - RedisSession session = redisRepository.createSession(); + this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); + RedisSession session = this.redisRepository.createSession(); Map delta = getDelta(); assertThat(delta.size()).isEqualTo(3); - Object creationTime = delta.get(CREATION_TIME_ATTR); + Object creationTime = delta.get(RedisOperationsSessionRepository.CREATION_TIME_ATTR); assertThat(creationTime).isEqualTo(session.getCreationTime()); - assertThat(delta.get(MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); - assertThat(delta.get(LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime()); + assertThat(delta.get(RedisOperationsSessionRepository.MAX_INACTIVE_ATTR)).isEqualTo(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); + assertThat(delta.get(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR)).isEqualTo(session.getCreationTime()); } @Test public void flushModeImmediateSetAttribute() { - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); - RedisSession session = redisRepository.createSession(); + this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); + RedisSession session = this.redisRepository.createSession(); String attrName = "someAttribute"; session.setAttribute(attrName, "someValue"); Map delta = getDelta(2); assertThat(delta.size()).isEqualTo(1); - assertThat(delta).isEqualTo(map(getSessionAttrNameKey(attrName), session.getAttribute(attrName))); + assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName))); } @Test public void flushModeImmediateRemoveAttribute() { - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); - RedisSession session = redisRepository.createSession(); + this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); + RedisSession session = this.redisRepository.createSession(); String attrName = "someAttribute"; session.removeAttribute(attrName); Map delta = getDelta(2); assertThat(delta.size()).isEqualTo(1); - assertThat(delta).isEqualTo(map(getSessionAttrNameKey(attrName), session.getAttribute(attrName))); + assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName))); } @Test public void flushModeSetMaxInactiveIntervalInSeconds() { - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); - RedisSession session = redisRepository.createSession(); + this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); + RedisSession session = this.redisRepository.createSession(); - reset(boundHashOperations); + reset(this.boundHashOperations); session.setMaxInactiveIntervalInSeconds(1); - verify(boundHashOperations).expire(anyLong(), any(TimeUnit.class)); + verify(this.boundHashOperations).expire(anyLong(), any(TimeUnit.class)); } @Test public void flushModeSetLastAccessedTime() { - when(redisOperations.boundHashOps(anyString())).thenReturn(boundHashOperations); - when(redisOperations.boundSetOps(anyString())).thenReturn(boundSetOperations); - when(redisOperations.boundValueOps(anyString())).thenReturn(boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); - redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); - RedisSession session = redisRepository.createSession(); + this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); + RedisSession session = this.redisRepository.createSession(); long now = System.currentTimeMillis(); session.setLastAccessedTime(now); Map delta = getDelta(2); assertThat(delta.size()).isEqualTo(1); - assertThat(delta).isEqualTo(map(LAST_ACCESSED_ATTR, session.getLastAccessedTime())); + assertThat(delta).isEqualTo(map(RedisOperationsSessionRepository.LAST_ACCESSED_ATTR, session.getLastAccessedTime())); } @Test(expected = IllegalArgumentException.class) public void setRedisFlushModeNull() { - redisRepository.setRedisFlushMode(null); + this.redisRepository.setRedisFlushMode(null); } private String getKey(String id) { @@ -601,22 +598,22 @@ public class RedisOperationsSessionRepositoryTests { } private Map map(Object...objects) { - Map result = new HashMap(); - if(objects == null) { + Map result = new HashMap(); + if (objects == null) { return result; } - for(int i = 0; i < objects.length; i += 2) { - result.put((String)objects[i], objects[i+1]); + for (int i = 0; i < objects.length; i += 2) { + result.put((String) objects[i], objects[i + 1]); } return result; } - private Map getDelta() { + private Map getDelta() { return getDelta(1); } - private Map getDelta(int times) { - verify(boundHashOperations,times(times)).putAll(delta.capture()); - return delta.getAllValues().get(times - 1); + private Map getDelta(int times) { + verify(this.boundHashOperations, times(times)).putAll(this.delta.capture()); + return this.delta.getAllValues().get(times - 1); } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/RedisSessionExpirationPolicyTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/RedisSessionExpirationPolicyTests.java index 0912cd72..4b30eaaf 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/RedisSessionExpirationPolicyTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/RedisSessionExpirationPolicyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis; -import static org.mockito.Mockito.*; +package org.springframework.session.data.redis; import java.util.concurrent.TimeUnit; @@ -24,12 +23,18 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.data.redis.core.BoundHashOperations; import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.data.redis.core.BoundValueOperations; import org.springframework.data.redis.core.RedisOperations; import org.springframework.session.MapSession; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + /** * @author Rob Winch */ @@ -42,11 +47,11 @@ public class RedisSessionExpirationPolicyTests { final static Long ONE_MINUTE_AGO = 1429111652346L; @Mock - RedisOperations sessionRedisOperations; + RedisOperations sessionRedisOperations; @Mock - BoundSetOperations setOperations; + BoundSetOperations setOperations; @Mock - BoundHashOperations hashOperations; + BoundHashOperations hashOperations; @Mock BoundValueOperations valueOperations; @@ -56,15 +61,15 @@ public class RedisSessionExpirationPolicyTests { @Before public void setup() { - RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(sessionRedisOperations); - policy = new RedisSessionExpirationPolicy(sessionRedisOperations, repository); - session = new MapSession(); - session.setLastAccessedTime(1429116694675L); - session.setId("12345"); + RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(this.sessionRedisOperations); + this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations, repository); + this.session = new MapSession(); + this.session.setLastAccessedTime(1429116694675L); + this.session.setId("12345"); - when(sessionRedisOperations.boundSetOps(anyString())).thenReturn(setOperations); - when(sessionRedisOperations.boundHashOps(anyString())).thenReturn(hashOperations); - when(sessionRedisOperations.boundValueOps(anyString())).thenReturn(valueOperations); + given(this.sessionRedisOperations.boundSetOps(anyString())).willReturn(this.setOperations); + given(this.sessionRedisOperations.boundHashOps(anyString())).willReturn(this.hashOperations); + given(this.sessionRedisOperations.boundValueOps(anyString())).willReturn(this.valueOperations); } // gh-169 @@ -72,48 +77,48 @@ public class RedisSessionExpirationPolicyTests { public void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp() throws Exception { long originalExpirationTimeInMs = ONE_MINUTE_AGO; long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(originalExpirationTimeInMs); - String originalExpireKey = policy.getExpirationKey(originalRoundedToNextMinInMs); + String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs); - policy.onExpirationUpdated(originalExpirationTimeInMs, session); + this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session); // verify the original is removed - verify(sessionRedisOperations).boundSetOps(originalExpireKey); - verify(setOperations).remove("expires:"+ session.getId()); + verify(this.sessionRedisOperations).boundSetOps(originalExpireKey); + verify(this.setOperations).remove("expires:" + this.session.getId()); } @Test public void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange() throws Exception { - long originalExpirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(session) - 10; + long originalExpirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session) - 10; long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(originalExpirationTimeInMs); - String originalExpireKey = policy.getExpirationKey(originalRoundedToNextMinInMs); + String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs); - policy.onExpirationUpdated(originalExpirationTimeInMs, session); + this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session); // verify the original is not removed - verify(sessionRedisOperations).boundSetOps(originalExpireKey); - verify(setOperations, never()).remove("expires:"+ session.getId()); + verify(this.sessionRedisOperations).boundSetOps(originalExpireKey); + verify(this.setOperations, never()).remove("expires:" + this.session.getId()); } @Test public void onExpirationUpdatedAddsExpirationTimeRoundedUp() throws Exception { - long expirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(session); + long expirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session); long expirationRoundedUpInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(expirationTimeInMs); - String expectedExpireKey = policy.getExpirationKey(expirationRoundedUpInMs); + String expectedExpireKey = this.policy.getExpirationKey(expirationRoundedUpInMs); - policy.onExpirationUpdated(null, session); + this.policy.onExpirationUpdated(null, this.session); - verify(sessionRedisOperations).boundSetOps(expectedExpireKey); - verify(setOperations).add("expires:" + session.getId()); - verify(setOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS); + verify(this.sessionRedisOperations).boundSetOps(expectedExpireKey); + verify(this.setOperations).add("expires:" + this.session.getId()); + verify(this.setOperations).expire(this.session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS); } @Test public void onExpirationUpdatedSetExpireSession() throws Exception { - String sessionKey = policy.getSessionKey(session.getId()); + String sessionKey = this.policy.getSessionKey(this.session.getId()); - policy.onExpirationUpdated(null, session); + this.policy.onExpirationUpdated(null, this.session); - verify(sessionRedisOperations).boundHashOps(sessionKey); - verify(hashOperations).expire(session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS); + verify(this.sessionRedisOperations).boundHashOps(sessionKey); + verify(this.hashOperations).expire(this.session.getMaxInactiveIntervalInSeconds() + TimeUnit.MINUTES.toSeconds(5), TimeUnit.SECONDS); } } diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/SessionMessageListenerTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/SessionMessageListenerTests.java index 43732cbf..358fbdcd 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/SessionMessageListenerTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/SessionMessageListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.*; +package org.springframework.session.data.redis; import java.io.UnsupportedEncodingException; @@ -27,12 +25,19 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.redis.connection.Message; import org.springframework.session.events.SessionDestroyedEvent; import org.springframework.session.events.SessionExpiredEvent; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; /** * @@ -61,7 +66,7 @@ public class SessionMessageListenerTests { @Before public void setup() { - listener = new SessionMessageListener(eventPublisher); + this.listener = new SessionMessageListener(this.eventPublisher); } @Test(expected = IllegalArgumentException.class) @@ -71,91 +76,91 @@ public class SessionMessageListenerTests { @Test public void onMessageNullBody() throws Exception { - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verifyZeroInteractions(eventPublisher); + verifyZeroInteractions(this.eventPublisher); } @Test public void onMessageDel() throws Exception { mockMessage("__keyevent@0__:del", "spring:session:sessions:123"); - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verify(eventPublisher).publishEvent(deletedEvent.capture()); - assertThat(deletedEvent.getValue().getSessionId()).isEqualTo("123"); + verify(this.eventPublisher).publishEvent(this.deletedEvent.capture()); + assertThat(this.deletedEvent.getValue().getSessionId()).isEqualTo("123"); } @Test public void onMessageDelSource() throws Exception { - mockMessage("__keyevent@0__:del","spring:session:sessions:123"); + mockMessage("__keyevent@0__:del", "spring:session:sessions:123"); - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verify(eventPublisher).publishEvent(deletedEvent.capture()); - assertThat(deletedEvent.getValue().getSource()).isEqualTo(listener); + verify(this.eventPublisher).publishEvent(this.deletedEvent.capture()); + assertThat(this.deletedEvent.getValue().getSource()).isEqualTo(this.listener); } @Test public void onMessageExpiredSource() throws Exception { - mockMessage("__keyevent@0__:expired","spring:session:sessions:123"); + mockMessage("__keyevent@0__:expired", "spring:session:sessions:123"); - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verify(eventPublisher).publishEvent(expiredEvent.capture()); - assertThat(expiredEvent.getValue().getSource()).isEqualTo(listener); + verify(this.eventPublisher).publishEvent(this.expiredEvent.capture()); + assertThat(this.expiredEvent.getValue().getSource()).isEqualTo(this.listener); } @Test public void onMessageExpired() throws Exception { - mockMessage("__keyevent@0__:expired","spring:session:sessions:543"); + mockMessage("__keyevent@0__:expired", "spring:session:sessions:543"); - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verify(eventPublisher).publishEvent(expiredEvent.capture()); - assertThat(expiredEvent.getValue().getSessionId()).isEqualTo("543"); + verify(this.eventPublisher).publishEvent(this.expiredEvent.capture()); + assertThat(this.expiredEvent.getValue().getSessionId()).isEqualTo("543"); } @Test public void onMessageHset() throws Exception { - mockMessage("__keyevent@0__:hset","spring:session:sessions:123"); + mockMessage("__keyevent@0__:hset", "spring:session:sessions:123"); - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verifyZeroInteractions(eventPublisher); + verifyZeroInteractions(this.eventPublisher); } @Test public void onMessageWrongKeyPrefix() throws Exception { - mockMessage("__keyevent@0__:del","spring:session:sessionsNo:123"); + mockMessage("__keyevent@0__:del", "spring:session:sessionsNo:123"); - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verifyZeroInteractions(eventPublisher); + verifyZeroInteractions(this.eventPublisher); } @Test public void onMessageRename() throws Exception { - mockMessage("__keyevent@0__:rename","spring:session:sessions:123"); + mockMessage("__keyevent@0__:rename", "spring:session:sessions:123"); - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verifyZeroInteractions(eventPublisher); + verifyZeroInteractions(this.eventPublisher); } @Test public void onMessageEventPublisherErrorCaught() throws Exception { - mockMessage("__keyevent@0__:del","spring:session:sessions:123"); - doThrow(new IllegalStateException("Test Exceptions are caught")).when(eventPublisher).publishEvent(any(ApplicationEvent.class)); + mockMessage("__keyevent@0__:del", "spring:session:sessions:123"); + willThrow(new IllegalStateException("Test Exceptions are caught")).given(this.eventPublisher).publishEvent(any(ApplicationEvent.class)); - listener.onMessage(message, pattern); + this.listener.onMessage(this.message, this.pattern); - verify(eventPublisher).publishEvent(any(ApplicationEvent.class)); + verify(this.eventPublisher).publishEvent(any(ApplicationEvent.class)); } private void mockMessage(String channel, String body) throws UnsupportedEncodingException { - when(message.getBody()).thenReturn(bytes(body)); - when(message.getChannel()).thenReturn(bytes(channel)); + given(this.message.getBody()).willReturn(bytes(body)); + given(this.message.getChannel()).willReturn(bytes(channel)); } private static byte[] bytes(String s) throws UnsupportedEncodingException { diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisKeyspaceNotificationsInitializerTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisKeyspaceNotificationsInitializerTests.java index 6fbfaff2..16827249 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisKeyspaceNotificationsInitializerTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisKeyspaceNotificationsInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis.config.annotation.web.http; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; -import static org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration.*; +import java.util.Arrays; import org.junit.Before; import org.junit.Test; @@ -28,11 +25,17 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.session.data.redis.config.ConfigureNotifyKeyspaceEventsAction; -import java.util.Arrays; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class EnableRedisKeyspaceNotificationsInitializerTests { @@ -45,29 +48,29 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { @Captor ArgumentCaptor options; - EnableRedisKeyspaceNotificationsInitializer initializer; + RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer initializer; @Before public void setup() { - when(connectionFactory.getConnection()).thenReturn(connection); + given(this.connectionFactory.getConnection()).willReturn(this.connection); - initializer = new EnableRedisKeyspaceNotificationsInitializer(connectionFactory, new ConfigureNotifyKeyspaceEventsAction()); + this.initializer = new RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer(this.connectionFactory, new ConfigureNotifyKeyspaceEventsAction()); } @Test public void afterPropertiesSetUnset() throws Exception { setConfigNotification(""); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); - assertOptionsContains("E","g","x"); + assertOptionsContains("E", "g", "x"); } @Test public void afterPropertiesSetA() throws Exception { setConfigNotification("A"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); assertOptionsContains("A", "E"); } @@ -76,7 +79,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { public void afterPropertiesSetE() throws Exception { setConfigNotification("E"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); assertOptionsContains("E", "g", "x"); } @@ -85,7 +88,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { public void afterPropertiesSetK() throws Exception { setConfigNotification("K"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); assertOptionsContains("K", "E", "g", "x"); } @@ -94,16 +97,16 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { public void afterPropertiesSetAE() throws Exception { setConfigNotification("AE"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); - verify(connection, never()).setConfig(anyString(), anyString()); + verify(this.connection, never()).setConfig(anyString(), anyString()); } @Test public void afterPropertiesSetAK() throws Exception { setConfigNotification("AK"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); assertOptionsContains("A", "K", "E"); } @@ -112,7 +115,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { public void afterPropertiesSetEK() throws Exception { setConfigNotification("EK"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); assertOptionsContains("E", "K", "g", "x"); } @@ -121,7 +124,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { public void afterPropertiesSetEg() throws Exception { setConfigNotification("Eg"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); assertOptionsContains("E", "g", "x"); } @@ -130,7 +133,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { public void afterPropertiesSetE$() throws Exception { setConfigNotification("E$"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); assertOptionsContains("E", "$", "g", "x"); } @@ -139,7 +142,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { public void afterPropertiesSetKg() throws Exception { setConfigNotification("Kg"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); assertOptionsContains("K", "g", "E", "x"); } @@ -148,20 +151,20 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { public void afterPropertiesSetAEK() throws Exception { setConfigNotification("AEK"); - initializer.afterPropertiesSet(); + this.initializer.afterPropertiesSet(); - verify(connection, never()).setConfig(anyString(), anyString()); + verify(this.connection, never()).setConfig(anyString(), anyString()); } private void assertOptionsContains(String... expectedValues) { - verify(connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), options.capture()); - for(String expectedValue : expectedValues) { - assertThat(options.getValue()).contains(expectedValue); + verify(this.connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), this.options.capture()); + for (String expectedValue : expectedValues) { + assertThat(this.options.getValue()).contains(expectedValue); } - assertThat(options.getValue().length()).isEqualTo(expectedValues.length); + assertThat(this.options.getValue().length()).isEqualTo(expectedValues.length); } private void setConfigNotification(String value) { - when(connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)).thenReturn(Arrays.asList(CONFIG_NOTIFY_KEYSPACE_EVENTS, value)); + given(this.connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)).willReturn(Arrays.asList(CONFIG_NOTIFY_KEYSPACE_EVENTS, value)); } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationClassPathXmlApplicationContextTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationClassPathXmlApplicationContextTests.java index 8143abd3..94b0178d 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationClassPathXmlApplicationContextTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationClassPathXmlApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis.config.annotation.web.http; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +package org.springframework.session.data.redis.config.annotation.web.http; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + /** * @author Rob Winch * @@ -35,13 +37,14 @@ public class RedisHttpSessionConfigurationClassPathXmlApplicationContextTests { // gh-318 @Test - public void contextLoads() {} + public void contextLoads() { + } static RedisConnectionFactory connectionFactory() { RedisConnectionFactory factory = mock(RedisConnectionFactory.class); RedisConnection connection = mock(RedisConnection.class); - when(factory.getConnection()).thenReturn(connection); + given(factory.getConnection()).willReturn(connection); return factory; } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java index 521947d1..5c060020 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis.config.annotation.web.http; -import static org.mockito.Mockito.mock; +package org.springframework.session.data.redis.config.annotation.web.http; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; @@ -27,6 +27,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.mockito.Mockito.mock; + /** * @author Rob Winch */ @@ -36,7 +38,8 @@ import org.springframework.test.context.web.WebAppConfiguration; public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { @Test - public void redisConnectionFactoryNotUsedSinceNoValidation() {} + public void redisConnectionFactoryNotUsedSinceNoValidation() { + } @EnableRedisHttpSession @Configuration diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideDefaultSerializerTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideDefaultSerializerTests.java index bad61458..b0911dcf 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideDefaultSerializerTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideDefaultSerializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis.config.annotation.web.http; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.*; +package org.springframework.session.data.redis.config.annotation.web.http; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,6 +30,10 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + /** * @author Rob Winch * @@ -41,14 +44,14 @@ import org.springframework.test.context.web.WebAppConfiguration; public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests { @Autowired - RedisTemplate template; + RedisTemplate template; @Autowired RedisSerializer defaultRedisSerializer; @Test public void overrideDefaultRedisTemplate() { - assertThat(template.getDefaultSerializer()).isSameAs(defaultRedisSerializer); + assertThat(this.template.getDefaultSerializer()).isSameAs(this.defaultRedisSerializer); } @EnableRedisHttpSession @@ -64,7 +67,7 @@ public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests { public RedisConnectionFactory connectionFactory() { RedisConnectionFactory factory = mock(RedisConnectionFactory.class); RedisConnection connection = mock(RedisConnection.class); - when(factory.getConnection()).thenReturn(connection); + given(factory.getConnection()).willReturn(connection); return factory; } diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutor.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutor.java index 8f03fb82..791825d4 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutor.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis.config.annotation.web.http; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +package org.springframework.session.data.redis.config.annotation.web.http; import java.util.concurrent.Executor; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -36,6 +32,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + /** * @author Vladimir Tsanev * @@ -53,7 +55,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor { @Test public void overrideSessionTaskExecutor() { - verify(springSessionRedisTaskExecutor, times(1)).execute(any(SchedulingAwareRunnable.class)); + verify(this.springSessionRedisTaskExecutor, times(1)).execute(any(SchedulingAwareRunnable.class)); } @EnableRedisHttpSession @@ -68,7 +70,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor { public RedisConnectionFactory connectionFactory() { RedisConnectionFactory factory = mock(RedisConnectionFactory.class); RedisConnection connection = mock(RedisConnection.class); - when(factory.getConnection()).thenReturn(connection); + given(factory.getConnection()).willReturn(connection); return factory; } diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutors.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutors.java index 909a9284..2e34aa20 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutors.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutors.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.data.redis.config.annotation.web.http; +import java.util.concurrent.Executor; + import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -28,14 +32,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import java.util.concurrent.Executor; - +import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Vladimir Tsanev @@ -57,8 +59,8 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors { @Test public void overrideSessionTaskExecutors() { - verify(springSessionRedisSubscriptionExecutor, times(1)).execute(any(SchedulingAwareRunnable.class)); - verify(springSessionRedisTaskExecutor, never()).execute(any(Runnable.class)); + verify(this.springSessionRedisSubscriptionExecutor, times(1)).execute(any(SchedulingAwareRunnable.class)); + verify(this.springSessionRedisTaskExecutor, never()).execute(any(Runnable.class)); } @EnableRedisHttpSession @@ -78,7 +80,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors { public RedisConnectionFactory connectionFactory() { RedisConnectionFactory factory = mock(RedisConnectionFactory.class); RedisConnection connection = mock(RedisConnection.class); - when(factory.getConnection()).thenReturn(connection); + given(factory.getConnection()).willReturn(connection); return factory; } diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlCustomExpireTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlCustomExpireTests.java index 99e62136..9bfc91ef 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlCustomExpireTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlCustomExpireTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,32 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis.config.annotation.web.http; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +package org.springframework.session.data.redis.config.annotation.web.http; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration public class RedisHttpSessionConfigurationXmlCustomExpireTests { @Test - public void contextLoads() {} + public void contextLoads() { + } static RedisConnectionFactory connectionFactory() { RedisConnectionFactory factory = mock(RedisConnectionFactory.class); RedisConnection connection = mock(RedisConnection.class); - when(factory.getConnection()).thenReturn(connection); + given(factory.getConnection()).willReturn(connection); return factory; } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlTests.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlTests.java index 08ca2ecb..afbe3bb8 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlTests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,32 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis.config.annotation.web.http; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +package org.springframework.session.data.redis.config.annotation.web.http; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration public class RedisHttpSessionConfigurationXmlTests { @Test - public void contextLoads() {} + public void contextLoads() { + } static RedisConnectionFactory connectionFactory() { RedisConnectionFactory factory = mock(RedisConnectionFactory.class); RedisConnection connection = mock(RedisConnection.class); - when(factory.getConnection()).thenReturn(connection); + given(factory.getConnection()).willReturn(connection); return factory; } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/gh109/Gh109Tests.java b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/gh109/Gh109Tests.java index a4f93f1f..62d8d72b 100644 --- a/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/gh109/Gh109Tests.java +++ b/spring-session/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/gh109/Gh109Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.data.redis.config.annotation.web.http.gh109; -import static org.mockito.Mockito.*; +package org.springframework.session.data.redis.config.annotation.web.http.gh109; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,6 +31,9 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + /** * This test must be in a different package than RedisHttpSessionConfiguration. * @@ -61,7 +64,7 @@ public class Gh109Tests { public RedisOperationsSessionRepository sessionRepository(RedisOperations sessionRedisTemplate, ApplicationEventPublisher applicationEventPublisher) { RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository( sessionRedisTemplate); - sessionRepository.setDefaultMaxInactiveInterval(sessionTimeout); + sessionRepository.setDefaultMaxInactiveInterval(this.sessionTimeout); return sessionRepository; } @@ -70,7 +73,7 @@ public class Gh109Tests { RedisConnectionFactory factory = mock(RedisConnectionFactory.class); RedisConnection connection = mock(RedisConnection.class); - when(factory.getConnection()).thenReturn(connection); + given(factory.getConnection()).willReturn(connection); return factory; } } diff --git a/spring-session/src/test/java/org/springframework/session/web/http/CookieHttpSessionStrategyTests.java b/spring-session/src/test/java/org/springframework/session/web/http/CookieHttpSessionStrategyTests.java index f0668a04..64845f4d 100644 --- a/spring-session/src/test/java/org/springframework/session/web/http/CookieHttpSessionStrategyTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/http/CookieHttpSessionStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,19 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; -import static org.assertj.core.api.Assertions.*; +import java.util.Map; + +import javax.servlet.http.Cookie; import org.junit.Before; import org.junit.Test; + import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.session.MapSession; import org.springframework.session.Session; -import javax.servlet.http.Cookie; -import java.util.Map; +import static org.assertj.core.api.Assertions.assertThat; public class CookieHttpSessionStrategyTests { private MockHttpServletRequest request; @@ -37,56 +40,56 @@ public class CookieHttpSessionStrategyTests { @Before public void setup() throws Exception { - cookieName = "SESSION"; - session = new MapSession(); - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - strategy = new CookieHttpSessionStrategy(); + this.cookieName = "SESSION"; + this.session = new MapSession(); + this.request = new MockHttpServletRequest(); + this.response = new MockHttpServletResponse(); + this.strategy = new CookieHttpSessionStrategy(); } @Test public void getRequestedSessionIdNull() throws Exception { - assertThat(strategy.getRequestedSessionId(request)).isNull(); + assertThat(this.strategy.getRequestedSessionId(this.request)).isNull(); } @Test public void getRequestedSessionIdNotNull() throws Exception { - setSessionCookie(session.getId()); - assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId()); + setSessionCookie(this.session.getId()); + assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId()); } @Test public void getRequestedSessionIdNotNullCustomCookieName() throws Exception { setCookieName("CUSTOM"); - setSessionCookie(session.getId()); - assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId()); + setSessionCookie(this.session.getId()); + assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId()); } @Test public void onNewSession() throws Exception { - strategy.onNewSession(session, request, response); - assertThat(getSessionId()).isEqualTo(session.getId()); + this.strategy.onNewSession(this.session, this.request, this.response); + assertThat(getSessionId()).isEqualTo(this.session.getId()); } @Test public void onNewSessionTwiceSameId() throws Exception { - strategy.onNewSession(session, request, response); - strategy.onNewSession(session, request, response); + this.strategy.onNewSession(this.session, this.request, this.response); + this.strategy.onNewSession(this.session, this.request, this.response); - assertThat(response.getCookies()).hasSize(1); + assertThat(this.response.getCookies()).hasSize(1); } @Test public void onNewSessionTwiceNewId() throws Exception { Session newSession = new MapSession(); - strategy.onNewSession(session, request, response); - strategy.onNewSession(newSession, request, response); + this.strategy.onNewSession(this.session, this.request, this.response); + this.strategy.onNewSession(newSession, this.request, this.response); - Cookie[] cookies = response.getCookies(); + Cookie[] cookies = this.response.getCookies(); assertThat(cookies).hasSize(2); - assertThat(cookies[0].getValue()).isEqualTo(session.getId()); + assertThat(cookies[0].getValue()).isEqualTo(this.session.getId()); assertThat(cookies[1].getValue()).isEqualTo(newSession.getId()); } @@ -94,302 +97,302 @@ public class CookieHttpSessionStrategyTests { public void onNewSessionExistingSessionSameAlias() throws Exception { Session existing = new MapSession(); setSessionCookie(existing.getId()); - strategy.onNewSession(session, request, response); - assertThat(getSessionId()).isEqualTo(session.getId()); + this.strategy.onNewSession(this.session, this.request, this.response); + assertThat(getSessionId()).isEqualTo(this.session.getId()); } @Test public void onNewSessionExistingSessionNewAlias() throws Exception { Session existing = new MapSession(); setSessionCookie(existing.getId()); - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new"); - strategy.onNewSession(session, request, response); - assertThat(getSessionId()).isEqualTo("0 " + existing.getId() + " new " + session.getId()); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new"); + this.strategy.onNewSession(this.session, this.request, this.response); + assertThat(getSessionId()).isEqualTo("0 " + existing.getId() + " new " + this.session.getId()); } // gh-321 @Test public void onNewSessionExplicitAlias() throws Exception { - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new"); - strategy.onNewSession(session, request, response); - assertThat(getSessionId()).isEqualTo("new " + session.getId()); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new"); + this.strategy.onNewSession(this.session, this.request, this.response); + assertThat(getSessionId()).isEqualTo("new " + this.session.getId()); } @Test public void onNewSessionCookiePath() throws Exception { - request.setContextPath("/somethingunique"); - strategy.onNewSession(session, request, response); + this.request.setContextPath("/somethingunique"); + this.strategy.onNewSession(this.session, this.request, this.response); - Cookie sessionCookie = response.getCookie(cookieName); - assertThat(sessionCookie.getPath()).isEqualTo(request.getContextPath() + "/"); + Cookie sessionCookie = this.response.getCookie(this.cookieName); + assertThat(sessionCookie.getPath()).isEqualTo(this.request.getContextPath() + "/"); } @Test public void onNewSessionCustomCookieName() throws Exception { setCookieName("CUSTOM"); - strategy.onNewSession(session, request, response); - assertThat(getSessionId()).isEqualTo(session.getId()); + this.strategy.onNewSession(this.session, this.request, this.response); + assertThat(getSessionId()).isEqualTo(this.session.getId()); } @Test public void onDeleteSession() throws Exception { - strategy.onInvalidateSession(request, response); + this.strategy.onInvalidateSession(this.request, this.response); assertThat(getSessionId()).isEmpty(); } @Test public void onDeleteSessionCookiePath() throws Exception { - request.setContextPath("/somethingunique"); - strategy.onInvalidateSession(request, response); + this.request.setContextPath("/somethingunique"); + this.strategy.onInvalidateSession(this.request, this.response); - Cookie sessionCookie = response.getCookie(cookieName); - assertThat(sessionCookie.getPath()).isEqualTo(request.getContextPath() + "/"); + Cookie sessionCookie = this.response.getCookie(this.cookieName); + assertThat(sessionCookie.getPath()).isEqualTo(this.request.getContextPath() + "/"); } @Test public void onDeleteSessionCustomCookieName() throws Exception { setCookieName("CUSTOM"); - strategy.onInvalidateSession(request, response); + this.strategy.onInvalidateSession(this.request, this.response); assertThat(getSessionId()).isEmpty(); } @Test public void onDeleteSessionExistingSessionSameAlias() throws Exception { Session existing = new MapSession(); - setSessionCookie("0 " + existing.getId() + " new " + session.getId()); - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new"); - strategy.onInvalidateSession(request, response); + setSessionCookie("0 " + existing.getId() + " new " + this.session.getId()); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new"); + this.strategy.onInvalidateSession(this.request, this.response); assertThat(getSessionId()).isEqualTo(existing.getId()); } @Test public void onDeleteSessionExistingSessionNewAlias() throws Exception { Session existing = new MapSession(); - setSessionCookie("0 " + existing.getId() + " new " + session.getId()); - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new"); - strategy.onInvalidateSession(request, response); + setSessionCookie("0 " + existing.getId() + " new " + this.session.getId()); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "new"); + this.strategy.onInvalidateSession(this.request, this.response); assertThat(getSessionId()).isEqualTo(existing.getId()); } @SuppressWarnings("deprecation") @Test(expected = IllegalArgumentException.class) public void setCookieNameNull() throws Exception { - strategy.setCookieName(null); + this.strategy.setCookieName(null); } @Test public void encodeURLNoExistingQuery() { - assertThat(strategy.encodeURL("/url", "2")).isEqualTo("/url?_s=2"); + assertThat(this.strategy.encodeURL("/url", "2")).isEqualTo("/url?_s=2"); } @Test public void encodeURLNoExistingQueryEmpty() { - assertThat(strategy.encodeURL("/url?", "2")).isEqualTo("/url?_s=2"); + assertThat(this.strategy.encodeURL("/url?", "2")).isEqualTo("/url?_s=2"); } @Test public void encodeURLExistingQueryNoAlias() { - assertThat(strategy.encodeURL("/url?a=b", "2")).isEqualTo("/url?a=b&_s=2"); + assertThat(this.strategy.encodeURL("/url?a=b", "2")).isEqualTo("/url?a=b&_s=2"); } @Test public void encodeURLExistingQueryExistingAliasStart() { - assertThat(strategy.encodeURL("/url?_s=1&y=z", "2")).isEqualTo("/url?_s=2&y=z"); + assertThat(this.strategy.encodeURL("/url?_s=1&y=z", "2")).isEqualTo("/url?_s=2&y=z"); } @Test public void encodeURLExistingQueryExistingAliasMiddle() { - assertThat(strategy.encodeURL("/url?a=b&_s=1&y=z", "2")).isEqualTo("/url?a=b&_s=2&y=z"); + assertThat(this.strategy.encodeURL("/url?a=b&_s=1&y=z", "2")).isEqualTo("/url?a=b&_s=2&y=z"); } @Test public void encodeURLExistingQueryExistingAliasEnd() { - assertThat(strategy.encodeURL("/url?a=b&_s=1", "2")).isEqualTo("/url?a=b&_s=2"); + assertThat(this.strategy.encodeURL("/url?a=b&_s=1", "2")).isEqualTo("/url?a=b&_s=2"); } // @Test public void encodeURLExistingQueryParamEndsWithActualParamStart() { - assertThat(strategy.encodeURL("/url?x_s=1&y=z", "2")).isEqualTo("/url?x_s=1&y=z&_s=2"); + assertThat(this.strategy.encodeURL("/url?x_s=1&y=z", "2")).isEqualTo("/url?x_s=1&y=z&_s=2"); } @Test public void encodeURLExistingQueryParamEndsWithActualParamMiddle() { - assertThat(strategy.encodeURL("/url?a=b&x_s=1&y=z", "2")).isEqualTo("/url?a=b&x_s=1&y=z&_s=2"); + assertThat(this.strategy.encodeURL("/url?a=b&x_s=1&y=z", "2")).isEqualTo("/url?a=b&x_s=1&y=z&_s=2"); } @Test public void encodeURLExistingQueryParamEndsWithActualParamEnd() { - assertThat(strategy.encodeURL("/url?a=b&x_s=1", "2")).isEqualTo("/url?a=b&x_s=1&_s=2"); + assertThat(this.strategy.encodeURL("/url?a=b&x_s=1", "2")).isEqualTo("/url?a=b&x_s=1&_s=2"); } // @Test public void encodeURLNoExistingQueryDefaultAlias() { - assertThat(strategy.encodeURL("/url", "0")).isEqualTo("/url"); + assertThat(this.strategy.encodeURL("/url", "0")).isEqualTo("/url"); } @Test public void encodeURLNoExistingQueryEmptyDefaultAlias() { - assertThat(strategy.encodeURL("/url?", "0")).isEqualTo("/url?"); + assertThat(this.strategy.encodeURL("/url?", "0")).isEqualTo("/url?"); } @Test public void encodeURLExistingQueryNoAliasDefaultAlias() { - assertThat(strategy.encodeURL("/url?a=b", "0")).isEqualTo("/url?a=b"); + assertThat(this.strategy.encodeURL("/url?a=b", "0")).isEqualTo("/url?a=b"); } @Test public void encodeURLExistingQueryExistingAliasStartDefaultAlias() { // relaxed constraint as result /url?&y=z does not hurt anything (ideally should remove the &) - assertThat(strategy.encodeURL("/url?_s=1&y=z", "0")).doesNotContain("_s=0&_s=1"); + assertThat(this.strategy.encodeURL("/url?_s=1&y=z", "0")).doesNotContain("_s=0&_s=1"); } @Test public void encodeURLExistingQueryExistingAliasMiddleDefaultAlias() { - assertThat(strategy.encodeURL("/url?a=b&_s=1&y=z", "0")).isEqualTo("/url?a=b&y=z"); + assertThat(this.strategy.encodeURL("/url?a=b&_s=1&y=z", "0")).isEqualTo("/url?a=b&y=z"); } @Test public void encodeURLExistingQueryExistingAliasEndDefaultAlias() { - assertThat(strategy.encodeURL("/url?a=b&_s=1", "0")).isEqualTo("/url?a=b"); + assertThat(this.strategy.encodeURL("/url?a=b&_s=1", "0")).isEqualTo("/url?a=b"); } @Test public void encodeURLMaliciousAlias() { - assertThat(strategy.encodeURL("/url?a=b&_s=1", "\"> ")).isEqualTo("/url?a=b&_s=%22%3E+%3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E"); + assertThat(this.strategy.encodeURL("/url?a=b&_s=1", "\"> ")).isEqualTo("/url?a=b&_s=%22%3E+%3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E"); } // --- getCurrentSessionAlias @Test public void getCurrentSessionAliasNull() { - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); } @Test public void getCurrentSessionAliasNullParamName() { - strategy.setSessionAliasParamName(null); - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "NOT USED"); + this.strategy.setSessionAliasParamName(null); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "NOT USED"); - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); } // protect against malicious users @Test public void getCurrentSessionAliasContainsQuote() { - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here\"this"); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here\"this"); - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); } @Test - public void getCurrentSessionAliasContainsSingleQuote() { - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here'this"); + public void getCurrentSessionAliasContainsSingleQuote() { + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here'this"); - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); } @Test public void getCurrentSessionAliasContainsSpace() { - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here this"); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here this"); - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); } @Test public void getCurrentSessionAliasContainsLt() { - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "herethis"); + this.strategy.setSessionAliasParamName(null); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here>this"); - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); } @Test public void getCurrentSessionAliasTooLong() { - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "012345678901234567890123456789012345678901234567890"); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "012345678901234567890123456789012345678901234567890"); - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); } // We want some sort of length restrictions, but want to ensure some sort of length Technically no hard limit, but chose 50 @Test public void getCurrentSessionAliasAllows50() { - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "01234567890123456789012345678901234567890123456789"); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "01234567890123456789012345678901234567890123456789"); - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo("01234567890123456789012345678901234567890123456789"); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo("01234567890123456789012345678901234567890123456789"); } @Test public void getCurrentSession() { String expectedAlias = "1"; - request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, expectedAlias); - assertThat(strategy.getCurrentSessionAlias(request)).isEqualTo(expectedAlias); + this.request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, expectedAlias); + assertThat(this.strategy.getCurrentSessionAlias(this.request)).isEqualTo(expectedAlias); } // --- getNewSessionAlias @Test public void getNewSessionAliasNoSessions() { - assertThat(strategy.getNewSessionAlias(request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); + assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualTo(CookieHttpSessionStrategy.DEFAULT_ALIAS); } @Test public void getNewSessionAliasSingleSession() { setSessionCookie("abc"); - assertThat(strategy.getNewSessionAlias(request)).isEqualTo("1"); + assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualTo("1"); } @Test public void getNewSessionAlias2Sessions() { setCookieWithNSessions(2); - assertThat(strategy.getNewSessionAlias(request)).isEqualTo("2"); + assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualTo("2"); } @Test public void getNewSessionAlias9Sessions() { setCookieWithNSessions(9); - assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("9"); + assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("9"); } @Test public void getNewSessionAlias10Sessions() { setCookieWithNSessions(10); - assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("a"); + assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("a"); } @Test public void getNewSessionAlias16Sessions() { setCookieWithNSessions(16); - assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("10"); + assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("10"); } @Test public void getNewSessionAliasInvalidAlias() { setSessionCookie("0 1 $ b"); - assertThat(strategy.getNewSessionAlias(request)).isEqualToIgnoringCase("1"); + assertThat(this.strategy.getNewSessionAlias(this.request)).isEqualToIgnoringCase("1"); } // --- getSessionIds @Test public void getSessionIdsNone() { - assertThat(strategy.getSessionIds(request)).isEmpty(); + assertThat(this.strategy.getSessionIds(this.request)).isEmpty(); } @Test @@ -397,7 +400,7 @@ public class CookieHttpSessionStrategyTests { String expectedId = "a"; setSessionCookie(expectedId); - Map sessionIds = strategy.getSessionIds(request); + Map sessionIds = this.strategy.getSessionIds(this.request); assertThat(sessionIds.size()).isEqualTo(1); assertThat(sessionIds.get("0")).isEqualTo(expectedId); } @@ -406,7 +409,7 @@ public class CookieHttpSessionStrategyTests { public void getSessionIdsMulti() { setSessionCookie("0 a 1 b"); - Map sessionIds = strategy.getSessionIds(request); + Map sessionIds = this.strategy.getSessionIds(this.request); assertThat(sessionIds.size()).isEqualTo(2); assertThat(sessionIds.get("0")).isEqualTo("a"); assertThat(sessionIds.get("1")).isEqualTo("b"); @@ -416,7 +419,7 @@ public class CookieHttpSessionStrategyTests { public void getSessionIdsDangling() { setSessionCookie("0 a 1 b noValue"); - Map sessionIds = strategy.getSessionIds(request); + Map sessionIds = this.strategy.getSessionIds(this.request); assertThat(sessionIds.size()).isEqualTo(2); assertThat(sessionIds.get("0")).isEqualTo("a"); assertThat(sessionIds.get("1")).isEqualTo("b"); @@ -436,12 +439,12 @@ public class CookieHttpSessionStrategyTests { private String createSessionCookieValue(long size) { StringBuffer buffer = new StringBuffer(); - for(long i=0;i < size; i++) { + for (long i = 0; i < size; i++) { String hex = Long.toHexString(i); buffer.append(hex); buffer.append(" "); buffer.append(i); - if(i < size - 1) { + if (i < size - 1) { buffer.append(" "); } } @@ -451,15 +454,15 @@ public class CookieHttpSessionStrategyTests { @SuppressWarnings("deprecation") public void setCookieName(String cookieName) { - strategy.setCookieName(cookieName); + this.strategy.setCookieName(cookieName); this.cookieName = cookieName; } public void setSessionCookie(String value) { - request.setCookies(new Cookie(cookieName, value)); + this.request.setCookies(new Cookie(this.cookieName, value)); } public String getSessionId() { - return response.getCookie(cookieName).getValue(); + return this.response.getCookie(this.cookieName).getValue(); } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/web/http/DefaultCookieSerializerTests.java b/spring-session/src/test/java/org/springframework/session/web/http/DefaultCookieSerializerTests.java index e81d5af6..94d4cb54 100644 --- a/spring-session/src/test/java/org/springframework/session/web/http/DefaultCookieSerializerTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/http/DefaultCookieSerializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.web.http; -import static org.assertj.core.api.Assertions.*; +package org.springframework.session.web.http; import javax.servlet.http.Cookie; import org.junit.Before; import org.junit.Test; + import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.session.web.http.CookieSerializer.CookieValue; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Rob Winch * @@ -43,107 +45,107 @@ public class DefaultCookieSerializerTests { @Before public void setup() { - cookieName = "SESSION"; - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - sessionId = "sessionId"; - serializer = new DefaultCookieSerializer(); + this.cookieName = "SESSION"; + this.request = new MockHttpServletRequest(); + this.response = new MockHttpServletResponse(); + this.sessionId = "sessionId"; + this.serializer = new DefaultCookieSerializer(); } // --- readCookieValues --- @Test public void readCookieValuesNull() { - assertThat(serializer.readCookieValues(request)).isEmpty(); + assertThat(this.serializer.readCookieValues(this.request)).isEmpty(); } @Test public void readCookieValuesSingle() { - request.setCookies(new Cookie(cookieName, sessionId)); + this.request.setCookies(new Cookie(this.cookieName, this.sessionId)); - assertThat(serializer.readCookieValues(request)).containsOnly(sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } @Test public void readCookieValuesSingleAndInvalidName() { - request.setCookies(new Cookie(cookieName, sessionId), new Cookie(cookieName+"INVALID", sessionId + "INVALID")); + this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName + "INVALID", this.sessionId + "INVALID")); - assertThat(serializer.readCookieValues(request)).containsOnly(sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } @Test public void readCookieValuesMulti() { String secondSession = "secondSessionId"; - request.setCookies(new Cookie(cookieName, sessionId), new Cookie(cookieName, secondSession)); + this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName, secondSession)); - assertThat(serializer.readCookieValues(request)).containsExactly(sessionId, secondSession); + assertThat(this.serializer.readCookieValues(this.request)).containsExactly(this.sessionId, secondSession); } @Test public void readCookieValuesMultiCustomSessionCookieName() { setCookieName("JSESSIONID"); String secondSession = "secondSessionId"; - request.setCookies(new Cookie(cookieName, sessionId), new Cookie(cookieName, secondSession)); + this.request.setCookies(new Cookie(this.cookieName, this.sessionId), new Cookie(this.cookieName, secondSession)); - assertThat(serializer.readCookieValues(request)).containsExactly(sessionId, secondSession); + assertThat(this.serializer.readCookieValues(this.request)).containsExactly(this.sessionId, secondSession); } // gh-392 @Test public void readCookieValuesNullCookieValue() { - request.setCookies(new Cookie(cookieName, null)); + this.request.setCookies(new Cookie(this.cookieName, null)); - assertThat(serializer.readCookieValues(request)).isEmpty(); + assertThat(this.serializer.readCookieValues(this.request)).isEmpty(); } @Test public void readCookieValuesNullCookieValueAndJvmRoute() { - serializer.setJvmRoute("123"); - request.setCookies(new Cookie(cookieName, null)); + this.serializer.setJvmRoute("123"); + this.request.setCookies(new Cookie(this.cookieName, null)); - assertThat(serializer.readCookieValues(request)).isEmpty(); + assertThat(this.serializer.readCookieValues(this.request)).isEmpty(); } @Test public void readCookieValuesNullCookieValueAndNotNullCookie() { - serializer.setJvmRoute("123"); - request.setCookies(new Cookie(cookieName, null), new Cookie(cookieName, sessionId)); + this.serializer.setJvmRoute("123"); + this.request.setCookies(new Cookie(this.cookieName, null), new Cookie(this.cookieName, this.sessionId)); - assertThat(serializer.readCookieValues(request)).containsOnly(sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } // --- writeCookie --- @Test public void writeCookie() { - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); - assertThat(getCookie().getValue()).isEqualTo(sessionId); + assertThat(getCookie().getValue()).isEqualTo(this.sessionId); } // --- httpOnly --- @Test public void writeCookieHttpOnlyDefault() { - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().isHttpOnly()).isTrue(); } @Test public void writeCookieHttpOnlySetTrue() { - serializer.setUseHttpOnlyCookie(true); + this.serializer.setUseHttpOnlyCookie(true); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().isHttpOnly()).isTrue(); } @Test public void writeCookieHttpOnlySetFalse() { - serializer.setUseHttpOnlyCookie(false); + this.serializer.setUseHttpOnlyCookie(false); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().isHttpOnly()).isFalse(); } @@ -152,7 +154,7 @@ public class DefaultCookieSerializerTests { @Test public void writeCookieDomainNameDefault() { - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getDomain()).isNull(); } @@ -160,17 +162,17 @@ public class DefaultCookieSerializerTests { @Test public void writeCookieDomainNameCustom() { String domainName = "example.com"; - serializer.setDomainName(domainName); + this.serializer.setDomainName(domainName); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getDomain()).isEqualTo(domainName); } - @Test(expected=IllegalStateException.class) + @Test(expected = IllegalStateException.class) public void setDomainNameAndDomainNamePatternThrows() { - serializer.setDomainName("example.com"); - serializer.setDomainNamePattern(".*"); + this.serializer.setDomainName("example.com"); + this.serializer.setDomainNamePattern(".*"); } // --- domainNamePattern --- @@ -178,38 +180,38 @@ public class DefaultCookieSerializerTests { @Test public void writeCookieDomainNamePattern() { String domainNamePattern = "^.+?\\.(\\w+\\.[a-z]+)$"; - serializer.setDomainNamePattern(domainNamePattern); + this.serializer.setDomainNamePattern(domainNamePattern); - String[] matchingDomains = {"child.sub.example.com","www.example.com"}; - for(String domain : matchingDomains) { - request.setServerName(domain); - serializer.writeCookieValue(cookieValue(sessionId)); + String[] matchingDomains = {"child.sub.example.com", "www.example.com"}; + for (String domain : matchingDomains) { + this.request.setServerName(domain); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getDomain()).isEqualTo("example.com"); - response = new MockHttpServletResponse(); + this.response = new MockHttpServletResponse(); } - String[] notMatchingDomains = {"example.com", "localhost","127.0.0.1"}; - for(String domain : notMatchingDomains) { - request.setServerName(domain); - serializer.writeCookieValue(cookieValue(sessionId)); + String[] notMatchingDomains = {"example.com", "localhost", "127.0.0.1"}; + for (String domain : notMatchingDomains) { + this.request.setServerName(domain); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getDomain()).isNull(); - response = new MockHttpServletResponse(); + this.response = new MockHttpServletResponse(); } } - @Test(expected=IllegalStateException.class) + @Test(expected = IllegalStateException.class) public void setDomainNamePatternAndDomainNameThrows() { - serializer.setDomainNamePattern(".*"); - serializer.setDomainName("example.com"); + this.serializer.setDomainNamePattern(".*"); + this.serializer.setDomainName("example.com"); } // --- cookieName --- @Test public void writeCookieCookieNameDefault() { - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getName()).isEqualTo("SESSION"); } @@ -219,52 +221,52 @@ public class DefaultCookieSerializerTests { String cookieName = "JSESSIONID"; setCookieName(cookieName); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getName()).isEqualTo(cookieName); } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void setCookieNameNullThrows() { - serializer.setCookieName(null); + this.serializer.setCookieName(null); } // --- cookiePath --- @Test public void writeCookieCookiePathDefaultEmptyContextPathUsed() { - request.setContextPath(""); + this.request.setContextPath(""); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getPath()).isEqualTo("/"); } @Test public void writeCookieCookiePathDefaultContextPathUsed() { - request.setContextPath("/context"); + this.request.setContextPath("/context"); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getPath()).isEqualTo("/context/"); } @Test public void writeCookieCookiePathExplicitNullCookiePathContextPathUsed() { - request.setContextPath("/context"); - serializer.setCookiePath(null); + this.request.setContextPath("/context"); + this.serializer.setCookiePath(null); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getPath()).isEqualTo("/context/"); } @Test public void writeCookieCookiePathExplicitCookiePath() { - request.setContextPath("/context"); - serializer.setCookiePath("/"); + this.request.setContextPath("/context"); + this.serializer.setCookiePath("/"); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getPath()).isEqualTo("/"); } @@ -273,25 +275,25 @@ public class DefaultCookieSerializerTests { @Test public void writeCookieCookieMaxAgeDefault() { - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getMaxAge()).isEqualTo(-1); } @Test public void writeCookieCookieMaxAgeExplicit() { - serializer.setCookieMaxAge(100); + this.serializer.setCookieMaxAge(100); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getMaxAge()).isEqualTo(100); } @Test public void writeCookieCookieMaxAgeExplicitEmptyCookie() { - serializer.setCookieMaxAge(100); + this.serializer.setCookieMaxAge(100); - serializer.writeCookieValue(cookieValue("")); + this.serializer.writeCookieValue(cookieValue("")); assertThat(getCookie().getMaxAge()).isEqualTo(0); } @@ -300,45 +302,45 @@ public class DefaultCookieSerializerTests { @Test public void writeCookieDefaultInsecureRequest() { - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getSecure()).isFalse(); } @Test public void writeCookieSecureSecureRequest() { - request.setSecure(true); - serializer.setUseSecureCookie(true); + this.request.setSecure(true); + this.serializer.setUseSecureCookie(true); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getSecure()).isTrue(); } @Test public void writeCookieSecureInsecureRequest() { - serializer.setUseSecureCookie(true); + this.serializer.setUseSecureCookie(true); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getSecure()).isTrue(); } @Test public void writeCookieInsecureSecureRequest() { - request.setSecure(true); - serializer.setUseSecureCookie(false); + this.request.setSecure(true); + this.serializer.setUseSecureCookie(false); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getSecure()).isFalse(); } @Test public void writeCookieInecureInsecureRequest() { - serializer.setUseSecureCookie(false); + this.serializer.setUseSecureCookie(false); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getSecure()).isFalse(); } @@ -348,38 +350,38 @@ public class DefaultCookieSerializerTests { @Test public void writeCookieJvmRoute() { String jvmRoute = "route"; - serializer.setJvmRoute(jvmRoute); + this.serializer.setJvmRoute(jvmRoute); - serializer.writeCookieValue(cookieValue(sessionId)); + this.serializer.writeCookieValue(cookieValue(this.sessionId)); - assertThat(getCookie().getValue()).isEqualTo(sessionId + "." + jvmRoute); + assertThat(getCookie().getValue()).isEqualTo(this.sessionId + "." + jvmRoute); } @Test public void readCookieJvmRoute() { String jvmRoute = "route"; - serializer.setJvmRoute(jvmRoute); - request.setCookies(new Cookie(cookieName, sessionId + "." + jvmRoute)); + this.serializer.setJvmRoute(jvmRoute); + this.request.setCookies(new Cookie(this.cookieName, this.sessionId + "." + jvmRoute)); - assertThat(serializer.readCookieValues(request)).containsOnly(sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } @Test public void readCookieJvmRouteRouteMissing() { String jvmRoute = "route"; - serializer.setJvmRoute(jvmRoute); - request.setCookies(new Cookie(cookieName, sessionId)); + this.serializer.setJvmRoute(jvmRoute); + this.request.setCookies(new Cookie(this.cookieName, this.sessionId)); - assertThat(serializer.readCookieValues(request)).containsOnly(sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } @Test public void readCookieJvmRouteOnlyRoute() { String jvmRoute = "route"; - serializer.setJvmRoute(jvmRoute); - request.setCookies(new Cookie(cookieName, "." + jvmRoute)); + this.serializer.setJvmRoute(jvmRoute); + this.request.setCookies(new Cookie(this.cookieName, "." + jvmRoute)); - assertThat(serializer.readCookieValues(request)).containsOnly(""); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(""); } public void setCookieName(String cookieName) { @@ -388,10 +390,10 @@ public class DefaultCookieSerializerTests { } private Cookie getCookie() { - return response.getCookie(cookieName); + return this.response.getCookie(this.cookieName); } private CookieValue cookieValue(String cookieValue) { - return new CookieValue(request, response, cookieValue); + return new CookieValue(this.request, this.response, cookieValue); } } diff --git a/spring-session/src/test/java/org/springframework/session/web/http/HeaderSessionStrategyTests.java b/spring-session/src/test/java/org/springframework/session/web/http/HeaderSessionStrategyTests.java index bc239766..87439ebf 100644 --- a/spring-session/src/test/java/org/springframework/session/web/http/HeaderSessionStrategyTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/http/HeaderSessionStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import org.junit.Before; import org.junit.Test; + import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.session.MapSession; import org.springframework.session.Session; -import org.springframework.session.web.http.HeaderHttpSessionStrategy; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; public class HeaderSessionStrategyTests { private MockHttpServletRequest request; @@ -35,57 +36,57 @@ public class HeaderSessionStrategyTests { @Before public void setup() throws Exception { - headerName = "x-auth-token"; - session = new MapSession(); - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - strategy = new HeaderHttpSessionStrategy(); + this.headerName = "x-auth-token"; + this.session = new MapSession(); + this.request = new MockHttpServletRequest(); + this.response = new MockHttpServletResponse(); + this.strategy = new HeaderHttpSessionStrategy(); } @Test public void getRequestedSessionIdNull() throws Exception { - assertThat(strategy.getRequestedSessionId(request)).isNull(); + assertThat(this.strategy.getRequestedSessionId(this.request)).isNull(); } @Test public void getRequestedSessionIdNotNull() throws Exception { - setSessionId(session.getId()); - assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId()); + setSessionId(this.session.getId()); + assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId()); } @Test public void getRequestedSessionIdNotNullCustomHeaderName() throws Exception { setHeaderName("CUSTOM"); - setSessionId(session.getId()); - assertThat(strategy.getRequestedSessionId(request)).isEqualTo(session.getId()); + setSessionId(this.session.getId()); + assertThat(this.strategy.getRequestedSessionId(this.request)).isEqualTo(this.session.getId()); } @Test public void onNewSession() throws Exception { - strategy.onNewSession(session, request, response); - assertThat(getSessionId()).isEqualTo(session.getId()); + this.strategy.onNewSession(this.session, this.request, this.response); + assertThat(getSessionId()).isEqualTo(this.session.getId()); } // the header is set as apposed to added @Test public void onNewSessionMulti() throws Exception { - strategy.onNewSession(session, request, response); - strategy.onNewSession(session, request, response); + this.strategy.onNewSession(this.session, this.request, this.response); + this.strategy.onNewSession(this.session, this.request, this.response); - assertThat(response.getHeaders(headerName).size()).isEqualTo(1); - assertThat(response.getHeaders(headerName)).containsOnly(session.getId()); + assertThat(this.response.getHeaders(this.headerName).size()).isEqualTo(1); + assertThat(this.response.getHeaders(this.headerName)).containsOnly(this.session.getId()); } @Test public void onNewSessionCustomHeaderName() throws Exception { setHeaderName("CUSTOM"); - strategy.onNewSession(session, request, response); - assertThat(getSessionId()).isEqualTo(session.getId()); + this.strategy.onNewSession(this.session, this.request, this.response); + assertThat(getSessionId()).isEqualTo(this.session.getId()); } @Test public void onDeleteSession() throws Exception { - strategy.onInvalidateSession(request, response); + this.strategy.onInvalidateSession(this.request, this.response); assertThat(getSessionId()).isEmpty(); } @@ -93,35 +94,35 @@ public class HeaderSessionStrategyTests { // the header is set as apposed to added @Test public void onDeleteSessionMulti() throws Exception { - strategy.onInvalidateSession(request, response); - strategy.onInvalidateSession(request, response); + this.strategy.onInvalidateSession(this.request, this.response); + this.strategy.onInvalidateSession(this.request, this.response); - assertThat(response.getHeaders(headerName).size()).isEqualTo(1); + assertThat(this.response.getHeaders(this.headerName).size()).isEqualTo(1); assertThat(getSessionId()).isEmpty(); } @Test public void onDeleteSessionCustomHeaderName() throws Exception { setHeaderName("CUSTOM"); - strategy.onInvalidateSession(request, response); + this.strategy.onInvalidateSession(this.request, this.response); assertThat(getSessionId()).isEmpty(); } @Test(expected = IllegalArgumentException.class) public void setHeaderNameNull() throws Exception { - strategy.setHeaderName(null); + this.strategy.setHeaderName(null); } public void setHeaderName(String headerName) { - strategy.setHeaderName(headerName); + this.strategy.setHeaderName(headerName); this.headerName = headerName; } public void setSessionId(String id) { - request.addHeader(headerName, id); + this.request.addHeader(this.headerName, id); } public String getSessionId() { - return response.getHeader(headerName); + return this.response.getHeader(this.headerName); } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/web/http/OnCommittedResponseWrapperTests.java b/spring-session/src/test/java/org/springframework/session/web/http/OnCommittedResponseWrapperTests.java index b82f5f6c..e8c57d00 100644 --- a/spring-session/src/test/java/org/springframework/session/web/http/OnCommittedResponseWrapperTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/http/OnCommittedResponseWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,24 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; - -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class OnCommittedResponseWrapperTests { @@ -49,14 +50,14 @@ public class OnCommittedResponseWrapperTests { @Before public void setup() throws Exception { - response = new OnCommittedResponseWrapper(delegate) { + this.response = new OnCommittedResponseWrapper(this.delegate) { @Override protected void onResponseCommitted() { - committed = true; + OnCommittedResponseWrapperTests.this.committed = true; } }; - when(delegate.getWriter()).thenReturn(writer); - when(delegate.getOutputStream()).thenReturn(out); + given(this.delegate.getWriter()).willReturn(this.writer); + given(this.delegate.getOutputStream()).willReturn(this.out); } @@ -64,26 +65,26 @@ public class OnCommittedResponseWrapperTests { @Test public void printWriterHashCode() throws Exception { - int expected = writer.hashCode(); + int expected = this.writer.hashCode(); - assertThat(response.getWriter().hashCode()).isEqualTo(expected); + assertThat(this.response.getWriter().hashCode()).isEqualTo(expected); } @Test public void printWriterCheckError() throws Exception { boolean expected = true; - when(writer.checkError()).thenReturn(expected); + given(this.writer.checkError()).willReturn(expected); - assertThat(response.getWriter().checkError()).isEqualTo(expected); + assertThat(this.response.getWriter().checkError()).isEqualTo(expected); } @Test public void printWriterWriteInt() throws Exception { int expected = 1; - response.getWriter().write(expected); + this.response.getWriter().write(expected); - verify(writer).write(expected); + verify(this.writer).write(expected); } @Test @@ -92,18 +93,18 @@ public class OnCommittedResponseWrapperTests { int off = 2; int len = 3; - response.getWriter().write(buff,off,len); + this.response.getWriter().write(buff, off, len); - verify(writer).write(buff,off,len); + verify(this.writer).write(buff, off, len); } @Test public void printWriterWriteChar() throws Exception { char[] buff = new char[0]; - response.getWriter().write(buff); + this.response.getWriter().write(buff); - verify(writer).write(buff); + verify(this.writer).write(buff); } @Test @@ -112,187 +113,187 @@ public class OnCommittedResponseWrapperTests { int off = 2; int len = 3; - response.getWriter().write(s,off,len); + this.response.getWriter().write(s, off, len); - verify(writer).write(s,off,len); + verify(this.writer).write(s, off, len); } @Test public void printWriterWriteString() throws Exception { String s = ""; - response.getWriter().write(s); + this.response.getWriter().write(s); - verify(writer).write(s); + verify(this.writer).write(s); } @Test public void printWriterPrintBoolean() throws Exception { boolean b = true; - response.getWriter().print(b); + this.response.getWriter().print(b); - verify(writer).print(b); + verify(this.writer).print(b); } @Test public void printWriterPrintChar() throws Exception { char c = 1; - response.getWriter().print(c); + this.response.getWriter().print(c); - verify(writer).print(c); + verify(this.writer).print(c); } @Test public void printWriterPrintInt() throws Exception { int i = 1; - response.getWriter().print(i); + this.response.getWriter().print(i); - verify(writer).print(i); + verify(this.writer).print(i); } @Test public void printWriterPrintLong() throws Exception { long l = 1; - response.getWriter().print(l); + this.response.getWriter().print(l); - verify(writer).print(l); + verify(this.writer).print(l); } @Test public void printWriterPrintFloat() throws Exception { float f = 1; - response.getWriter().print(f); + this.response.getWriter().print(f); - verify(writer).print(f); + verify(this.writer).print(f); } @Test public void printWriterPrintDouble() throws Exception { double x = 1; - response.getWriter().print(x); + this.response.getWriter().print(x); - verify(writer).print(x); + verify(this.writer).print(x); } @Test public void printWriterPrintCharArray() throws Exception { char[] x = new char[0]; - response.getWriter().print(x); + this.response.getWriter().print(x); - verify(writer).print(x); + verify(this.writer).print(x); } @Test public void printWriterPrintString() throws Exception { String x = "1"; - response.getWriter().print(x); + this.response.getWriter().print(x); - verify(writer).print(x); + verify(this.writer).print(x); } @Test public void printWriterPrintObject() throws Exception { Object x = "1"; - response.getWriter().print(x); + this.response.getWriter().print(x); - verify(writer).print(x); + verify(this.writer).print(x); } @Test public void printWriterPrintln() throws Exception { - response.getWriter().println(); + this.response.getWriter().println(); - verify(writer).println(); + verify(this.writer).println(); } @Test public void printWriterPrintlnBoolean() throws Exception { boolean b = true; - response.getWriter().println(b); + this.response.getWriter().println(b); - verify(writer).println(b); + verify(this.writer).println(b); } @Test public void printWriterPrintlnChar() throws Exception { char c = 1; - response.getWriter().println(c); + this.response.getWriter().println(c); - verify(writer).println(c); + verify(this.writer).println(c); } @Test public void printWriterPrintlnInt() throws Exception { int i = 1; - response.getWriter().println(i); + this.response.getWriter().println(i); - verify(writer).println(i); + verify(this.writer).println(i); } @Test public void printWriterPrintlnLong() throws Exception { long l = 1; - response.getWriter().println(l); + this.response.getWriter().println(l); - verify(writer).println(l); + verify(this.writer).println(l); } @Test public void printWriterPrintlnFloat() throws Exception { float f = 1; - response.getWriter().println(f); + this.response.getWriter().println(f); - verify(writer).println(f); + verify(this.writer).println(f); } @Test public void printWriterPrintlnDouble() throws Exception { double x = 1; - response.getWriter().println(x); + this.response.getWriter().println(x); - verify(writer).println(x); + verify(this.writer).println(x); } @Test public void printWriterPrintlnCharArray() throws Exception { char[] x = new char[0]; - response.getWriter().println(x); + this.response.getWriter().println(x); - verify(writer).println(x); + verify(this.writer).println(x); } @Test public void printWriterPrintlnString() throws Exception { String x = "1"; - response.getWriter().println(x); + this.response.getWriter().println(x); - verify(writer).println(x); + verify(this.writer).println(x); } @Test public void printWriterPrintlnObject() throws Exception { Object x = "1"; - response.getWriter().println(x); + this.response.getWriter().println(x); - verify(writer).println(x); + verify(this.writer).println(x); } @Test @@ -300,9 +301,9 @@ public class OnCommittedResponseWrapperTests { String format = "format"; Object[] args = new Object[] { "1" }; - response.getWriter().printf(format, args); + this.response.getWriter().printf(format, args); - verify(writer).printf(format, args); + verify(this.writer).printf(format, args); } @Test @@ -311,9 +312,9 @@ public class OnCommittedResponseWrapperTests { String format = "format"; Object[] args = new Object[] { "1" }; - response.getWriter().printf(l, format, args); + this.response.getWriter().printf(l, format, args); - verify(writer).printf(l, format, args); + verify(this.writer).printf(l, format, args); } @Test @@ -321,9 +322,9 @@ public class OnCommittedResponseWrapperTests { String format = "format"; Object[] args = new Object[] { "1" }; - response.getWriter().format(format, args); + this.response.getWriter().format(format, args); - verify(writer).format(format, args); + verify(this.writer).format(format, args); } @Test @@ -332,9 +333,9 @@ public class OnCommittedResponseWrapperTests { String format = "format"; Object[] args = new Object[] { "1" }; - response.getWriter().format(l, format, args); + this.response.getWriter().format(l, format, args); - verify(writer).format(l, format, args); + verify(this.writer).format(l, format, args); } @@ -342,9 +343,9 @@ public class OnCommittedResponseWrapperTests { public void printWriterAppendCharSequence() throws Exception { String x = "a"; - response.getWriter().append(x); + this.response.getWriter().append(x); - verify(writer).append(x); + verify(this.writer).append(x); } @Test @@ -353,9 +354,9 @@ public class OnCommittedResponseWrapperTests { int start = 1; int end = 3; - response.getWriter().append(x, start, end); + this.response.getWriter().append(x, start, end); - verify(writer).append(x, start, end); + verify(this.writer).append(x, start, end); } @@ -363,9 +364,9 @@ public class OnCommittedResponseWrapperTests { public void printWriterAppendChar() throws Exception { char x = 1; - response.getWriter().append(x); + this.response.getWriter().append(x); - verify(writer).append(x); + verify(this.writer).append(x); } // servletoutputstream @@ -373,27 +374,27 @@ public class OnCommittedResponseWrapperTests { @Test public void outputStreamHashCode() throws Exception { - int expected = out.hashCode(); + int expected = this.out.hashCode(); - assertThat(response.getOutputStream().hashCode()).isEqualTo(expected); + assertThat(this.response.getOutputStream().hashCode()).isEqualTo(expected); } @Test public void outputStreamWriteInt() throws Exception { int expected = 1; - response.getOutputStream().write(expected); + this.response.getOutputStream().write(expected); - verify(out).write(expected); + verify(this.out).write(expected); } @Test public void outputStreamWriteByte() throws Exception { byte[] expected = new byte[0]; - response.getOutputStream().write(expected); + this.response.getOutputStream().write(expected); - verify(out).write(expected); + verify(this.out).write(expected); } @Test @@ -402,142 +403,142 @@ public class OnCommittedResponseWrapperTests { int end = 2; byte[] expected = new byte[0]; - response.getOutputStream().write(expected, start, end); + this.response.getOutputStream().write(expected, start, end); - verify(out).write(expected, start, end); + verify(this.out).write(expected, start, end); } @Test public void outputStreamPrintBoolean() throws Exception { boolean b = true; - response.getOutputStream().print(b); + this.response.getOutputStream().print(b); - verify(out).print(b); + verify(this.out).print(b); } @Test public void outputStreamPrintChar() throws Exception { char c = 1; - response.getOutputStream().print(c); + this.response.getOutputStream().print(c); - verify(out).print(c); + verify(this.out).print(c); } @Test public void outputStreamPrintInt() throws Exception { int i = 1; - response.getOutputStream().print(i); + this.response.getOutputStream().print(i); - verify(out).print(i); + verify(this.out).print(i); } @Test public void outputStreamPrintLong() throws Exception { long l = 1; - response.getOutputStream().print(l); + this.response.getOutputStream().print(l); - verify(out).print(l); + verify(this.out).print(l); } @Test public void outputStreamPrintFloat() throws Exception { float f = 1; - response.getOutputStream().print(f); + this.response.getOutputStream().print(f); - verify(out).print(f); + verify(this.out).print(f); } @Test public void outputStreamPrintDouble() throws Exception { double x = 1; - response.getOutputStream().print(x); + this.response.getOutputStream().print(x); - verify(out).print(x); + verify(this.out).print(x); } @Test public void outputStreamPrintString() throws Exception { String x = "1"; - response.getOutputStream().print(x); + this.response.getOutputStream().print(x); - verify(out).print(x); + verify(this.out).print(x); } @Test public void outputStreamPrintln() throws Exception { - response.getOutputStream().println(); + this.response.getOutputStream().println(); - verify(out).println(); + verify(this.out).println(); } @Test public void outputStreamPrintlnBoolean() throws Exception { boolean b = true; - response.getOutputStream().println(b); + this.response.getOutputStream().println(b); - verify(out).println(b); + verify(this.out).println(b); } @Test public void outputStreamPrintlnChar() throws Exception { char c = 1; - response.getOutputStream().println(c); + this.response.getOutputStream().println(c); - verify(out).println(c); + verify(this.out).println(c); } @Test public void outputStreamPrintlnInt() throws Exception { int i = 1; - response.getOutputStream().println(i); + this.response.getOutputStream().println(i); - verify(out).println(i); + verify(this.out).println(i); } @Test public void outputStreamPrintlnLong() throws Exception { long l = 1; - response.getOutputStream().println(l); + this.response.getOutputStream().println(l); - verify(out).println(l); + verify(this.out).println(l); } @Test public void outputStreamPrintlnFloat() throws Exception { float f = 1; - response.getOutputStream().println(f); + this.response.getOutputStream().println(f); - verify(out).println(f); + verify(this.out).println(f); } @Test public void outputStreamPrintlnDouble() throws Exception { double x = 1; - response.getOutputStream().println(x); + this.response.getOutputStream().println(x); - verify(out).println(x); + verify(this.out).println(x); } @Test public void outputStreamPrintlnString() throws Exception { String x = "1"; - response.getOutputStream().println(x); + this.response.getOutputStream().println(x); - verify(out).println(x); + verify(this.out).println(x); } // The amount of content specified in the setContentLength method of the response @@ -546,35 +547,35 @@ public class OnCommittedResponseWrapperTests { @Test public void contentLengthPrintWriterWriteIntCommits() throws Exception { int expected = 1; - response.setContentLength(String.valueOf(expected).length()); + this.response.setContentLength(String.valueOf(expected).length()); - response.getWriter().write(expected); + this.response.getWriter().write(expected); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteIntMultiDigitCommits() throws Exception { int expected = 10000; - response.setContentLength(String.valueOf(expected).length()); + this.response.setContentLength(String.valueOf(expected).length()); - response.getWriter().write(expected); + this.response.getWriter().write(expected); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPlus1PrintWriterWriteIntMultiDigitCommits() throws Exception { int expected = 10000; - response.setContentLength(String.valueOf(expected).length() + 1); + this.response.setContentLength(String.valueOf(expected).length() + 1); - response.getWriter().write(expected); + this.response.getWriter().write(expected); - assertThat(committed).isFalse(); + assertThat(this.committed).isFalse(); - response.getWriter().write(1); + this.response.getWriter().write(1); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @@ -583,21 +584,21 @@ public class OnCommittedResponseWrapperTests { char[] buff = new char[0]; int off = 2; int len = 3; - response.setContentLength(3); + this.response.setContentLength(3); - response.getWriter().write(buff,off,len); + this.response.getWriter().write(buff, off, len); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteCharCommits() throws Exception { char[] buff = new char[4]; - response.setContentLength(buff.length); + this.response.setContentLength(buff.length); - response.getWriter().write(buff); + this.response.getWriter().write(buff); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test @@ -605,240 +606,240 @@ public class OnCommittedResponseWrapperTests { String s = ""; int off = 2; int len = 3; - response.setContentLength(3); + this.response.setContentLength(3); - response.getWriter().write(s,off,len); + this.response.getWriter().write(s, off, len); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteStringCommits() throws IOException { String body = "something"; - response.setContentLength(body.length()); + this.response.setContentLength(body.length()); - response.getWriter().write(body); + this.response.getWriter().write(body); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void printWriterWriteStringContentLengthCommits() throws IOException { String body = "something"; - response.getWriter().write(body); + this.response.getWriter().write(body); - response.setContentLength(body.length()); + this.response.setContentLength(body.length()); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void printWriterWriteStringDoesNotCommit() throws IOException { String body = "something"; - response.getWriter().write(body); + this.response.getWriter().write(body); - assertThat(committed).isFalse(); + assertThat(this.committed).isFalse(); } @Test public void contentLengthPrintWriterPrintBooleanCommits() throws Exception { boolean b = true; - response.setContentLength(1); + this.response.setContentLength(1); - response.getWriter().print(b); + this.response.getWriter().print(b); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintCharCommits() throws Exception { char c = 1; - response.setContentLength(1); + this.response.setContentLength(1); - response.getWriter().print(c); + this.response.getWriter().print(c); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintIntCommits() throws Exception { int i = 1234; - response.setContentLength(String.valueOf(i).length()); + this.response.setContentLength(String.valueOf(i).length()); - response.getWriter().print(i); + this.response.getWriter().print(i); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintLongCommits() throws Exception { long l = 12345; - response.setContentLength(String.valueOf(l).length()); + this.response.setContentLength(String.valueOf(l).length()); - response.getWriter().print(l); + this.response.getWriter().print(l); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintFloatCommits() throws Exception { float f = 12345; - response.setContentLength(String.valueOf(f).length()); + this.response.setContentLength(String.valueOf(f).length()); - response.getWriter().print(f); + this.response.getWriter().print(f); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintDoubleCommits() throws Exception { double x = 1.2345; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getWriter().print(x); + this.response.getWriter().print(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintCharArrayCommits() throws Exception { char[] x = new char[10]; - response.setContentLength(x.length); + this.response.setContentLength(x.length); - response.getWriter().print(x); + this.response.getWriter().print(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintStringCommits() throws Exception { String x = "12345"; - response.setContentLength(x.length()); + this.response.setContentLength(x.length()); - response.getWriter().print(x); + this.response.getWriter().print(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintObjectCommits() throws Exception { Object x = "12345"; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getWriter().print(x); + this.response.getWriter().print(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnCommits() throws Exception { - response.setContentLength(NL.length()); + this.response.setContentLength(NL.length()); - response.getWriter().println(); + this.response.getWriter().println(); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnBooleanCommits() throws Exception { boolean b = true; - response.setContentLength(1); + this.response.setContentLength(1); - response.getWriter().println(b); + this.response.getWriter().println(b); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnCharCommits() throws Exception { char c = 1; - response.setContentLength(1); + this.response.setContentLength(1); - response.getWriter().println(c); + this.response.getWriter().println(c); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnIntCommits() throws Exception { int i = 12345; - response.setContentLength(String.valueOf(i).length()); + this.response.setContentLength(String.valueOf(i).length()); - response.getWriter().println(i); + this.response.getWriter().println(i); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnLongCommits() throws Exception { long l = 12345678; - response.setContentLength(String.valueOf(l).length()); + this.response.setContentLength(String.valueOf(l).length()); - response.getWriter().println(l); + this.response.getWriter().println(l); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnFloatCommits() throws Exception { float f = 1234; - response.setContentLength(String.valueOf(f).length()); + this.response.setContentLength(String.valueOf(f).length()); - response.getWriter().println(f); + this.response.getWriter().println(f); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnDoubleCommits() throws Exception { double x = 1; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getWriter().println(x); + this.response.getWriter().println(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnCharArrayCommits() throws Exception { char[] x = new char[20]; - response.setContentLength(x.length); + this.response.setContentLength(x.length); - response.getWriter().println(x); + this.response.getWriter().println(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnStringCommits() throws Exception { String x = "1"; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getWriter().println(x); + this.response.getWriter().println(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnObjectCommits() throws Exception { Object x = "1"; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getWriter().println(x); + this.response.getWriter().println(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterAppendCharSequenceCommits() throws Exception { String x = "a"; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getWriter().append(x); + this.response.getWriter().append(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test @@ -846,55 +847,55 @@ public class OnCommittedResponseWrapperTests { String x = "abcdef"; int start = 1; int end = 3; - response.setContentLength(end - start); + this.response.setContentLength(end - start); - response.getWriter().append(x, start, end); + this.response.getWriter().append(x, start, end); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterAppendCharCommits() throws Exception { char x = 1; - response.setContentLength(1); + this.response.setContentLength(1); - response.getWriter().append(x); + this.response.getWriter().append(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamWriteIntCommits() throws Exception { int expected = 1; - response.setContentLength(String.valueOf(expected).length()); + this.response.setContentLength(String.valueOf(expected).length()); - response.getOutputStream().write(expected); + this.response.getOutputStream().write(expected); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamWriteIntMultiDigitCommits() throws Exception { int expected = 10000; - response.setContentLength(String.valueOf(expected).length()); + this.response.setContentLength(String.valueOf(expected).length()); - response.getOutputStream().write(expected); + this.response.getOutputStream().write(expected); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthPlus1OutputStreamWriteIntMultiDigitCommits() throws Exception { int expected = 10000; - response.setContentLength(String.valueOf(expected).length() + 1); + this.response.setContentLength(String.valueOf(expected).length() + 1); - response.getOutputStream().write(expected); + this.response.getOutputStream().write(expected); - assertThat(committed).isFalse(); + assertThat(this.committed).isFalse(); - response.getOutputStream().write(1); + this.response.getOutputStream().write(1); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } // gh-171 @@ -905,218 +906,218 @@ public class OnCommittedResponseWrapperTests { " \"token\" : \"06300b65-c4aa-4c8f-8cda-39ee17f545a0\",\n" + " \"headerName\" : \"X-CSRF-TOKEN\"\n" + "}"; - response.setContentLength(expected.length() + 1); + this.response.setContentLength(expected.length() + 1); - response.getOutputStream().write(expected.getBytes()); + this.response.getOutputStream().write(expected.getBytes()); - assertThat(committed).isFalse(); + assertThat(this.committed).isFalse(); - response.getOutputStream().write("1".getBytes("UTF-8")); + this.response.getOutputStream().write("1".getBytes("UTF-8")); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintBooleanCommits() throws Exception { boolean b = true; - response.setContentLength(1); + this.response.setContentLength(1); - response.getOutputStream().print(b); + this.response.getOutputStream().print(b); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintCharCommits() throws Exception { char c = 1; - response.setContentLength(1); + this.response.setContentLength(1); - response.getOutputStream().print(c); + this.response.getOutputStream().print(c); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintIntCommits() throws Exception { int i = 1234; - response.setContentLength(String.valueOf(i).length()); + this.response.setContentLength(String.valueOf(i).length()); - response.getOutputStream().print(i); + this.response.getOutputStream().print(i); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintLongCommits() throws Exception { long l = 12345; - response.setContentLength(String.valueOf(l).length()); + this.response.setContentLength(String.valueOf(l).length()); - response.getOutputStream().print(l); + this.response.getOutputStream().print(l); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintFloatCommits() throws Exception { float f = 12345; - response.setContentLength(String.valueOf(f).length()); + this.response.setContentLength(String.valueOf(f).length()); - response.getOutputStream().print(f); + this.response.getOutputStream().print(f); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintDoubleCommits() throws Exception { double x = 1.2345; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getOutputStream().print(x); + this.response.getOutputStream().print(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintStringCommits() throws Exception { String x = "12345"; - response.setContentLength(x.length()); + this.response.setContentLength(x.length()); - response.getOutputStream().print(x); + this.response.getOutputStream().print(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnCommits() throws Exception { - response.setContentLength(NL.length()); + this.response.setContentLength(NL.length()); - response.getOutputStream().println(); + this.response.getOutputStream().println(); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnBooleanCommits() throws Exception { boolean b = true; - response.setContentLength(1); + this.response.setContentLength(1); - response.getOutputStream().println(b); + this.response.getOutputStream().println(b); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnCharCommits() throws Exception { char c = 1; - response.setContentLength(1); + this.response.setContentLength(1); - response.getOutputStream().println(c); + this.response.getOutputStream().println(c); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnIntCommits() throws Exception { int i = 12345; - response.setContentLength(String.valueOf(i).length()); + this.response.setContentLength(String.valueOf(i).length()); - response.getOutputStream().println(i); + this.response.getOutputStream().println(i); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnLongCommits() throws Exception { long l = 12345678; - response.setContentLength(String.valueOf(l).length()); + this.response.setContentLength(String.valueOf(l).length()); - response.getOutputStream().println(l); + this.response.getOutputStream().println(l); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnFloatCommits() throws Exception { float f = 1234; - response.setContentLength(String.valueOf(f).length()); + this.response.setContentLength(String.valueOf(f).length()); - response.getOutputStream().println(f); + this.response.getOutputStream().println(f); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnDoubleCommits() throws Exception { double x = 1; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getOutputStream().println(x); + this.response.getOutputStream().println(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnStringCommits() throws Exception { String x = "1"; - response.setContentLength(String.valueOf(x).length()); + this.response.setContentLength(String.valueOf(x).length()); - response.getOutputStream().println(x); + this.response.getOutputStream().println(x); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void contentLengthDoesNotCommit() throws IOException { String body = "something"; - response.setContentLength(body.length()); + this.response.setContentLength(body.length()); - assertThat(committed).isFalse(); + assertThat(this.committed).isFalse(); } @Test public void contentLengthOutputStreamWriteStringCommits() throws IOException { String body = "something"; - response.setContentLength(body.length()); + this.response.setContentLength(body.length()); - response.getOutputStream().print(body); + this.response.getOutputStream().print(body); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void addHeaderContentLengthPrintWriterWriteStringCommits() throws Exception { int expected = 1234; - response.addHeader("Content-Length",String.valueOf(String.valueOf(expected).length())); + this.response.addHeader("Content-Length", String.valueOf(String.valueOf(expected).length())); - response.getWriter().write(expected); + this.response.getWriter().write(expected); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void bufferSizePrintWriterWriteCommits() throws Exception { String expected = "1234567890"; - when(response.getBufferSize()).thenReturn(expected.length()); + given(this.response.getBufferSize()).willReturn(expected.length()); - response.getWriter().write(expected); + this.response.getWriter().write(expected); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); } @Test public void bufferSizeCommitsOnce() throws Exception { String expected = "1234567890"; - when(response.getBufferSize()).thenReturn(expected.length()); + given(this.response.getBufferSize()).willReturn(expected.length()); - response.getWriter().write(expected); + this.response.getWriter().write(expected); - assertThat(committed).isTrue(); + assertThat(this.committed).isTrue(); - committed = false; + this.committed = false; - response.getWriter().write(expected); + this.response.getWriter().write(expected); - assertThat(committed).isFalse(); + assertThat(this.committed).isFalse(); } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/web/http/OncePerRequestFilterTests.java b/spring-session/src/test/java/org/springframework/session/web/http/OncePerRequestFilterTests.java index 18a43bcb..048e4b5e 100644 --- a/spring-session/src/test/java/org/springframework/session/web/http/OncePerRequestFilterTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/http/OncePerRequestFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.session.web.http; -import org.junit.Before; -import org.junit.Test; -import org.springframework.mock.web.MockFilterChain; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.session.web.http.OncePerRequestFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -28,11 +26,14 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; +import org.junit.Before; +import org.junit.Test; -import static org.assertj.core.api.Assertions.*; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.assertj.core.api.Assertions.assertThat; public class OncePerRequestFilterTests { private MockHttpServletRequest request; @@ -47,15 +48,16 @@ public class OncePerRequestFilterTests { @Before @SuppressWarnings("serial") public void setup() { - servlet = new HttpServlet() {}; - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - chain = new MockFilterChain(); - invocations = new ArrayList(); - filter = new OncePerRequestFilter() { + this.servlet = new HttpServlet() { + }; + this.request = new MockHttpServletRequest(); + this.response = new MockHttpServletResponse(); + this.chain = new MockFilterChain(); + this.invocations = new ArrayList(); + this.filter = new OncePerRequestFilter() { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - invocations.add(this); + OncePerRequestFilterTests.this.invocations.add(this); filterChain.doFilter(request, response); } }; @@ -63,16 +65,16 @@ public class OncePerRequestFilterTests { @Test public void doFilterOnce() throws ServletException, IOException { - filter.doFilter(request, response, chain); + this.filter.doFilter(this.request, this.response, this.chain); - assertThat(invocations).containsOnly(filter); + assertThat(this.invocations).containsOnly(this.filter); } @Test public void doFilterMultiOnlyIvokesOnce() throws ServletException, IOException { - filter.doFilter(request, response, new MockFilterChain(servlet, filter)); + this.filter.doFilter(this.request, this.response, new MockFilterChain(this.servlet, this.filter)); - assertThat(invocations).containsOnly(filter); + assertThat(this.invocations).containsOnly(this.filter); } @Test @@ -80,12 +82,12 @@ public class OncePerRequestFilterTests { OncePerRequestFilter filter2 = new OncePerRequestFilter() { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - invocations.add(this); + OncePerRequestFilterTests.this.invocations.add(this); filterChain.doFilter(request, response); } }; - filter.doFilter(request, response, new MockFilterChain(servlet, filter2)); + this.filter.doFilter(this.request, this.response, new MockFilterChain(this.servlet, filter2)); - assertThat(invocations).containsOnly(filter, filter2); + assertThat(this.invocations).containsOnly(this.filter, filter2); } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapterTests.java b/spring-session/src/test/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapterTests.java index 11fbd980..3679607f 100644 --- a/spring-session/src/test/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapterTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.web.http; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.*; +package org.springframework.session.web.http; import java.util.Arrays; import java.util.Collections; @@ -32,11 +30,17 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.session.MapSession; import org.springframework.session.Session; import org.springframework.session.events.SessionCreatedEvent; import org.springframework.session.events.SessionDestroyedEvent; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + /** * @author Rob Winch * @since 1.1 @@ -58,11 +62,11 @@ public class SessionEventHttpSessionListenerAdapterTests { @Before public void setup() { - this.listener = new SessionEventHttpSessionListenerAdapter(Arrays.asList(listener1, listener2)); + this.listener = new SessionEventHttpSessionListenerAdapter(Arrays.asList(this.listener1, this.listener2)); Session session = new MapSession(); - destroyed = new SessionDestroyedEvent(this, session); - created = new SessionCreatedEvent(this, session); + this.destroyed = new SessionDestroyedEvent(this, session); + this.created = new SessionCreatedEvent(this, session); } // We want relaxed constructor that will allow for an empty listeners to @@ -77,31 +81,31 @@ public class SessionEventHttpSessionListenerAdapterTests { */ @Test public void onApplicationEventEmptyListenersDoesNotUseEvent() { - listener = new SessionEventHttpSessionListenerAdapter(Collections.emptyList()); - destroyed = mock(SessionDestroyedEvent.class); + this.listener = new SessionEventHttpSessionListenerAdapter(Collections.emptyList()); + this.destroyed = mock(SessionDestroyedEvent.class); - listener.onApplicationEvent(destroyed); + this.listener.onApplicationEvent(this.destroyed); - verifyZeroInteractions(destroyed, listener1, listener2); + verifyZeroInteractions(this.destroyed, this.listener1, this.listener2); } @Test public void onApplicationEventDestroyed() { - listener.onApplicationEvent(destroyed); + this.listener.onApplicationEvent(this.destroyed); - verify(listener1).sessionDestroyed(sessionEvent.capture()); - verify(listener2).sessionDestroyed(sessionEvent.capture()); + verify(this.listener1).sessionDestroyed(this.sessionEvent.capture()); + verify(this.listener2).sessionDestroyed(this.sessionEvent.capture()); - assertThat(sessionEvent.getValue().getSession().getId()).isEqualTo(destroyed.getSessionId()); + assertThat(this.sessionEvent.getValue().getSession().getId()).isEqualTo(this.destroyed.getSessionId()); } @Test public void onApplicationEventCreated() { - listener.onApplicationEvent(created); + this.listener.onApplicationEvent(this.created); - verify(listener1).sessionCreated(sessionEvent.capture()); - verify(listener2).sessionCreated(sessionEvent.capture()); + verify(this.listener1).sessionCreated(this.sessionEvent.capture()); + verify(this.listener2).sessionCreated(this.sessionEvent.capture()); - assertThat(sessionEvent.getValue().getSession().getId()).isEqualTo(created.getSessionId()); + assertThat(this.sessionEvent.getValue().getSession().getId()).isEqualTo(this.created.getSessionId()); } } diff --git a/spring-session/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java b/spring-session/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java index e301bd20..75bc801d 100644 --- a/spring-session/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.web.http; -import static org.assertj.core.api.Assertions.*; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; +package org.springframework.session.web.http; import java.io.IOException; import java.util.ArrayList; @@ -50,6 +40,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.mock.web.MockFilterChain; @@ -63,6 +54,17 @@ import org.springframework.session.Session; import org.springframework.session.SessionRepository; import org.springframework.test.util.ReflectionTestUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + @RunWith(MockitoJUnitRunner.class) @SuppressWarnings("deprecation") public class SessionRepositoryFilterTests { @@ -83,9 +85,9 @@ public class SessionRepositoryFilterTests { @Before public void setup() throws Exception { - sessions = new HashMap(); - sessionRepository = new MapSessionRepository(sessions); - filter = new SessionRepositoryFilter(sessionRepository); + this.sessions = new HashMap(); + this.sessionRepository = new MapSessionRepository(this.sessions); + this.filter = new SessionRepositoryFilter(this.sessionRepository); setupRequest(); } @@ -98,11 +100,11 @@ public class SessionRepositoryFilterTests { long creationTime = wrappedRequest.getSession().getCreationTime(); long now = System.currentTimeMillis(); assertThat(now - creationTime).isGreaterThanOrEqualTo(0).isLessThan(5000); - request.setAttribute(CREATE_ATTR, creationTime); + SessionRepositoryFilterTests.this.request.setAttribute(CREATE_ATTR, creationTime); } }); - final long expectedCreationTime = (Long) request.getAttribute(CREATE_ATTR); + final long expectedCreationTime = (Long) this.request.getAttribute(CREATE_ATTR); Thread.sleep(50L); nextRequest(); @@ -121,8 +123,8 @@ public class SessionRepositoryFilterTests { MapSession session = new MapSession(); session.setLastAccessedTime(0L); this.sessionRepository = spy(this.sessionRepository); - when(this.sessionRepository.createSession()).thenReturn(session); - this.filter = new SessionRepositoryFilter(sessionRepository); + given(this.sessionRepository.createSession()).willReturn(session); + this.filter = new SessionRepositoryFilter(this.sessionRepository); doFilter(new DoInFilter() { @Override @@ -144,7 +146,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest) { long lastAccessed = wrappedRequest.getSession().getLastAccessedTime(); assertThat(lastAccessed).isEqualTo(wrappedRequest.getSession().getCreationTime()); - request.setAttribute(ACCESS_ATTR, lastAccessed); + SessionRepositoryFilterTests.this.request.setAttribute(ACCESS_ATTR, lastAccessed); } }); @@ -170,11 +172,11 @@ public class SessionRepositoryFilterTests { String id = wrappedRequest.getSession().getId(); assertThat(id).isNotNull(); assertThat(wrappedRequest.getSession().getId()).isEqualTo(id); - request.setAttribute(ID_ATTR, id); + SessionRepositoryFilterTests.this.request.setAttribute(ID_ATTR, id); } }); - final String id = (String) request.getAttribute(ID_ATTR); + final String id = (String) this.request.getAttribute(ID_ATTR); assertThat(getSessionCookie().getValue()).isEqualTo(id); setSessionCookie(id); @@ -193,11 +195,11 @@ public class SessionRepositoryFilterTests { @Override public void doFilter(HttpServletRequest wrappedRequest) { String id = wrappedRequest.getSession().getId(); - request.setAttribute(ID_ATTR, id); + SessionRepositoryFilterTests.this.request.setAttribute(ID_ATTR, id); } }); - final String id = (String) request.getAttribute(ID_ATTR); + final String id = (String) this.request.getAttribute(ID_ATTR); setupRequest(); doFilter(new DoInFilter() { @@ -223,8 +225,8 @@ public class SessionRepositoryFilterTests { @Test public void doFilterServletContextExplicit() throws Exception { final ServletContext expectedContext = new MockServletContext(); - filter = new SessionRepositoryFilter(sessionRepository); - filter.setServletContext(expectedContext); + this.filter = new SessionRepositoryFilter(this.sessionRepository); + this.filter.setServletContext(expectedContext); doFilter(new DoInFilter() { @Override @@ -380,7 +382,7 @@ public class SessionRepositoryFilterTests { }); nextRequest(); - response.reset(); + this.response.reset(); doFilter(new DoInFilter() { @Override @@ -389,29 +391,29 @@ public class SessionRepositoryFilterTests { } }); - assertThat(response.getCookie("SESSION")).isNull(); + assertThat(this.response.getCookie("SESSION")).isNull(); } @Test public void doFilterSetsCookieIfChanged() throws Exception { - sessionRepository = new MapSessionRepository() { + this.sessionRepository = new MapSessionRepository() { @Override public ExpiringSession getSession(String id) { return createSession(); } }; - filter = new SessionRepositoryFilter(sessionRepository); + this.filter = new SessionRepositoryFilter(this.sessionRepository); doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { wrappedRequest.getSession(); } }); - assertThat(response.getCookie("SESSION")).isNotNull(); + assertThat(this.response.getCookie("SESSION")).isNotNull(); nextRequest(); - response.reset(); + this.response.reset(); doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -419,7 +421,7 @@ public class SessionRepositoryFilterTests { } }); - assertThat(response.getCookie("SESSION")).isNotNull(); + assertThat(this.response.getCookie("SESSION")).isNotNull(); } @Test @@ -468,7 +470,7 @@ public class SessionRepositoryFilterTests { }); nextRequest(); - request.setRequestedSessionIdValid(false); // ensure we are using wrapped request + this.request.setRequestedSessionIdValid(false); // ensure we are using wrapped request doFilter(new DoInFilter() { @Override @@ -511,7 +513,7 @@ public class SessionRepositoryFilterTests { // the old session was removed final String changedSessionId = getSessionCookie().getValue(); assertThat(originalSessionId).isNotEqualTo(changedSessionId); - assertThat(sessionRepository.getSession(originalSessionId)).isNull(); + assertThat(this.sessionRepository.getSession(originalSessionId)).isNull(); nextRequest(); @@ -533,7 +535,9 @@ public class SessionRepositoryFilterTests { try { ReflectionTestUtils.invokeMethod(wrappedRequest, "changeSessionId"); fail("Exected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -542,7 +546,7 @@ public class SessionRepositoryFilterTests { @Test public void doFilterIsRequestedValidSessionFalseInvalidId() throws Exception { setSessionCookie("invalid"); - request.setRequestedSessionIdValid(true); // ensure we are using wrapped request + this.request.setRequestedSessionIdValid(true); // ensure we are using wrapped request doFilter(new DoInFilter() { @Override @@ -554,7 +558,7 @@ public class SessionRepositoryFilterTests { @Test public void doFilterIsRequestedValidSessionFalse() throws Exception { - request.setRequestedSessionIdValid(true); // ensure we are using wrapped request + this.request.setRequestedSessionIdValid(true); // ensure we are using wrapped request doFilter(new DoInFilter() { @Override @@ -607,7 +611,7 @@ public class SessionRepositoryFilterTests { @Test public void doFilterCookieSecuritySettings() throws Exception { - request.setSecure(true); + this.request.setSecure(true); doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -634,7 +638,9 @@ public class SessionRepositoryFilterTests { try { sessionContext.getIds().nextElement(); fail("Expected Exception"); - } catch(NoSuchElementException success) {} + } + catch (NoSuchElementException success) { + } } }); } @@ -683,7 +689,9 @@ public class SessionRepositoryFilterTests { try { session.invalidate(); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -698,7 +706,9 @@ public class SessionRepositoryFilterTests { try { session.getCreationTime(); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -713,7 +723,9 @@ public class SessionRepositoryFilterTests { try { session.getAttribute("attr"); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -728,7 +740,9 @@ public class SessionRepositoryFilterTests { try { session.getValue("attr"); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -743,7 +757,9 @@ public class SessionRepositoryFilterTests { try { session.getAttributeNames(); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -758,7 +774,9 @@ public class SessionRepositoryFilterTests { try { session.getValueNames(); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -773,7 +791,9 @@ public class SessionRepositoryFilterTests { try { session.setAttribute("a", "b"); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -788,7 +808,9 @@ public class SessionRepositoryFilterTests { try { session.putValue("a", "b"); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -803,7 +825,9 @@ public class SessionRepositoryFilterTests { try { session.removeAttribute("name"); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -818,7 +842,9 @@ public class SessionRepositoryFilterTests { try { session.removeValue("name"); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -833,7 +859,9 @@ public class SessionRepositoryFilterTests { try { session.isNew(); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -848,7 +876,9 @@ public class SessionRepositoryFilterTests { try { session.getLastAccessedTime(); fail("Expected Exception"); - } catch(IllegalStateException success) {} + } + catch (IllegalStateException success) { + } } }); } @@ -988,7 +1018,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - assertThat(sessionRepository.getSession(id)).isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull(); } }); } @@ -1000,7 +1030,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error"); - assertThat(sessionRepository.getSession(id)).isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull(); } }); } @@ -1012,7 +1042,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.sendRedirect("/"); - assertThat(sessionRepository.getSession(id)).isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull(); } }); } @@ -1024,7 +1054,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.flushBuffer(); - assertThat(sessionRepository.getSession(id)).isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull(); } }); } @@ -1036,7 +1066,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.getOutputStream().flush(); - assertThat(sessionRepository.getSession(id)).isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull(); } }); } @@ -1048,7 +1078,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.getOutputStream().close(); - assertThat(sessionRepository.getSession(id)).isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull(); } }); } @@ -1060,7 +1090,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.getWriter().flush(); - assertThat(sessionRepository.getSession(id)).isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull(); } }); } @@ -1072,7 +1102,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.getWriter().close(); - assertThat(sessionRepository.getSession(id)).isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.getSession(id)).isNotNull(); } }); } @@ -1081,11 +1111,11 @@ public class SessionRepositoryFilterTests { @Test public void doFilterAdapterGetRequestedSessionId() throws Exception { - filter.setHttpSessionStrategy(strategy); + this.filter.setHttpSessionStrategy(this.strategy); final String expectedId = "MultiHttpSessionStrategyAdapter-requested-id"; - when(strategy.getRequestedSessionId(any(HttpServletRequest.class))).thenReturn(expectedId); + given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(expectedId); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { String actualId = wrappedRequest.getRequestedSessionId(); @@ -1096,69 +1126,69 @@ public class SessionRepositoryFilterTests { @Test public void doFilterAdapterOnNewSession() throws Exception { - filter.setHttpSessionStrategy(strategy); + this.filter.setHttpSessionStrategy(this.strategy); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { wrappedRequest.getSession(); } }); - HttpServletRequest request = (HttpServletRequest) chain.getRequest(); - Session session = sessionRepository.getSession(request.getSession().getId()); - verify(strategy).onNewSession(eq(session), any(HttpServletRequest.class),any(HttpServletResponse.class)); + HttpServletRequest request = (HttpServletRequest) this.chain.getRequest(); + Session session = this.sessionRepository.getSession(request.getSession().getId()); + verify(this.strategy).onNewSession(eq(session), any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void doFilterAdapterOnInvalidate() throws Exception { - filter.setHttpSessionStrategy(strategy); + this.filter.setHttpSessionStrategy(this.strategy); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { wrappedRequest.getSession().getId(); } }); - HttpServletRequest request = (HttpServletRequest) chain.getRequest(); + HttpServletRequest request = (HttpServletRequest) this.chain.getRequest(); String id = request.getSession().getId(); - when(strategy.getRequestedSessionId(any(HttpServletRequest.class))).thenReturn(id); + given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(id); setupRequest(); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { wrappedRequest.getSession().invalidate(); } }); - verify(strategy).onInvalidateSession(any(HttpServletRequest.class),any(HttpServletResponse.class)); + verify(this.strategy).onInvalidateSession(any(HttpServletRequest.class), any(HttpServletResponse.class)); } // gh-188 @Test public void doFilterRequestSessionNoRequestSessionDoesNotInvalidate() throws Exception { - filter.setHttpSessionStrategy(strategy); + this.filter.setHttpSessionStrategy(this.strategy); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { wrappedRequest.getSession().getId(); } }); - HttpServletRequest request = (HttpServletRequest) chain.getRequest(); + HttpServletRequest request = (HttpServletRequest) this.chain.getRequest(); String id = request.getSession().getId(); - when(strategy.getRequestedSessionId(any(HttpServletRequest.class))).thenReturn(id); + given(this.strategy.getRequestedSessionId(any(HttpServletRequest.class))).willReturn(id); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { } }); - verify(strategy,never()).onInvalidateSession(any(HttpServletRequest.class),any(HttpServletResponse.class)); + verify(this.strategy, never()).onInvalidateSession(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test @@ -1166,9 +1196,9 @@ public class SessionRepositoryFilterTests { public void doFilterRequestSessionNoRequestSessionNoSessionRepositoryInteractions() throws Exception { SessionRepository sessionRepository = spy(new MapSessionRepository()); - filter = new SessionRepositoryFilter(sessionRepository); + this.filter = new SessionRepositoryFilter(sessionRepository); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { wrappedRequest.getSession().getId(); @@ -1178,7 +1208,7 @@ public class SessionRepositoryFilterTests { reset(sessionRepository); setupRequest(); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { } @@ -1191,9 +1221,9 @@ public class SessionRepositoryFilterTests { public void doFilterLazySessionCreation() throws Exception { SessionRepository sessionRepository = spy(new MapSessionRepository()); - filter = new SessionRepositoryFilter(sessionRepository); + this.filter = new SessionRepositoryFilter(sessionRepository); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { } @@ -1209,9 +1239,9 @@ public class SessionRepositoryFilterTests { SessionRepository sessionRepository = spy(this.sessionRepository); setSessionCookie(session.getId()); - filter = new SessionRepositoryFilter(sessionRepository); + this.filter = new SessionRepositoryFilter(sessionRepository); - doFilter(new DoInFilter(){ + doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException { } @@ -1224,24 +1254,24 @@ public class SessionRepositoryFilterTests { @Test public void order() { - assertThat(AnnotationAwareOrderComparator.INSTANCE.compare(filter, new SessionRepositoryFilterDefaultOrder())); + assertThat(AnnotationAwareOrderComparator.INSTANCE.compare(this.filter, new SessionRepositoryFilterDefaultOrder())); } // We want the filter to work without any dependencies on Spring @Test(expected = ClassCastException.class) @SuppressWarnings("unused") public void doesNotImplementOrdered() { - Ordered o = (Ordered) filter; + Ordered o = (Ordered) this.filter; } @Test(expected = IllegalArgumentException.class) public void setHttpSessionStrategyNull() { - filter.setHttpSessionStrategy((HttpSessionStrategy) null); + this.filter.setHttpSessionStrategy((HttpSessionStrategy) null); } @Test(expected = IllegalArgumentException.class) public void setMultiHttpSessionStrategyNull() { - filter.setHttpSessionStrategy((MultiHttpSessionStrategy) null); + this.filter.setHttpSessionStrategy((MultiHttpSessionStrategy) null); } // --- helper methods @@ -1252,39 +1282,39 @@ public class SessionRepositoryFilterTests { assertThat(cookie.getMaxAge()).isEqualTo(-1); assertThat(cookie.getValue()).isNotEqualTo("INVALID"); assertThat(cookie.isHttpOnly()).describedAs("Cookie is expected to be HTTP Only").isTrue(); - assertThat(cookie.getSecure()).describedAs("Cookie secured is expected to be " + request.isSecure()).isEqualTo(request.isSecure()); - assertThat(request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull(); + assertThat(cookie.getSecure()).describedAs("Cookie secured is expected to be " + this.request.isSecure()).isEqualTo(this.request.isSecure()); + assertThat(this.request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull(); } private void assertNoSession() { Cookie cookie = getSessionCookie(); assertThat(cookie).isNull(); - assertThat(request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull(); + assertThat(this.request.getSession(false)).describedAs("The original HttpServletRequest HttpSession should be null").isNull(); } private Cookie getSessionCookie() { - return response.getCookie("SESSION"); + return this.response.getCookie("SESSION"); } private void setSessionCookie(String sessionId) { - request.setCookies(new Cookie[]{new Cookie("SESSION", sessionId)}); + this.request.setCookies(new Cookie[]{new Cookie("SESSION", sessionId)}); } private void setupRequest() { - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - chain = new MockFilterChain(); + this.request = new MockHttpServletRequest(); + this.response = new MockHttpServletResponse(); + this.chain = new MockFilterChain(); } private void nextRequest() throws Exception { - Map nameToCookie = new HashMap(); - if (request.getCookies() != null) { - for(Cookie cookie : request.getCookies()) { + Map nameToCookie = new HashMap(); + if (this.request.getCookies() != null) { + for (Cookie cookie : this.request.getCookies()) { nameToCookie.put(cookie.getName(), cookie); } } - if (response.getCookies() != null) { - for(Cookie cookie : response.getCookies()) { + if (this.response.getCookies() != null) { + for (Cookie cookie : this.response.getCookies()) { nameToCookie.put(cookie.getName(), cookie); } } @@ -1292,25 +1322,27 @@ public class SessionRepositoryFilterTests { setupRequest(); - request.setCookies(nextRequestCookies); + this.request.setCookies(nextRequestCookies); } @SuppressWarnings("serial") private void doFilter(final DoInFilter doInFilter) throws ServletException, IOException { - chain = new MockFilterChain(new HttpServlet() {}, new OncePerRequestFilter() { + this.chain = new MockFilterChain(new HttpServlet() { + }, new OncePerRequestFilter() { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { doInFilter.doFilter(request, response); } }); - filter.doFilter(request, response, chain); + this.filter.doFilter(this.request, this.response, this.chain); } abstract class DoInFilter { void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws ServletException, IOException { doFilter(wrappedRequest); } - void doFilter(HttpServletRequest wrappedRequest) {} + void doFilter(HttpServletRequest wrappedRequest) { + } } static class SessionRepositoryFilterDefaultOrder implements Ordered { @@ -1318,4 +1350,4 @@ public class SessionRepositoryFilterTests { return SessionRepositoryFilter.DEFAULT_ORDER; } } -} \ No newline at end of file +} diff --git a/spring-session/src/test/java/org/springframework/session/web/socket/handler/WebSocketConnectHandlerDecoratorFactoryTests.java b/spring-session/src/test/java/org/springframework/session/web/socket/handler/WebSocketConnectHandlerDecoratorFactoryTests.java index 7e84512c..4e7715ca 100644 --- a/spring-session/src/test/java/org/springframework/session/web/socket/handler/WebSocketConnectHandlerDecoratorFactoryTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/socket/handler/WebSocketConnectHandlerDecoratorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.web.socket.handler; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.*; +package org.springframework.session.web.socket.handler; import org.junit.Before; import org.junit.Test; @@ -25,12 +23,18 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.session.web.socket.events.SessionConnectEvent; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketSession; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.verify; + @RunWith(MockitoJUnitRunner.class) public class WebSocketConnectHandlerDecoratorFactoryTests { @Mock @@ -46,7 +50,7 @@ public class WebSocketConnectHandlerDecoratorFactoryTests { @Before public void setup() { - factory = new WebSocketConnectHandlerDecoratorFactory(eventPublisher); + this.factory = new WebSocketConnectHandlerDecoratorFactory(this.eventPublisher); } @Test(expected = IllegalArgumentException.class) @@ -56,21 +60,21 @@ public class WebSocketConnectHandlerDecoratorFactoryTests { @Test public void decorateAfterConnectionEstablished() throws Exception { - WebSocketHandler decorated = factory.decorate(delegate); + WebSocketHandler decorated = this.factory.decorate(this.delegate); - decorated.afterConnectionEstablished(session); + decorated.afterConnectionEstablished(this.session); - verify(eventPublisher).publishEvent(event.capture()); - assertThat(event.getValue().getWebSocketSession()).isSameAs(session); + verify(this.eventPublisher).publishEvent(this.event.capture()); + assertThat(this.event.getValue().getWebSocketSession()).isSameAs(this.session); } @Test public void decorateAfterConnectionEstablishedEventError() throws Exception { - WebSocketHandler decorated = factory.decorate(delegate); - doThrow(new IllegalStateException("Test throw on publishEvent")).when(eventPublisher).publishEvent(any(ApplicationEvent.class)); + WebSocketHandler decorated = this.factory.decorate(this.delegate); + willThrow(new IllegalStateException("Test throw on publishEvent")).given(this.eventPublisher).publishEvent(any(ApplicationEvent.class)); - decorated.afterConnectionEstablished(session); + decorated.afterConnectionEstablished(this.session); - verify(eventPublisher).publishEvent(any(SessionConnectEvent.class)); + verify(this.eventPublisher).publishEvent(any(SessionConnectEvent.class)); } } diff --git a/spring-session/src/test/java/org/springframework/session/web/socket/handler/WebSocketRegistryListenerTests.java b/spring-session/src/test/java/org/springframework/session/web/socket/handler/WebSocketRegistryListenerTests.java index 47769247..2e16fe6a 100644 --- a/spring-session/src/test/java/org/springframework/session/web/socket/handler/WebSocketRegistryListenerTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/socket/handler/WebSocketRegistryListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.web.socket.handler; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +package org.springframework.session.web.socket.handler; import java.security.Principal; import java.util.HashMap; @@ -30,6 +25,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; @@ -42,6 +38,12 @@ import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.messaging.SessionDisconnectEvent; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + @RunWith(MockitoJUnitRunner.class) public class WebSocketRegistryListenerTests { @Mock @@ -60,7 +62,7 @@ public class WebSocketRegistryListenerTests { SessionDisconnectEvent disconnect; SessionDeletedEvent deleted; - + SessionExpiredEvent expired; Map attributes; @@ -72,101 +74,101 @@ public class WebSocketRegistryListenerTests { @Before public void setup() { - sessionId = "session-id"; - attributes = new HashMap(); - SessionRepositoryMessageInterceptor.setSessionId(attributes, sessionId); + this.sessionId = "session-id"; + this.attributes = new HashMap(); + SessionRepositoryMessageInterceptor.setSessionId(this.attributes, this.sessionId); - when(wsSession.getAttributes()).thenReturn(attributes); - when(wsSession.getPrincipal()).thenReturn(principal); - when(wsSession.getId()).thenReturn("wsSession-id"); + given(this.wsSession.getAttributes()).willReturn(this.attributes); + given(this.wsSession.getPrincipal()).willReturn(this.principal); + given(this.wsSession.getId()).willReturn("wsSession-id"); - when(wsSession2.getAttributes()).thenReturn(attributes); - when(wsSession2.getPrincipal()).thenReturn(principal); - when(wsSession2.getId()).thenReturn("wsSession-id2"); + given(this.wsSession2.getAttributes()).willReturn(this.attributes); + given(this.wsSession2.getPrincipal()).willReturn(this.principal); + given(this.wsSession2.getId()).willReturn("wsSession-id2"); - Map headers = new HashMap(); - headers.put(SimpMessageHeaderAccessor.SESSION_ATTRIBUTES, attributes); - when(message.getHeaders()).thenReturn(new MessageHeaders(headers)); + Map headers = new HashMap(); + headers.put(SimpMessageHeaderAccessor.SESSION_ATTRIBUTES, this.attributes); + given(this.message.getHeaders()).willReturn(new MessageHeaders(headers)); - listener = new WebSocketRegistryListener(); - connect = new SessionConnectEvent(listener,wsSession); - connect2 = new SessionConnectEvent(listener,wsSession2); - disconnect = new SessionDisconnectEvent(listener, message, wsSession.getId(), CloseStatus.NORMAL); - deleted = new SessionDeletedEvent(listener, sessionId); - expired = new SessionExpiredEvent(listener, sessionId); + this.listener = new WebSocketRegistryListener(); + this.connect = new SessionConnectEvent(this.listener, this.wsSession); + this.connect2 = new SessionConnectEvent(this.listener, this.wsSession2); + this.disconnect = new SessionDisconnectEvent(this.listener, this.message, this.wsSession.getId(), CloseStatus.NORMAL); + this.deleted = new SessionDeletedEvent(this.listener, this.sessionId); + this.expired = new SessionExpiredEvent(this.listener, this.sessionId); } @Test public void onApplicationEventConnectSessionDeleted() throws Exception { - listener.onApplicationEvent(connect); + this.listener.onApplicationEvent(this.connect); - listener.onApplicationEvent(deleted); + this.listener.onApplicationEvent(this.deleted); - verify(wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS); + verify(this.wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS); } - + @Test public void onApplicationEventConnectSessionExpired() throws Exception { - listener.onApplicationEvent(connect); + this.listener.onApplicationEvent(this.connect); - listener.onApplicationEvent(expired); + this.listener.onApplicationEvent(this.expired); - verify(wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS); + verify(this.wsSession).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS); } @Test public void onApplicationEventConnectSessionDeletedNullPrincipal() throws Exception { - when(wsSession.getPrincipal()).thenReturn(null); - listener.onApplicationEvent(connect); + given(this.wsSession.getPrincipal()).willReturn(null); + this.listener.onApplicationEvent(this.connect); - listener.onApplicationEvent(deleted); + this.listener.onApplicationEvent(this.deleted); - verify(wsSession,times(0)).close(any(CloseStatus.class)); + verify(this.wsSession, times(0)).close(any(CloseStatus.class)); } @Test public void onApplicationEventConnectDisconnect() throws Exception { - listener.onApplicationEvent(connect); - listener.onApplicationEvent(disconnect); + this.listener.onApplicationEvent(this.connect); + this.listener.onApplicationEvent(this.disconnect); - listener.onApplicationEvent(deleted); + this.listener.onApplicationEvent(this.deleted); - verify(wsSession,times(0)).close(any(CloseStatus.class)); + verify(this.wsSession, times(0)).close(any(CloseStatus.class)); } // gh-76 @Test @SuppressWarnings("unchecked") public void onApplicationEventConnectDisconnectCleanup() { - listener.onApplicationEvent(connect); + this.listener.onApplicationEvent(this.connect); - listener.onApplicationEvent(disconnect); + this.listener.onApplicationEvent(this.disconnect); - Map> httpSessionIdToWsSessions = - (Map>) ReflectionTestUtils.getField(listener, "httpSessionIdToWsSessions"); + Map> httpSessionIdToWsSessions = + (Map>) ReflectionTestUtils.getField(this.listener, "httpSessionIdToWsSessions"); assertThat(httpSessionIdToWsSessions).isEmpty(); } @Test public void onApplicationEventConnectDisconnectNullSession() throws Exception { - listener.onApplicationEvent(connect); - attributes.clear(); + this.listener.onApplicationEvent(this.connect); + this.attributes.clear(); - listener.onApplicationEvent(disconnect); + this.listener.onApplicationEvent(this.disconnect); // no exception } @Test public void onApplicationEventConnectConnectDisonnect() throws Exception { - listener.onApplicationEvent(connect); - listener.onApplicationEvent(connect2); - listener.onApplicationEvent(disconnect); + this.listener.onApplicationEvent(this.connect); + this.listener.onApplicationEvent(this.connect2); + this.listener.onApplicationEvent(this.disconnect); - listener.onApplicationEvent(deleted); + this.listener.onApplicationEvent(this.deleted); - verify(wsSession2).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS); - verify(wsSession,times(0)).close(any(CloseStatus.class)); + verify(this.wsSession2).close(WebSocketRegistryListener.SESSION_EXPIRED_STATUS); + verify(this.wsSession, times(0)).close(any(CloseStatus.class)); } } diff --git a/spring-session/src/test/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptorTests.java b/spring-session/src/test/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptorTests.java index b1979559..579d9d6d 100644 --- a/spring-session/src/test/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptorTests.java +++ b/spring-session/src/test/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.session.web.socket.server; -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; +package org.springframework.session.web.socket.server; import java.util.Collections; import java.util.EnumSet; @@ -33,6 +30,7 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -43,6 +41,15 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.session.ExpiringSession; import org.springframework.session.SessionRepository; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.longThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + @RunWith(MockitoJUnitRunner.class) public class SessionRepositoryMessageInterceptorTests { @Mock @@ -60,14 +67,14 @@ public class SessionRepositoryMessageInterceptorTests { @Before public void setup() { - interceptor = new SessionRepositoryMessageInterceptor(sessionRepository); - headers = SimpMessageHeaderAccessor.create(); - headers.setSessionId("session"); - headers.setSessionAttributes(new HashMap()); + this.interceptor = new SessionRepositoryMessageInterceptor(this.sessionRepository); + this.headers = SimpMessageHeaderAccessor.create(); + this.headers.setSessionId("session"); + this.headers.setSessionAttributes(new HashMap()); setMessageType(SimpMessageType.MESSAGE); String sessionId = "http-session"; setSessionId(sessionId); - when(sessionRepository.getSession(sessionId)).thenReturn(session); + given(this.sessionRepository.getSession(sessionId)).willReturn(this.session); } @Test(expected = IllegalArgumentException.class) @@ -77,105 +84,105 @@ public class SessionRepositoryMessageInterceptorTests { @Test public void preSendNullMessage() { - assertThat(interceptor.preSend(null, channel)).isNull(); + assertThat(this.interceptor.preSend(null, this.channel)).isNull(); } @Test public void preSendConnectAckDoesNotInvokeSessionRepository() { setMessageType(SimpMessageType.CONNECT_ACK); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } @Test public void preSendHeartbeatDoesNotInvokeSessionRepository() { setMessageType(SimpMessageType.HEARTBEAT); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } @Test public void preSendDisconnectDoesNotInvokeSessionRepository() { setMessageType(SimpMessageType.DISCONNECT); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } @Test public void preSendOtherDoesNotInvokeSessionRepository() { setMessageType(SimpMessageType.OTHER); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } @Test(expected = IllegalArgumentException.class) public void setMatchingMessageTypesNull() { - interceptor.setMatchingMessageTypes(null); + this.interceptor.setMatchingMessageTypes(null); } @Test(expected = IllegalArgumentException.class) public void setMatchingMessageTypesEmpty() { - interceptor.setMatchingMessageTypes(Collections.emptySet()); + this.interceptor.setMatchingMessageTypes(Collections.emptySet()); } @Test public void preSendSetMatchingMessageTypes() { - interceptor.setMatchingMessageTypes(EnumSet.of(SimpMessageType.DISCONNECT)); + this.interceptor.setMatchingMessageTypes(EnumSet.of(SimpMessageType.DISCONNECT)); setMessageType(SimpMessageType.DISCONNECT); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verify(sessionRepository).getSession(anyString()); - verify(sessionRepository).save(session); + verify(this.sessionRepository).getSession(anyString()); + verify(this.sessionRepository).save(this.session); } @Test public void preSendConnectUpdatesLastUpdateTime() { setMessageType(SimpMessageType.CONNECT); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verify(session).setLastAccessedTime(longThat(isAlmostNow())); - verify(sessionRepository).save(session); + verify(this.session).setLastAccessedTime(longThat(isAlmostNow())); + verify(this.sessionRepository).save(this.session); } @Test public void preSendMessageUpdatesLastUpdateTime() { setMessageType(SimpMessageType.MESSAGE); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verify(session).setLastAccessedTime(longThat(isAlmostNow())); - verify(sessionRepository).save(session); + verify(this.session).setLastAccessedTime(longThat(isAlmostNow())); + verify(this.sessionRepository).save(this.session); } @Test public void preSendSubscribeUpdatesLastUpdateTime() { setMessageType(SimpMessageType.SUBSCRIBE); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verify(session).setLastAccessedTime(longThat(isAlmostNow())); - verify(sessionRepository).save(session); + verify(this.session).setLastAccessedTime(longThat(isAlmostNow())); + verify(this.sessionRepository).save(this.session); } @Test public void preSendUnsubscribeUpdatesLastUpdateTime() { setMessageType(SimpMessageType.UNSUBSCRIBE); - session.setLastAccessedTime(0L); + this.session.setLastAccessedTime(0L); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verify(session).setLastAccessedTime(longThat(isAlmostNow())); - verify(sessionRepository).save(session); + verify(this.session).setLastAccessedTime(longThat(isAlmostNow())); + verify(this.sessionRepository).save(this.session); } // This will updated when SPR-12288 is resolved @@ -183,42 +190,42 @@ public class SessionRepositoryMessageInterceptorTests { public void preSendExpiredSession() { setSessionId("expired"); - interceptor.preSend(createMessage(), channel); + this.interceptor.preSend(createMessage(), this.channel); - verify(sessionRepository,times(0)).save(any(ExpiringSession.class)); + verify(this.sessionRepository, times(0)).save(any(ExpiringSession.class)); } @Test public void preSendNullSessionId() { setSessionId(null); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } @Test public void preSendNullSessionAttributes() { - headers.setSessionAttributes(null); + this.headers.setSessionAttributes(null); - assertThat(interceptor.preSend(createMessage(), channel)).isSameAs(createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } @Test public void beforeHandshakeNotServletServerHttpRequest() throws Exception { - assertThat(interceptor.beforeHandshake(null,null,null,null)).isTrue(); + assertThat(this.interceptor.beforeHandshake(null, null, null, null)).isTrue(); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } @Test public void beforeHandshakeNullSession() throws Exception { ServletServerHttpRequest request = new ServletServerHttpRequest(new MockHttpServletRequest()); - assertThat(interceptor.beforeHandshake(request,null,null,null)).isTrue(); + assertThat(this.interceptor.beforeHandshake(request, null, null, null)).isTrue(); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } @Test @@ -226,9 +233,9 @@ public class SessionRepositoryMessageInterceptorTests { MockHttpServletRequest httpRequest = new MockHttpServletRequest(); HttpSession httpSession = httpRequest.getSession(); ServletServerHttpRequest request = new ServletServerHttpRequest(httpRequest); - Map attributes = new HashMap(); + Map attributes = new HashMap(); - assertThat(interceptor.beforeHandshake(request,null,null,attributes)).isTrue(); + assertThat(this.interceptor.beforeHandshake(request, null, null, attributes)).isTrue(); assertThat(attributes.size()).isEqualTo(1); assertThat(SessionRepositoryMessageInterceptor.getSessionId(attributes)).isEqualTo(httpSession.getId()); @@ -239,22 +246,22 @@ public class SessionRepositoryMessageInterceptorTests { */ @Test public void afterHandshakeDoesNothing() { - interceptor.afterHandshake(null,null,null,null); + this.interceptor.afterHandshake(null, null, null, null); - verifyZeroInteractions(sessionRepository); + verifyZeroInteractions(this.sessionRepository); } private void setSessionId(String id) { - SessionRepositoryMessageInterceptor.setSessionId(headers.getSessionAttributes(), id); + SessionRepositoryMessageInterceptor.setSessionId(this.headers.getSessionAttributes(), id); } private Message createMessage() { - createMessage = MessageBuilder.createMessage("", headers.getMessageHeaders()); - return createMessage; + this.createMessage = MessageBuilder.createMessage("", this.headers.getMessageHeaders()); + return this.createMessage; } private void setMessageType(SimpMessageType type) { - headers.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, type); + this.headers.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, type); } static AlmostNowMatcher isAlmostNow() {