Prepare codebase to adhere to Checkstyle rules

Issue gh-393
This commit is contained in:
Vedran Pavic
2016-03-05 20:27:06 +01:00
committed by Rob Winch
parent 9e3bcafa75
commit 7f3302253b
222 changed files with 4071 additions and 3556 deletions

View File

@@ -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;
import java.util.HashMap;
@@ -22,8 +23,8 @@ import org.springframework.context.ApplicationListener;
import org.springframework.session.events.AbstractSessionEvent;
public class SessionEventRegistry implements ApplicationListener<AbstractSessionEvent> {
private Map<String,AbstractSessionEvent> events = new HashMap<String,AbstractSessionEvent>();
private Map<String,Object> locks = new HashMap<String,Object>();
private Map<String, AbstractSessionEvent> events = new HashMap<String, AbstractSessionEvent>();
private Map<String, Object> locks = new HashMap<String, Object>();
public void onApplicationEvent(AbstractSessionEvent event) {
String sessionId = event.getSessionId();
@@ -51,20 +52,20 @@ public class SessionEventRegistry implements ApplicationListener<AbstractSession
@SuppressWarnings("unchecked")
private <E extends AbstractSessionEvent> 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;
}

View File

@@ -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<String> regionList = new ArrayList<String>(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 extends ExpiringSession> 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 extends ExpiringSession> T expire(T session) {
session.setLastAccessedTime(0l);
session.setLastAccessedTime(0L);
return session;
}
/* (non-Javadoc) */
@SuppressWarnings("unchecked")
protected <T extends ExpiringSession> T get(String sessionId) {
return (T) gemfireSessionRepository.getSession(sessionId);
return (T) this.gemfireSessionRepository.getSession(sessionId);
}
/* (non-Javadoc) */
protected <T extends ExpiringSession> 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 extends AbstractSessionEvent> T waitForSessionEvent(long duration) {
waitOnCondition(new Condition() {
public boolean evaluate() {
return (sessionEvent != null);
return (SessionEventListener.this.sessionEvent != null);
}
}, duration);

View File

@@ -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.<ExpiringSession>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.<ExpiringSession>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();

View File

@@ -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<Object, ExpiringSession> sessionRegion = gemfireCache.getRegion(SPRING_SESSION_GEMFIRE_REGION_NAME);
Region<Object, ExpiringSession> 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<String, ExpiringSession> doFindByIndexNameAndIndexValue(String indexName, String indexValue) {
return gemfireSessionRepository.findByIndexNameAndIndexValue(indexName, indexValue);
return this.gemfireSessionRepository.findByIndexNameAndIndexValue(indexName, indexValue);
}
protected Map<String, ExpiringSession> doFindByPrincipalName(String principalName) {
return doFindByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, principalName);
return doFindByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principalName);
}
@SuppressWarnings({ "unchecked" })
protected Map<String, ExpiringSession> doFindByPrincipalName(String regionName, String principalName) {
try {
Region<String, ExpiringSession> region = gemfireCache.getRegion(regionName);
Region<String, ExpiringSession> 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<String, ExpiringSession> 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<String> 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() {

View File

@@ -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<Object, ExpiringSession> sessionRegion = gemfireCache.getRegion(SPRING_SESSION_GEMFIRE_REGION_NAME);
Region<Object, ExpiringSession> 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();

View File

@@ -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<Object, ExpiringSession> example = assertCacheAndRegion(gemfireCache, "JavaExample",
Region<Object, ExpiringSession> 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<Object, ExpiringSession> example = assertCacheAndRegion(gemfireCache, "JavaExample",
Region<Object, ExpiringSession> 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<Object, ExpiringSession> example = assertCacheAndRegion(gemfireCache, "JavaExample",
Region<Object, ExpiringSession> example = assertCacheAndRegion(this.gemfireCache, "JavaExample",
DataPolicy.REPLICATE);
QueryService queryService = example.getRegionService().getQueryService();

View File

@@ -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<Object, ExpiringSession> example = assertCacheAndRegion(gemfireCache, "XmlExample", DataPolicy.NORMAL);
Region<Object, ExpiringSession> example = assertCacheAndRegion(this.gemfireCache, "XmlExample", DataPolicy.NORMAL);
assertEntryIdleTimeout(example, ExpirationAction.INVALIDATE, 3600);
}
@Test
public void verifyGemFireExampleCacheRegionPrincipalNameIndexWasCreatedSuccessfully() {
Region<Object, ExpiringSession> example = assertCacheAndRegion(gemfireCache, "XmlExample", DataPolicy.NORMAL);
Region<Object, ExpiringSession> 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<Object, ExpiringSession> example = assertCacheAndRegion(gemfireCache, "XmlExample", DataPolicy.NORMAL);
Region<Object, ExpiringSession> example = assertCacheAndRegion(this.gemfireCache, "XmlExample", DataPolicy.NORMAL);
QueryService queryService = example.getRegionService().getQueryService();

View File

@@ -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<S extends Expirin
@Before
public void setup() {
registry.setLock(lock);
this.registry.setLock(this.lock);
}
@Test
public void expireFiresSessionExpiredEvent() throws InterruptedException {
S toSave = repository.createSession();
S toSave = this.repository.createSession();
toSave.setAttribute("a", "b");
Authentication toSaveToken = new UsernamePasswordAuthenticationToken("user","password", AuthorityUtils.createAuthorityList("ROLE_USER"));
Authentication toSaveToken = new UsernamePasswordAuthenticationToken("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext();
toSaveContext.setAuthentication(toSaveToken);
toSave.setAttribute("SPRING_SECURITY_CONTEXT", toSaveContext);
repository.save(toSave);
this.repository.save(toSave);
synchronized (lock) {
lock.wait((toSave.getMaxInactiveIntervalInSeconds() * 1000) + 1);
synchronized (this.lock) {
this.lock.wait((toSave.getMaxInactiveIntervalInSeconds() * 1000) + 1);
}
if(!registry.receivedEvent()) {
if (!this.registry.receivedEvent()) {
// Redis makes no guarantees on when an expired event will be fired
// we can ensure it gets fired by trying to get the session
repository.getSession(toSave.getId());
synchronized (lock) {
if(!registry.receivedEvent()) {
this.repository.getSession(toSave.getId());
synchronized (this.lock) {
if (!this.registry.receivedEvent()) {
// wait at most a minute
lock.wait(TimeUnit.MINUTES.toMillis(1));
this.lock.wait(TimeUnit.MINUTES.toMillis(1));
}
}
}
assertThat(registry.receivedEvent()).isTrue();
assertThat(this.registry.receivedEvent()).isTrue();
}
static class SessionExpiredEventRegistry implements ApplicationListener<SessionExpiredEvent> {
@@ -90,14 +91,14 @@ public class EnableRedisHttpSessionExpireSessionDestroyedTests<S extends Expirin
private Object lock;
public void onApplicationEvent(SessionExpiredEvent event) {
synchronized (lock) {
receivedEvent = true;
lock.notifyAll();
synchronized (this.lock) {
this.receivedEvent = true;
this.lock.notifyAll();
}
}
public boolean receivedEvent() {
return receivedEvent;
return this.receivedEvent;
}
public void setLock(Object lock) {

View File

@@ -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.flushimmediately;
import org.springframework.context.annotation.Bean;
@@ -34,4 +35,4 @@ public class RedisHttpSessionConfig {
factory.setUsePool(false);
return factory;
}
}
}

View File

@@ -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.flushimmediately;
import static org.assertj.core.api.Assertions.assertThat;
package org.springframework.session.data.redis.flushimmediately;
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.SessionRepository;
@@ -26,8 +26,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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=RedisHttpSessionConfig.class)
@ContextConfiguration(classes = RedisHttpSessionConfig.class)
@WebAppConfiguration
public class RedisOperationsSessionRepositoryFlushImmediatelyITests<S extends ExpiringSession> {
@@ -36,10 +38,10 @@ public class RedisOperationsSessionRepositoryFlushImmediatelyITests<S extends Ex
@Test
public void savesOnCreate() throws InterruptedException {
S created = sessionRepository.createSession();
S created = this.sessionRepository.createSession();
S getSession = sessionRepository.getSession(created.getId());
S getSession = this.sessionRepository.getSession(created.getId());
assertThat(getSession).isNotNull();
}
}
}

View File

@@ -1,6 +1,20 @@
package org.springframework.session.data.redis.taskexecutor;
/*
* 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.
*/
import static org.assertj.core.api.Assertions.assertThat;
package org.springframework.session.data.redis.taskexecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@@ -8,6 +22,7 @@ import java.util.concurrent.TimeUnit;
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;
@@ -21,6 +36,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;
/**
* @author Vladimir Tsanev
*/
@@ -37,11 +54,11 @@ public class RedisListenerContainerTaskExecutorITests {
@Test
public void testRedisDelEventsAreDispatchedInSessionTaskExecutor() throws InterruptedException {
BoundSetOperations<Object, Object> ops = redis
BoundSetOperations<Object, Object> 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;
}
}

View File

@@ -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<S extends ExpiringSessio
@Test
public void createAndDestroySession() {
S sessionToSave = repository.createSession();
S sessionToSave = this.repository.createSession();
String sessionId = sessionToSave.getId();
IMap<String, S> hazelcastMap = hazelcast.getMap("spring:session:sessions");
IMap<String, S> 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);
}

View File

@@ -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<S extends ExpiringSession>
@AfterClass
public static void teardown() {
if(hazelcastInstance != null) {
if (hazelcastInstance != null) {
hazelcastInstance.shutdown();
}
}

View File

@@ -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.

View File

@@ -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.

View File

@@ -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<S extends ExpiringSession> {
@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<S extends ExpiringSession> {
@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

View File

@@ -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<S extends ExpiringSession> {
@@ -54,11 +55,11 @@ public class HazelcastHttpSessionConfigurationXmlTests<S extends ExpiringSession
@Test
public void saveSessionTest() throws InterruptedException {
S sessionToSave = repository.createSession();
S sessionToSave = this.repository.createSession();
repository.save(sessionToSave);
this.repository.save(sessionToSave);
S session = repository.getSession(sessionToSave.getId());
S session = this.repository.getSession(sessionToSave.getId());
assertThat(session.getId()).isEqualTo(sessionToSave.getId());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(1800);
@@ -91,11 +92,11 @@ public class HazelcastHttpSessionConfigurationXmlTests<S extends ExpiringSession
@Test
public void saveSessionTest() throws InterruptedException {
S sessionToSave = repository.createSession();
S sessionToSave = this.repository.createSession();
repository.save(sessionToSave);
this.repository.save(sessionToSave);
S session = repository.getSession(sessionToSave.getId());
S session = this.repository.getSession(sessionToSave.getId());
assertThat(session.getId()).isEqualTo(sessionToSave.getId());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(1200);

View File

@@ -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,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session;
/**
* A {@link Session} that contains additional attributes that are useful for determining if a session is expired.
*
* @since 1.0
* @author Rob Winch
* @since 1.0
*/
public interface ExpiringSession extends Session {
@@ -31,14 +32,14 @@ public interface ExpiringSession extends Session {
long getCreationTime();
/**
* Sets the last accessed time in milliseconds since midnight of 1/1/1970 GMT
* Sets the last accessed time in milliseconds since midnight of 1/1/1970 GMT.
*
* @param lastAccessedTime the last accessed time in milliseconds since midnight of 1/1/1970 GMT
*/
void setLastAccessedTime(long lastAccessedTime);
/**
* Gets the last time this {@link Session} was accessed expressed in milliseconds since midnight of 1/1/1970 GMT
* Gets the last time this {@link Session} was accessed expressed in milliseconds since midnight of 1/1/1970 GMT.
*
* @return the last time the client sent a request associated with the session expressed in milliseconds since midnight of 1/1/1970 GMT
*/

View File

@@ -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;
import java.util.Map;
@@ -22,11 +23,10 @@ import java.util.Map;
* the principal name. The principal name is defined by the {@link Session}
* attribute with the name {@link FindByIndexNameSessionRepository#PRINCIPAL_NAME_INDEX_NAME}.
*
* @author Rob Winch
*
* @param <S>
* the type of Session being managed by this
* {@link FindByIndexNameSessionRepository}
* @author Rob Winch
*/
public interface FindByIndexNameSessionRepository<S extends Session> extends SessionRepository<S> {
@@ -61,4 +61,4 @@ public interface FindByIndexNameSessionRepository<S extends Session> extends Ses
* an empty Map is returned.
*/
Map<String, S> findByIndexNameAndIndexValue(String indexName, String indexValue);
}
}

View File

@@ -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.
* </p>
*
* @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<String, Object> sessionAttrs = new HashMap<String, Object>();
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> T getAttribute(String attributeName) {
return (T) sessionAttrs.get(attributeName);
return (T) this.sessionAttrs.get(attributeName);
}
public Set<String> 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;
}
}

View File

@@ -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<ExpiringSession>
*/
private Integer defaultMaxInactiveInterval;
private final Map<String,ExpiringSession> sessions;
private final Map<String, ExpiringSession> 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<String, ExpiringSession>());
@@ -53,8 +54,8 @@ public class MapSessionRepository implements SessionRepository<ExpiringSession>
*
* @param sessions the {@link java.util.Map} to use. Cannot be null.
*/
public MapSessionRepository(Map<String,ExpiringSession> sessions) {
if(sessions == null) {
public MapSessionRepository(Map<String, ExpiringSession> sessions) {
if (sessions == null) {
throw new IllegalArgumentException("sessions cannot be null");
}
this.sessions = sessions;
@@ -69,15 +70,15 @@ public class MapSessionRepository implements SessionRepository<ExpiringSession>
}
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<ExpiringSession>
}
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;
}

View File

@@ -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);
}
}

View File

@@ -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 <S> the {@link Session} type
* @author Rob Winch
* @since 1.0
*/
@@ -59,4 +61,4 @@ public interface SessionRepository<S extends Session> {
* @param id the {@link org.springframework.session.Session#getId()} to delete
*/
void delete(String id);
}
}

View File

@@ -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

View File

@@ -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<HttpSessionListener> httpSessionListeners = new ArrayList<HttpSessionListener>();
@@ -93,22 +94,23 @@ public class SpringHttpSessionConfiguration {
@Bean
public SessionEventHttpSessionListenerAdapter sessionEventHttpSessionListenerAdapter() {
return new SessionEventHttpSessionListenerAdapter(httpSessionListeners);
return new SessionEventHttpSessionListenerAdapter(this.httpSessionListeners);
}
@Bean
public <S extends ExpiringSession> SessionRepositoryFilter<? extends ExpiringSession> springSessionRepositoryFilter(SessionRepository<S> sessionRepository) {
SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<S>(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;
}

View File

@@ -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<Object, ExpiringSession>
implements InitializingBean, FindByIndexNameSessionRepository<ExpiringSession>,
@@ -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<Object, ExpiringSession> 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> T getAttribute(String attributeName) {
return sessionAttributes.getAttribute(attributeName);
return this.sessionAttributes.getAttribute(attributeName);
}
/* (non-Javadoc) */
public Set<String> 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.<GemFireSessionAttributes>readObject(in));
this.sessionAttributes.from(this.<GemFireSessionAttributes>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> T getAttribute(String attributeName) {
synchronized (lock) {
return (T) sessionAttributes.get(attributeName);
synchronized (this.lock) {
return (T) this.sessionAttributes.get(attributeName);
}
}
/* (non-Javadoc) */
public Set<String> getAttributeNames() {
synchronized (lock) {
return Collections.unmodifiableSet(new HashSet<String>(sessionAttributes.keySet()));
synchronized (this.lock) {
return Collections.unmodifiableSet(new HashSet<String>(this.sessionAttributes.keySet()));
}
}
@@ -709,19 +711,21 @@ public abstract class AbstractGemFireOperationsSessionRepository extends CacheLi
@SuppressWarnings("all")
public Set<Entry<String, Object>> entrySet() {
return new AbstractSet<Entry<String, Object>>() {
@Override public Iterator<Entry<String, Object>> iterator() {
return Collections.unmodifiableMap(sessionAttributes).entrySet().iterator();
@Override
public Iterator<Entry<String, Object>> 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<String> 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> T readObject(DataInput in) throws ClassNotFoundException , IOException {
<T> 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<String, Object> entry : sessionAttributeDeltas.entrySet()) {
for (Map.Entry<String, Object> 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<String, Object> 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();
}
}

View File

@@ -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 {

View File

@@ -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.

View File

@@ -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<Object> SPRING_SESSION_GEMFIRE_REGION_KEY_CONSTRAINT = Object.class;
protected static final Class<GemFireSession> 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();
}

View File

@@ -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 <K> the type of keys
* @param <V> 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<K, V> implements FactoryBean<Region<K, V>>, InitializingBean {
@@ -88,7 +90,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean<K, V> 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<K, V> implements FactoryBean
* @see com.gemstone.gemfire.cache.Region
*/
public Region<K, V> getObject() throws Exception {
return region;
return this.region;
}
/**
@@ -191,7 +193,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean<K, V> 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<K, V> 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<K, V> 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<K, V> implements FactoryBean
* @see com.gemstone.gemfire.cache.RegionAttributes
*/
protected RegionAttributes<K, V> getRegionAttributes() {
return regionAttributes;
return this.regionAttributes;
}
/**
@@ -287,7 +289,7 @@ public class GemFireCacheTypeAwareRegionFactoryBean<K, V> 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<K, V> 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);
}
}

View File

@@ -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,

View File

@@ -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;

View File

@@ -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.
* </p>
*
* @since 1.0
*
* @author Rob Winch
* @since 1.0
*/
public class RedisOperationsSessionRepository implements FindByIndexNameSessionRepository<RedisOperationsSessionRepository.RedisSession>, 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<Object,Object> sessionRedisOperations;
private final RedisOperations<Object, Object> 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<String,RedisSession> findByIndexNameAndIndexValue(String indexName, String indexValue) {
if(!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) {
public Map<String, RedisSession> findByIndexNameAndIndexValue(String indexName, String indexValue) {
if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) {
return Collections.emptyMap();
}
String principalKey = getPrincipalKey(indexValue);
Set<Object> sessionIds = sessionRedisOperations.boundSetOps(principalKey).members();
Map<String,RedisSession> sessions = new HashMap<String,RedisSession>(sessionIds.size());
for(Object id : sessionIds) {
Set<Object> sessionIds = this.sessionRedisOperations.boundSetOps(principalKey).members();
Map<String, RedisSession> sessions = new HashMap<String, RedisSession>(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<Object, Object> 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<Object, Object> entries) {
MapSession loaded = new MapSession(id);
for(Map.Entry<Object,Object> entry : entries.entrySet()) {
for (Map.Entry<Object, Object> 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<Object,Object> loaded = (Map<Object, Object>) defaultSerializer.deserialize(message.getBody());
Map<Object, Object> loaded = (Map<Object, Object>) 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<Object,Object> loaded, String channel) {
public void handleCreated(Map<Object, Object> 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<Object,Object> createDefaultTemplate(RedisConnectionFactory connectionFactory) {
Assert.notNull(connectionFactory,"connectionFactory cannot be null");
private static RedisTemplate<Object, Object> createDefaultTemplate(RedisConnectionFactory connectionFactory) {
Assert.notNull(connectionFactory, "connectionFactory cannot be null");
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
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<String, Object> delta = new HashMap<String,Object>();
private Map<String, Object> delta = new HashMap<String, Object>();
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<String> 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<String,Object>(delta.size());
this.delta = new HashMap<String, Object>(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;

View File

@@ -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<Object,Object> redis;
private final RedisOperations<Object, Object> redis;
private final RedisOperationsSessionRepository redisSession;
public RedisSessionExpirationPolicy(
RedisOperations<Object,Object> sessionRedisOperations, RedisOperationsSessionRepository redisSession) {
RedisSessionExpirationPolicy(
RedisOperations<Object, Object> 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<Object, Object> expireOperations = redis.boundSetOps(expireKey);
BoundSetOperations<Object, Object> 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<Object> sessionsToExpire = redis.boundSetOps(expirationKey).members();
redis.delete(expirationKey);
for(Object session : sessionsToExpire) {
Set<Object> 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) {

View File

@@ -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));
}
}

View File

@@ -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<String> 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);
}
}

View File

@@ -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;

View File

@@ -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;
}
}

View File

@@ -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<Object,Object> sessionRedisTemplate(RedisConnectionFactory connectionFactory) {
public RedisTemplate<Object, Object> sessionRedisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
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<Object, Object> 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<String, Object> 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);
}
}
}

View File

@@ -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 extends Session> S getSession() {
return (S) session;
return (S) this.session;
}
public String getSessionId() {
return sessionId;
return this.sessionId;
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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<String, Expiring
}
public void entryAdded(EntryEvent<String, ExpiringSession> 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<String, ExpiringSession> 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<String, ExpiringSession> event) {
if(logger.isDebugEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("Session deleted with id: " + event.getOldValue().getId());
}
this.eventPublisher.publishEvent(new SessionDeletedEvent(this, event.getOldValue()));

View File

@@ -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

View File

@@ -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<ExpiringSession> 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<String, ExpiringSession> {
private IMap<String,ExpiringSession> delegate;
private IMap<String, ExpiringSession> delegate;
ExpiringSessionMap(IMap<String,ExpiringSession> delegate) {
ExpiringSessionMap(IMap<String, ExpiringSession> 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<? extends String, ? extends ExpiringSession> m) {
delegate.putAll(m);
this.delegate.putAll(m);
}
public void clear() {
delegate.clear();
this.delegate.clear();
}
public Set<String> keySet() {
return delegate.keySet();
return this.delegate.keySet();
}
public Collection<ExpiringSession> values() {
return delegate.values();
return this.delegate.values();
}
public Set<java.util.Map.Entry<String, ExpiringSession>> 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();
}
}
}

View File

@@ -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<DispatcherType> 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;

View File

@@ -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<String,String> sessionIds = getSessionIds(request);
Map<String, String> 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<String> 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<String> sessionIdsWritten = getSessionIdsWritten(request);
if(sessionIdsWritten.contains(session.getId())) {
if (sessionIdsWritten.contains(session.getId())) {
return;
}
sessionIdsWritten.add(session.getId());
Map<String,String> sessionIds = getSessionIds(request);
Map<String, String> 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<String> getSessionIdsWritten(HttpServletRequest request) {
Set<String> sessionsWritten = (Set<String>) request.getAttribute(SESSION_IDS_WRITTEN_ATTR);
if(sessionsWritten == null) {
if (sessionsWritten == null) {
sessionsWritten = new HashSet<String>();
request.setAttribute(SESSION_IDS_WRITTEN_ATTR, sessionsWritten);
}
@@ -235,15 +237,15 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy
}
private String createSessionCookieValue(Map<String, String> 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<String,String> entry : sessionIds.entrySet()) {
for (Map.Entry<String, String> 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<String,String> sessionIds = getSessionIds(request);
Map<String, String> 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<String,String> getSessionIds(HttpServletRequest request) {
List<String> cookieValues = cookieSerializer.readCookieValues(request);
public Map<String, String> getSessionIds(HttpServletRequest request) {
List<String> cookieValues = this.cookieSerializer.readCookieValues(request);
String sessionCookieValue = cookieValues.isEmpty() ? "" : cookieValues.iterator().next();
Map<String,String> result = new LinkedHashMap<String,String>();
Map<String, String> result = new LinkedHashMap<String, String>();
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);
}
}
}
/**
* 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);
}
}
}

View File

@@ -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;
}
}
}

View File

@@ -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<String> readCookieValues(HttpServletRequest request) {
Cookie cookies[] = request.getCookies();
Cookie[] cookies = request.getCookies();
List<String> matchingCookieValues = new ArrayList<String>();
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;
}

View File

@@ -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 <S> the {@link ExpiringSession} type
* @author Rob Winch
* @since 1.1
*/
@@ -39,7 +41,7 @@ class ExpiringSessionHttpSession<S extends ExpiringSession> 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<S extends ExpiringSession> 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<S extends ExpiringSession> 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<S extends ExpiringSession> implements HttpSessi
public Enumeration<String> getAttributeNames() {
checkState();
return Collections.enumeration(session.getAttributeNames());
return Collections.enumeration(this.session.getAttributeNames());
}
public String[] getValueNames() {
checkState();
Set<String> attrs = session.getAttributeNames();
Set<String> 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<S extends ExpiringSession> 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<S extends ExpiringSession> 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.");
}
}

View File

@@ -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:
* </pre>
*
* @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;
}
}
}

View File

@@ -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

View File

@@ -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 {

View File

@@ -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.
* </p>
*
* @see CookieHttpSessionStrategy
*
* @author Rob Winch
* @since 1.0
* @see CookieHttpSessionStrategy
*/
public interface MultiHttpSessionStrategy extends HttpSessionStrategy, RequestResponsePostProcessor {
}
}

View File

@@ -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 <code>sendError()</code>
* superclass <code>sendError()</code>.
* @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 <code>sendError()</code>
* superclass <code>sendError()</code>.
* @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 <code>sendRedirect()</code>
* superclass <code>sendRedirect()</code>.
* @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
* <code>getOutputStream().close()</code> or <code>getOutputStream().flush()</code>
* <code>getOutputStream().close()</code> or <code>getOutputStream().flush()</code>.
* @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
* <code>getWriter().close()</code> or <code>getWriter().flush()</code>
* <code>getWriter().close()</code> or <code>getWriter().flush()</code>.
* @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 <code>flushBuffer()</code>
* superclass <code>flushBuffer()</code>.
* @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 <code>onResponseCommmitted()</code> 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() + "]";
}
}
}
}

View File

@@ -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() {
}
}

View File

@@ -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;

View File

@@ -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<ExpiringSession>(session, context);
HttpSession httpSession = new ExpiringSessionHttpSession<ExpiringSession>(session, this.context);
HttpSessionEvent httpSessionEvent = new HttpSessionEvent(httpSession);
return httpSessionEvent;
}

View File

@@ -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.
* </p>
*
* @param <S> the {@link ExpiringSession} type.
* @since 1.0
* @author Rob Winch
*/
@@ -67,8 +70,14 @@ public class SessionRepositoryFilter<S extends ExpiringSession> 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<S> sessionRepository;
@@ -78,12 +87,12 @@ public class SessionRepositoryFilter<S extends ExpiringSession> extends OncePerR
private MultiHttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy();
/**
* Creates a new instance
* Creates a new instance.
*
* @param sessionRepository the <code>SessionRepository</code> to use. Cannot be null.
*/
public SessionRepositoryFilter(SessionRepository<S> sessionRepository) {
if(sessionRepository == null) {
if (sessionRepository == null) {
throw new IllegalArgumentException("sessionRepository cannot be null");
}
this.sessionRepository = sessionRepository;
@@ -95,7 +104,7 @@ public class SessionRepositoryFilter<S extends ExpiringSession> 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<S extends ExpiringSession> 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<S extends ExpiringSession> 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<S extends ExpiringSession> extends OncePerR
@Override
protected void onResponseCommitted() {
request.commitSession();
this.request.commitSession();
}
}
@@ -185,29 +197,31 @@ public class SessionRepositoryFilter<S extends ExpiringSession> 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<S extends ExpiringSession> 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<String,Object> attrs = new HashMap<String,Object>();
Map<String, Object> attrs = new HashMap<String, Object>();
Enumeration<String> 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<S extends ExpiringSession> extends OncePerR
original.setSession(newSession.getSession());
newSession.setMaxInactiveInterval(session.getMaxInactiveInterval());
for(Map.Entry<String, Object> attr : attrs.entrySet()) {
for (Map.Entry<String, Object> attr : attrs.entrySet()) {
String attrName = attr.getKey();
Object attrValue = attr.getValue();
newSession.setAttribute(attrName, attrValue);
@@ -246,29 +260,29 @@ public class SessionRepositoryFilter<S extends ExpiringSession> 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<S extends ExpiringSession> 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<S extends ExpiringSession> 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<S extends ExpiringSession> 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<S extends ExpiringSession> extends OncePerR
@Override
public String getRequestedSessionId() {
return httpSessionStrategy.getRequestedSessionId(this);
return SessionRepositoryFilter.this.httpSessionStrategy.getRequestedSessionId(this);
}
/**
@@ -333,38 +347,45 @@ public class SessionRepositoryFilter<S extends ExpiringSession> extends OncePerR
*/
private final class HttpSessionWrapper extends ExpiringSessionHttpSession<S> {
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,

View File

@@ -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;
* }
* </code>
*
* @author Rob Winch
* @since 1.0
*
* @param <S>
* the type of ExpiringSession
* @author Rob Winch
* @since 1.0
*/
public abstract class AbstractSessionWebSocketMessageBrokerConfigurer<S extends ExpiringSession> extends AbstractWebSocketMessageBrokerConfigurer {
@@ -90,7 +90,7 @@ public abstract class AbstractSessionWebSocketMessageBrokerConfigurer<S extends
}
public final void registerStompEndpoints(StompEndpointRegistry registry) {
if(registry instanceof WebMvcStompEndpointRegistry) {
if (registry instanceof WebMvcStompEndpointRegistry) {
WebMvcStompEndpointRegistry mvcRegistry = (WebMvcStompEndpointRegistry) registry;
configureStompEndpoints(new SessionStompEndpointRegistry(mvcRegistry, sessionRepositoryInterceptor()));
}
@@ -122,28 +122,31 @@ public abstract class AbstractSessionWebSocketMessageBrokerConfigurer<S extends
@Bean
public WebSocketConnectHandlerDecoratorFactory wsConnectHandlerDecoratorFactory() {
return new WebSocketConnectHandlerDecoratorFactory(eventPublisher);
return new WebSocketConnectHandlerDecoratorFactory(this.eventPublisher);
}
@Bean
@SuppressWarnings("unchecked")
public SessionRepositoryMessageInterceptor<S> sessionRepositoryInterceptor() {
return new SessionRepositoryMessageInterceptor<S>(sessionRepository);
return new SessionRepositoryMessageInterceptor<S>(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<S extends
return this.registry.setErrorHandler(errorHandler);
}
}
}
}

View File

@@ -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.events;
import org.springframework.context.ApplicationEvent;
@@ -42,6 +43,6 @@ public class SessionConnectEvent extends ApplicationEvent {
}
public WebSocketSession getWebSocketSession() {
return webSocketSession;
return this.webSocketSession;
}
}
}

View File

@@ -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.web.socket.handler;
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.session.Session;
@@ -47,7 +49,7 @@ public final class WebSocketConnectHandlerDecoratorFactory implements WebSocketH
private final ApplicationEventPublisher eventPublisher;
/**
* Creates a new instance
* Creates a new instance.
*
* @param eventPublisher the {@link ApplicationEventPublisher} to use. Cannot be null.
*/
@@ -63,7 +65,7 @@ public final class WebSocketConnectHandlerDecoratorFactory implements WebSocketH
private final class SessionWebSocketHandler extends WebSocketHandlerDecorator {
public SessionWebSocketHandler(WebSocketHandler delegate) {
SessionWebSocketHandler(WebSocketHandler delegate) {
super(delegate);
}
@@ -72,12 +74,12 @@ public final class WebSocketConnectHandlerDecoratorFactory implements WebSocketH
throws Exception {
super.afterConnectionEstablished(wsSession);
publishEvent(new SessionConnectEvent(this,wsSession));
publishEvent(new SessionConnectEvent(this, wsSession));
}
private void publishEvent(ApplicationEvent event) {
try {
eventPublisher.publishEvent(event);
WebSocketConnectHandlerDecoratorFactory.this.eventPublisher.publishEvent(event);
}
catch (Throwable ex) {
logger.error("Error publishing " + event + ".", ex);

View File

@@ -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.handler;
import java.io.IOException;
@@ -22,6 +23,7 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
@@ -51,16 +53,18 @@ public final class WebSocketRegistryListener implements ApplicationListener<Appl
static final CloseStatus SESSION_EXPIRED_STATUS = new CloseStatus(CloseStatus.POLICY_VIOLATION.getCode(),
"This connection was established under an authenticated HTTP Session that has expired");
private final ConcurrentHashMap<String,Map<String,WebSocketSession>> httpSessionIdToWsSessions = new ConcurrentHashMap<String,Map<String,WebSocketSession>>();
private final ConcurrentHashMap<String, Map<String, WebSocketSession>> httpSessionIdToWsSessions = new ConcurrentHashMap<String, Map<String, WebSocketSession>>();
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<String, Object> sessionAttributes = SimpMessageHeaderAccessor.getSessionAttributes(e.getMessage().getHeaders());
String httpSessionId = sessionAttributes == null ? null : SessionRepositoryMessageInterceptor.getSessionId(sessionAttributes);
@@ -70,7 +74,7 @@ public final class WebSocketRegistryListener implements ApplicationListener<Appl
private void afterConnectionEstablished(WebSocketSession wsSession) {
Principal principal = wsSession.getPrincipal();
if(principal == null) {
if (principal == null) {
return;
}
@@ -84,19 +88,19 @@ public final class WebSocketRegistryListener implements ApplicationListener<Appl
}
private void afterConnectionClosed(String httpSessionId, String wsSessionId) {
if(httpSessionId == null) {
if (httpSessionId == null) {
return;
}
Map<String,WebSocketSession> sessions = httpSessionIdToWsSessions.get(httpSessionId);
if(sessions != null) {
Map<String, WebSocketSession> 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<Appl
}
private void registerWsSession(String httpSessionId, WebSocketSession wsSession) {
Map<String,WebSocketSession> sessions = httpSessionIdToWsSessions.get(httpSessionId);
if(sessions == null) {
Map<String, WebSocketSession> sessions = this.httpSessionIdToWsSessions.get(httpSessionId);
if (sessions == null) {
sessions =
new ConcurrentHashMap<String,WebSocketSession>();
httpSessionIdToWsSessions.putIfAbsent(httpSessionId, sessions);
sessions = httpSessionIdToWsSessions.get(httpSessionId);
new ConcurrentHashMap<String, WebSocketSession>();
this.httpSessionIdToWsSessions.putIfAbsent(httpSessionId, sessions);
sessions = this.httpSessionIdToWsSessions.get(httpSessionId);
}
sessions.put(wsSession.getId(), wsSession);
}
private void closeWsSessions(String httpSessionId) {
Map<String,WebSocketSession> sessionsToClose = httpSessionIdToWsSessions.remove(httpSessionId);
if(sessionsToClose == null) {
Map<String, WebSocketSession> 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);
}
}
}
}
}

View File

@@ -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;
* .
* </p>
*
* @param <S> the {@link ExpiringSession} type
* @author Rob Winch
* @since 1.0
*/
@@ -75,7 +77,7 @@ public final class SessionRepositoryMessageInterceptor<S extends ExpiringSession
private Set<SimpMessageType> 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<S extends ExpiringSession
* {@link Session}
*/
public void setMatchingMessageTypes(Set<SimpMessageType> 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<String, Object> 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<S extends ExpiringSession
public static void setSessionId(Map<String, Object> attributes, String sessionId) {
attributes.put(SPRING_SESSION_ID_ATTR_NAME, sessionId);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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 {
}
}
}
}

View File

@@ -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

View File

@@ -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

View File

@@ -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.<Object, ExpiringSession>getRegion()).thenReturn(mockRegion);
given(this.mockRegion.getAttributesMutator()).willReturn(this.mockAttributesMutator);
given(this.mockRegion.getFullPath()).willReturn("/Example");
given(this.mockTemplate.<Object, ExpiringSession>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<Object> mockSelectResults = mock(SelectResults.class);
when(mockSelectResults.asList()).thenReturn(Collections.<Object>singletonList(mockSession));
given(mockSelectResults.asList()).willReturn(Collections.<Object>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<String, ExpiringSession> sessions = sessionRepository.findByIndexNameAndIndexValue(indexName, indexValue);
Map<String, ExpiringSession> 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<Object> mockSelectResults = mock(SelectResults.class);
when(mockSelectResults.asList()).thenReturn(Arrays.<Object>asList(mockSessionOne, mockSessionTwo, mockSessionThree));
given(mockSelectResults.asList()).willReturn(Arrays.<Object>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<String, ExpiringSession> sessions = sessionRepository.findByIndexNameAndIndexValue(
PRINCIPAL_NAME_INDEX_NAME, principalName);
Map<String, ExpiringSession> 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<Object> 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<String, ExpiringSession> sessions = sessionRepository.findByIndexNameAndIndexValue(
PRINCIPAL_NAME_INDEX_NAME, principalName);
Map<String, ExpiringSession> 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<Void>() {
willAnswer(new Answer<Void>() {
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.<String>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.<String>emptySet());
when(mockTemplate.put(eq(expectedSessionId), isA(GemFireSession.class)))
.thenAnswer(new Answer<ExpiringSession>() {
given(this.mockTemplate.put(eq(expectedSessionId), isA(AbstractGemFireOperationsSessionRepository.GemFireSession.class)))
.willAnswer(new Answer<ExpiringSession>() {
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<Void>() {
willAnswer(new Answer<Void>() {
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<Void>() {
willAnswer(new Answer<Void>() {
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 {

View File

@@ -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<Object,Object> mockRegion = mock(Region.class);
Region<Object, Object> 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();
}
}

View File

@@ -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<Object,ExpiringSession> mockClientRegion;
Region<Object, ExpiringSession> mockClientRegion;
@Mock
Region<Object,ExpiringSession> mockServerRegion;
Region<Object, ExpiringSession> mockServerRegion;
@Mock
ClientCache mockClientCache;
private GemFireCacheTypeAwareRegionFactoryBean<Object,ExpiringSession> regionFactoryBean;
private GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession> regionFactoryBean;
@Before
public void setup() {
regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object,ExpiringSession>();
this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession>();
}
@Test
public void afterPropertiesSetCreatesClientRegionForClientCache() throws Exception {
regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object,ExpiringSession>() {
@Override protected Region<Object,ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockClientCache);
return mockClientRegion;
this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession>() {
@Override
protected Region<Object, ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientCache);
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion;
}
@Override protected Region<Object,ExpiringSession> newServerRegion(final GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockClientCache);
return mockServerRegion;
@Override
protected Region<Object, ExpiringSession> 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<Object,ExpiringSession>() {
@Override protected Region<Object,ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
this.regionFactoryBean = new GemFireCacheTypeAwareRegionFactoryBean<Object, ExpiringSession>() {
@Override
protected Region<Object, ExpiringSession> newClientRegion(GemFireCache gemfireCache) throws Exception {
assertThat(gemfireCache).isSameAs(mockCache);
return mockClientRegion;
return GemFireCacheTypeAwareRegionFactoryBeanTest.this.mockClientRegion;
}
@Override protected Region<Object,ExpiringSession> newServerRegion(final GemFireCache gemfireCache) throws Exception {
@Override
protected Region<Object, ExpiringSession> 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<Object>[] interests = regionFactoryBean.registerInterests(true);
Interest<Object>[] 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<Object>[] interests = regionFactoryBean.registerInterests(false);
Interest<Object>[] 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<Object,ExpiringSession> mockRegionAttributes = mock(RegionAttributes.class);
RegionAttributes<Object, ExpiringSession> 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);
}

View File

@@ -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();
}

View File

@@ -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<Object,Object> redisOperations;
RedisOperations<Object, Object> redisOperations;
@Mock
BoundValueOperations<Object, Object> boundValueOperations;
@Mock
@@ -93,7 +90,7 @@ public class RedisOperationsSessionRepositoryTests {
@Captor
ArgumentCaptor<AbstractSessionEvent> event;
@Captor
ArgumentCaptor<Map<String,Object>> delta;
ArgumentCaptor<Map<String, Object>> 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<String,Object> delta = getDelta();
Map<String, Object> 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.<Object>singleton(expiredId));
when(redisOperations.boundHashOps(getKey(expiredId))).thenReturn(boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.<Object>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.<Object>singleton(sessionId));
when(redisOperations.boundHashOps(getKey(sessionId))).thenReturn(boundHashOperations);
given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
given(this.boundSetOperations.members()).willReturn(Collections.<Object>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<String, RedisSession> sessionIdToSessions = redisRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal");
Map<String, RedisSession> 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<Object> expiredIds = new HashSet<Object>(Arrays.asList("expired-key1","expired-key2"));
when(boundSetOperations.members()).thenReturn(expiredIds);
Set<Object> expiredIds = new HashSet<Object>(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<String,Object>());
given(this.defaultSerializer.deserialize(body)).willReturn(new HashMap<String, Object>());
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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String,Object> result = new HashMap<String,Object>();
if(objects == null) {
Map<String, Object> result = new HashMap<String, Object>();
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<String,Object> getDelta() {
private Map<String, Object> getDelta() {
return getDelta(1);
}
private Map<String,Object> getDelta(int times) {
verify(boundHashOperations,times(times)).putAll(delta.capture());
return delta.getAllValues().get(times - 1);
private Map<String, Object> getDelta(int times) {
verify(this.boundHashOperations, times(times)).putAll(this.delta.capture());
return this.delta.getAllValues().get(times - 1);
}
}
}

View File

@@ -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<Object,Object> sessionRedisOperations;
RedisOperations<Object, Object> sessionRedisOperations;
@Mock
BoundSetOperations<Object,Object> setOperations;
BoundSetOperations<Object, Object> setOperations;
@Mock
BoundHashOperations<Object,Object, Object> hashOperations;
BoundHashOperations<Object, Object, Object> hashOperations;
@Mock
BoundValueOperations<Object, Object> 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);
}
}

View File

@@ -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 {

View File

@@ -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<String> 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));
}
}
}

View File

@@ -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;
}
}
}

View File

@@ -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

View File

@@ -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<Object,Object> template;
RedisTemplate<Object, Object> template;
@Autowired
RedisSerializer<Object> 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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}
}
}

View File

@@ -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;
}
}
}

View File

@@ -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<Object, Object> 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;
}
}

View File

@@ -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", "\"> <script>alert('hi')</script>")).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", "\"> <script>alert('hi')</script>")).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, "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 getCurrentSessionAliasContainsGt() {
strategy.setSessionAliasParamName(null);
request.setParameter(CookieHttpSessionStrategy.DEFAULT_SESSION_ALIAS_PARAM_NAME, "here>this");
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<String, String> sessionIds = strategy.getSessionIds(request);
Map<String, String> 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<String, String> sessionIds = strategy.getSessionIds(request);
Map<String, String> 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<String, String> sessionIds = strategy.getSessionIds(request);
Map<String, String> 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();
}
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}
}

View File

@@ -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<OncePerRequestFilter>();
filter = new OncePerRequestFilter() {
this.servlet = new HttpServlet() {
};
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
this.invocations = new ArrayList<OncePerRequestFilter>();
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);
}
}
}

View File

@@ -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.<HttpSessionListener>emptyList());
destroyed = mock(SessionDestroyedEvent.class);
this.listener = new SessionEventHttpSessionListenerAdapter(Collections.<HttpSessionListener>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());
}
}

View File

@@ -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<String, ExpiringSession>();
sessionRepository = new MapSessionRepository(sessions);
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.sessions = new HashMap<String, ExpiringSession>();
this.sessionRepository = new MapSessionRepository(this.sessions);
this.filter = new SessionRepositoryFilter<ExpiringSession>(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<ExpiringSession>(sessionRepository);
given(this.sessionRepository.createSession()).willReturn(session);
this.filter = new SessionRepositoryFilter<ExpiringSession>(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<ExpiringSession>(sessionRepository);
filter.setServletContext(expectedContext);
this.filter = new SessionRepositoryFilter<ExpiringSession>(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<ExpiringSession>(sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(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<ExpiringSession> sessionRepository = spy(new MapSessionRepository());
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(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<ExpiringSession> sessionRepository = spy(new MapSessionRepository());
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(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<ExpiringSession> sessionRepository = spy(this.sessionRepository);
setSessionCookie(session.getId());
filter = new SessionRepositoryFilter<ExpiringSession>(sessionRepository);
this.filter = new SessionRepositoryFilter<ExpiringSession>(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<String,Cookie> nameToCookie = new HashMap<String,Cookie>();
if (request.getCookies() != null) {
for(Cookie cookie : request.getCookies()) {
Map<String, Cookie> nameToCookie = new HashMap<String, Cookie>();
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;
}
}
}
}

View File

@@ -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));
}
}

View File

@@ -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<String, Object> attributes;
@@ -72,101 +74,101 @@ public class WebSocketRegistryListenerTests {
@Before
public void setup() {
sessionId = "session-id";
attributes = new HashMap<String,Object>();
SessionRepositoryMessageInterceptor.setSessionId(attributes, sessionId);
this.sessionId = "session-id";
this.attributes = new HashMap<String, Object>();
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<String,Object> headers = new HashMap<String,Object>();
headers.put(SimpMessageHeaderAccessor.SESSION_ATTRIBUTES, attributes);
when(message.getHeaders()).thenReturn(new MessageHeaders(headers));
Map<String, Object> headers = new HashMap<String, Object>();
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<String,Map<String,WebSocketSession>> httpSessionIdToWsSessions =
(Map<String, Map<String, WebSocketSession>>) ReflectionTestUtils.getField(listener, "httpSessionIdToWsSessions");
Map<String, Map<String, WebSocketSession>> httpSessionIdToWsSessions =
(Map<String, Map<String, WebSocketSession>>) 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));
}
}

View File

@@ -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<ExpiringSession>(sessionRepository);
headers = SimpMessageHeaderAccessor.create();
headers.setSessionId("session");
headers.setSessionAttributes(new HashMap<String,Object>());
this.interceptor = new SessionRepositoryMessageInterceptor<ExpiringSession>(this.sessionRepository);
this.headers = SimpMessageHeaderAccessor.create();
this.headers.setSessionId("session");
this.headers.setSessionAttributes(new HashMap<String, Object>());
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.<SimpMessageType>emptySet());
this.interceptor.setMatchingMessageTypes(Collections.<SimpMessageType>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<String,Object> attributes = new HashMap<String,Object>();
Map<String, Object> attributes = new HashMap<String, Object>();
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() {