Session Optional<T> getAttribute -> T getAttribute

Issue gh-819
This commit is contained in:
Rob Winch
2017-06-30 10:07:58 -05:00
parent ab3e280993
commit 8ef36e4f3e
19 changed files with 120 additions and 167 deletions

View File

@@ -16,15 +16,11 @@
package docs; package docs;
import java.time.Duration;
import java.util.Optional;
import com.hazelcast.config.Config; import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast; import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap; import com.hazelcast.core.IMap;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@@ -40,6 +36,8 @@ import org.springframework.session.web.http.SessionRepositoryFilter;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/** /**
@@ -73,8 +71,8 @@ public class IndexDocTests {
S session = this.repository.findById(toSave.getId()); // <5> S session = this.repository.findById(toSave.getId()); // <5>
// <6> // <6>
Optional<User> user = session.getAttribute(ATTR_USER); User user = session.getAttribute(ATTR_USER);
assertThat(user.orElse(null)).isEqualTo(rwinch); assertThat(user).isEqualTo(rwinch);
} }
// ... setter methods ... // ... setter methods ...

View File

@@ -18,7 +18,7 @@
<th>Information</th> <th>Information</th>
<th>Terminate</th> <th>Terminate</th>
</tr> </tr>
<tr th:each="sessionElement : ${sessions}" th:with="details=${sessionElement.getAttribute('SESSION_DETAILS').orElse(null)}"> <tr th:each="sessionElement : ${sessions}" th:with="details=${sessionElement.getAttribute('SESSION_DETAILS')}">
<td th:text="${sessionElement.id.substring(30)}"></td> <td th:text="${sessionElement.id.substring(30)}"></td>
<td th:text="${details?.location}"></td> <td th:text="${details?.location}"></td>
<td th:text="${#temporals.format(sessionElement.creationTime.atZone(T(java.time.ZoneId).systemDefault()),'dd/MMM/yyyy HH:mm:ss')}"></td> <td th:text="${#temporals.format(sessionElement.creationTime.atZone(T(java.time.ZoneId).systemDefault()),'dd/MMM/yyyy HH:mm:ss')}"></td>

View File

@@ -16,23 +16,16 @@
package sample; package sample;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.session.web.http.HttpSessionManager;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
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 org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.session.web.http.HttpSessionManager;
public class UserAccountsFilter implements Filter { public class UserAccountsFilter implements Filter {
@@ -67,15 +60,15 @@ public class UserAccountsFilter implements Filter {
continue; continue;
} }
Optional<String> username = session.getAttribute("username"); String username = session.getAttribute("username");
if (!username.isPresent()) { if (username == null) {
unauthenticatedAlias = alias; unauthenticatedAlias = alias;
continue; continue;
} }
String logoutUrl = sessionManager.encodeURL("./logout", alias); String logoutUrl = sessionManager.encodeURL("./logout", alias);
String switchAccountUrl = sessionManager.encodeURL("./", alias); String switchAccountUrl = sessionManager.encodeURL("./", alias);
Account account = new Account(username.get(), logoutUrl, switchAccountUrl); Account account = new Account(username, logoutUrl, switchAccountUrl);
if (currentSessionAlias.equals(alias)) { if (currentSessionAlias.equals(alias)) {
currentAccount = account; currentAccount = account;
} }

View File

@@ -21,7 +21,6 @@ import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@@ -94,8 +93,10 @@ public final class MapSession implements Session, Serializable {
this.sessionAttrs = new HashMap<>( this.sessionAttrs = new HashMap<>(
session.getAttributeNames().size()); session.getAttributeNames().size());
for (String attrName : session.getAttributeNames()) { for (String attrName : session.getAttributeNames()) {
session.getAttribute(attrName) Object attrValue = session.getAttribute(attrName);
.ifPresent(attrValue -> this.sessionAttrs.put(attrName, attrValue)); if(attrValue != null) {
this.sessionAttrs.put(attrName, attrValue);
}
} }
this.lastAccessedTime = session.getLastAccessedTime(); this.lastAccessedTime = session.getLastAccessedTime();
this.creationTime = session.getCreationTime(); this.creationTime = session.getCreationTime();
@@ -138,8 +139,8 @@ public final class MapSession implements Session, Serializable {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> Optional<T> getAttribute(String attributeName) { public <T> T getAttribute(String attributeName) {
return Optional.ofNullable((T) this.sessionAttrs.get(attributeName)); return (T) this.sessionAttrs.get(attributeName);
} }
public Set<String> getAttributeNames() { public Set<String> getAttributeNames() {

View File

@@ -18,7 +18,6 @@ package org.springframework.session;
import java.time.Duration; import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import java.util.Optional;
import java.util.Set; import java.util.Set;
/** /**
@@ -42,12 +41,12 @@ public interface Session {
* Gets the Object associated with the specified name or null if no Object is * Gets the Object associated with the specified name or null if no Object is
* associated to that name. * associated to that name.
* *
* @param <T> The return type of the attribute
* @param attributeName the name of the attribute to get * @param attributeName the name of the attribute to get
* @return the Object associated with the specified name or null if no Object is * @return the Object associated with the specified name or null if no Object is
* associated to that name * associated to that name
* @param <T> The return type of the attribute
*/ */
<T> Optional<T> getAttribute(String attributeName); <T> T getAttribute(String attributeName);
/** /**
* Gets the attribute names that have a value associated with it. Each value can be * Gets the attribute names that have a value associated with it. Each value can be

View File

@@ -17,7 +17,6 @@
package org.springframework.session.security; package org.springframework.session.security;
import java.util.Date; import java.util.Date;
import java.util.Optional;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@@ -55,11 +54,10 @@ class SpringSessionBackedSessionInformation<S extends Session>
super(resolvePrincipal(session), session.getId(), super(resolvePrincipal(session), session.getId(),
Date.from(session.getLastAccessedTime())); Date.from(session.getLastAccessedTime()));
this.sessionRepository = sessionRepository; this.sessionRepository = sessionRepository;
session.getAttribute(EXPIRED_ATTR).ifPresent(expired -> { Boolean expired = session.getAttribute(EXPIRED_ATTR);
if (Boolean.TRUE.equals(expired)) { if (Boolean.TRUE.equals(expired)) {
super.expireNow(); super.expireNow();
} }
});
} }
/** /**
@@ -69,16 +67,16 @@ class SpringSessionBackedSessionInformation<S extends Session>
* @return the principal's name, or empty String if it couldn't be determined * @return the principal's name, or empty String if it couldn't be determined
*/ */
private static String resolvePrincipal(Session session) { private static String resolvePrincipal(Session session) {
Optional<String> principalName = session String principalName = session
.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); .getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName.isPresent()) { if (principalName != null) {
return principalName.get(); return principalName;
} }
Optional<SecurityContext> securityContext = session SecurityContext securityContext = session
.getAttribute(SPRING_SECURITY_CONTEXT); .getAttribute(SPRING_SECURITY_CONTEXT);
if (securityContext.isPresent() if (securityContext != null
&& securityContext.get().getAuthentication() != null) { && securityContext.getAuthentication() != null) {
return securityContext.get().getAuthentication().getName(); return securityContext.getAuthentication().getName();
} }
return ""; return "";
} }

View File

@@ -69,7 +69,7 @@ public class SpringSessionBackedSessionRegistry<S extends Session>
List<SessionInformation> infos = new ArrayList<>(); List<SessionInformation> infos = new ArrayList<>();
for (S session : sessions) { for (S session : sessions) {
if (includeExpiredSessions || !Boolean.TRUE.equals(session if (includeExpiredSessions || !Boolean.TRUE.equals(session
.getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR).orElse(false))) { .getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))) {
infos.add(new SpringSessionBackedSessionInformation<>(session, infos.add(new SpringSessionBackedSessionInformation<>(session,
this.sessionRepository)); this.sessionRepository));
} }

View File

@@ -16,18 +16,17 @@
package org.springframework.session.web.http; package org.springframework.session.web.http;
import org.springframework.session.Session;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import java.time.Duration; import java.time.Duration;
import java.util.Collections; import java.util.Collections;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import org.springframework.session.Session;
/** /**
* Adapts Spring Session's {@link Session} to an {@link HttpSession}. * Adapts Spring Session's {@link Session} to an {@link HttpSession}.
* *
@@ -87,7 +86,7 @@ class HttpSessionAdapter<S extends Session> implements HttpSession {
public Object getAttribute(String name) { public Object getAttribute(String name) {
checkState(); checkState();
return this.session.getAttribute(name).orElse(null); return this.session.getAttribute(name);
} }
public Object getValue(String name) { public Object getValue(String name) {

View File

@@ -16,14 +16,13 @@
package org.springframework.session; package org.springframework.session;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public class MapSessionTests { public class MapSessionTests {
@@ -114,8 +113,8 @@ public class MapSessionTests {
return Duration.ZERO; return Duration.ZERO;
} }
public <T> Optional<T> getAttribute(String attributeName) { public <T> T getAttribute(String attributeName) {
return Optional.empty(); return null;
} }
public Set<String> getAttributeNames() { public Set<String> getAttributeNames() {

View File

@@ -16,20 +16,12 @@
package org.springframework.session.security; package org.springframework.session.security;
import java.time.Instant;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.session.SessionInformation; import org.springframework.security.core.session.SessionInformation;
@@ -38,10 +30,14 @@ import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.MapSession; import org.springframework.session.MapSession;
import org.springframework.session.Session; import org.springframework.session.Session;
import java.time.Instant;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.mock; import static org.mockito.BDDMockito.*;
import static org.mockito.BDDMockito.verify;
import static org.mockito.BDDMockito.when;
/** /**
* Tests for {@link SpringSessionBackedSessionRegistry}. * Tests for {@link SpringSessionBackedSessionRegistry}.
@@ -140,7 +136,7 @@ public class SpringSessionBackedSessionRegistryTest {
verify(this.sessionRepository).save(captor.capture()); verify(this.sessionRepository).save(captor.capture());
assertThat(captor.getValue().<Boolean>getAttribute( assertThat(captor.getValue().<Boolean>getAttribute(
SpringSessionBackedSessionInformation.EXPIRED_ATTR)) SpringSessionBackedSessionInformation.EXPIRED_ATTR))
.isEqualTo(Optional.of(Boolean.TRUE)); .isEqualTo(Boolean.TRUE);
} }
private Session createSession(String sessionId, String userName, private Session createSession(String sessionId, String userName,

View File

@@ -15,12 +15,7 @@
*/ */
package org.springframework.session.data.redis; package org.springframework.session.data.redis;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -42,6 +37,9 @@ import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionDestroyedEvent; import org.springframework.session.events.SessionDestroyedEvent;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ContextConfiguration @ContextConfiguration
@@ -102,7 +100,7 @@ public class RedisOperationsSessionRepositoryITests extends AbstractITests {
assertThat(this.registry.getEvent(toSave.getId()).getSession() assertThat(this.registry.getEvent(toSave.getId()).getSession()
.<String>getAttribute(expectedAttributeName)) .<String>getAttribute(expectedAttributeName))
.isEqualTo(Optional.of(expectedAttributeValue)); .isEqualTo(expectedAttributeValue);
} }
@Test @Test
@@ -120,8 +118,8 @@ public class RedisOperationsSessionRepositoryITests extends AbstractITests {
Session session = this.repository.findById(toSave.getId()); Session session = this.repository.findById(toSave.getId());
assertThat(session.getAttributeNames().size()).isEqualTo(2); assertThat(session.getAttributeNames().size()).isEqualTo(2);
assertThat(session.<String>getAttribute("a")).isEqualTo(Optional.of("b")); assertThat(session.<String>getAttribute("a")).isEqualTo("b");
assertThat(session.<String>getAttribute("1")).isEqualTo(Optional.of("2")); assertThat(session.<String>getAttribute("1")).isEqualTo("2");
this.repository.deleteById(toSave.getId()); this.repository.deleteById(toSave.getId());
} }

View File

@@ -16,17 +16,8 @@
package org.springframework.session.data.redis; package org.springframework.session.data.redis;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.Message;
@@ -51,6 +42,13 @@ import org.springframework.session.events.SessionExpiredEvent;
import org.springframework.session.web.http.SessionRepositoryFilter; import org.springframework.session.web.http.SessionRepositoryFilter;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/** /**
* <p> * <p>
* A {@link org.springframework.session.SessionRepository} that is implemented using * A {@link org.springframework.session.SessionRepository} that is implemented using
@@ -740,7 +738,7 @@ public class RedisOperationsSessionRepository implements
return this.cached.getMaxInactiveInterval(); return this.cached.getMaxInactiveInterval();
} }
public <T> Optional<T> getAttribute(String attributeName) { public <T> T getAttribute(String attributeName) {
return this.cached.getAttribute(attributeName); return this.cached.getAttribute(attributeName);
} }
@@ -816,15 +814,15 @@ public class RedisOperationsSessionRepository implements
private SpelExpressionParser parser = new SpelExpressionParser(); private SpelExpressionParser parser = new SpelExpressionParser();
public String resolvePrincipal(Session session) { public String resolvePrincipal(Session session) {
Optional<String> principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME); String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);
if (principalName.isPresent()) { if (principalName != null) {
return principalName.get(); return principalName;
} }
Optional<Object> authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication.isPresent()) { if (authentication != null) {
Expression expression = this.parser Expression expression = this.parser
.parseExpression("authentication?.name"); .parseExpression("authentication?.name");
return expression.getValue(authentication.get(), String.class); return expression.getValue(authentication, String.class);
} }
return null; return null;
} }

View File

@@ -16,17 +16,6 @@
package org.springframework.session.data.redis; package org.springframework.session.data.redis;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -34,7 +23,6 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.connection.DefaultMessage; import org.springframework.data.redis.connection.DefaultMessage;
import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnection;
@@ -57,17 +45,18 @@ import org.springframework.session.data.redis.RedisOperationsSessionRepository.P
import org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession; import org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession;
import org.springframework.session.events.AbstractSessionEvent; import org.springframework.session.events.AbstractSessionEvent;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.*;
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) @RunWith(MockitoJUnitRunner.class)
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
@@ -273,7 +262,7 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(getDelta()).isEqualTo( assertThat(getDelta()).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName).orElse(null))); session.getAttribute(attrName)));
} }
@Test @Test
@@ -332,7 +321,7 @@ public class RedisOperationsSessionRepositoryTests {
given(this.redisOperations.boundSetOps(anyString())) given(this.redisOperations.boundSetOps(anyString()))
.willReturn(this.boundSetOperations); .willReturn(this.boundSetOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
expected.getAttribute(attrName).orElse(null), expected.getAttribute(attrName),
RedisOperationsSessionRepository.CREATION_TIME_ATTR, RedisOperationsSessionRepository.CREATION_TIME_ATTR,
expected.getCreationTime().toEpochMilli(), expected.getCreationTime().toEpochMilli(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, RedisOperationsSessionRepository.MAX_INACTIVE_ATTR,
@@ -382,7 +371,7 @@ public class RedisOperationsSessionRepositoryTests {
given(this.redisOperations.boundHashOps(getKey(expected.getId()))) given(this.redisOperations.boundHashOps(getKey(expected.getId())))
.willReturn(this.boundHashOperations); .willReturn(this.boundHashOperations);
Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
expected.getAttribute(attrName).orElse(null), expected.getAttribute(attrName),
RedisOperationsSessionRepository.CREATION_TIME_ATTR, RedisOperationsSessionRepository.CREATION_TIME_ATTR,
expected.getCreationTime().toEpochMilli(), expected.getCreationTime().toEpochMilli(),
RedisOperationsSessionRepository.MAX_INACTIVE_ATTR, RedisOperationsSessionRepository.MAX_INACTIVE_ATTR,
@@ -630,7 +619,7 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(delta.size()).isEqualTo(1); assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo( assertThat(delta).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName).orElse(null))); session.getAttribute(attrName)));
} }
@Test @Test
@@ -651,7 +640,7 @@ public class RedisOperationsSessionRepositoryTests {
assertThat(delta.size()).isEqualTo(1); assertThat(delta.size()).isEqualTo(1);
assertThat(delta).isEqualTo( assertThat(delta).isEqualTo(
map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName),
session.getAttribute(attrName).orElse(null))); session.getAttribute(attrName)));
} }
@Test @Test

View File

@@ -22,7 +22,6 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -327,7 +326,7 @@ public class HazelcastSessionRepository implements
return this.delegate.getMaxInactiveInterval(); return this.delegate.getMaxInactiveInterval();
} }
public <T> Optional<T> getAttribute(String attributeName) { public <T> T getAttribute(String attributeName) {
return this.delegate.getAttribute(attributeName); return this.delegate.getAttribute(attributeName);
} }

View File

@@ -16,11 +16,8 @@
package org.springframework.session.hazelcast; package org.springframework.session.hazelcast;
import java.util.Optional;
import com.hazelcast.query.extractor.ValueCollector; import com.hazelcast.query.extractor.ValueCollector;
import com.hazelcast.query.extractor.ValueExtractor; import com.hazelcast.query.extractor.ValueExtractor;
import org.springframework.expression.Expression; import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.FindByIndexNameSessionRepository;
@@ -58,16 +55,16 @@ public class PrincipalNameExtractor extends ValueExtractor<MapSession, String> {
private SpelExpressionParser parser = new SpelExpressionParser(); private SpelExpressionParser parser = new SpelExpressionParser();
public String resolvePrincipal(Session session) { public String resolvePrincipal(Session session) {
Optional<String> principalName = session.getAttribute( String principalName = session.getAttribute(
FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName.isPresent()) { if (principalName != null) {
return principalName.get(); return principalName;
} }
Optional<Object> authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication.isPresent()) { if (authentication != null) {
Expression expression = this.parser Expression expression = this.parser
.parseExpression("authentication?.name"); .parseExpression("authentication?.name");
return expression.getValue(authentication.get(), String.class); return expression.getValue(authentication, String.class);
} }
return null; return null;
} }

View File

@@ -272,7 +272,7 @@ public class HazelcastSessionRepositoryTests {
HazelcastSession session = this.repository.findById(saved.getId()); HazelcastSession session = this.repository.findById(saved.getId());
assertThat(session.getId()).isEqualTo(saved.getId()); assertThat(session.getId()).isEqualTo(saved.getId());
assertThat(session.<String>getAttribute("savedName").orElse(null)).isEqualTo("savedValue"); assertThat(session.<String>getAttribute("savedName")).isEqualTo("savedValue");
verify(this.sessions, times(1)).get(eq(saved.getId())); verify(this.sessions, times(1)).get(eq(saved.getId()));
} }

View File

@@ -16,19 +16,9 @@
package org.springframework.session.jdbc; package org.springframework.session.jdbc;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import javax.sql.DataSource;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@@ -47,6 +37,13 @@ import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/** /**
@@ -139,8 +136,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests {
Session session = this.repository.findById(toSave.getId()); Session session = this.repository.findById(toSave.getId());
assertThat(session.getAttributeNames().size()).isEqualTo(2); assertThat(session.getAttributeNames().size()).isEqualTo(2);
assertThat(session.<String>getAttribute("a")).isEqualTo(Optional.of("b")); assertThat(session.<String>getAttribute("a")).isEqualTo("b");
assertThat(session.<String>getAttribute("1")).isEqualTo(Optional.of("2")); assertThat(session.<String>getAttribute("1")).isEqualTo("2");
this.repository.deleteById(toSave.getId()); this.repository.deleteById(toSave.getId());
} }

View File

@@ -16,24 +16,8 @@
package org.springframework.session.jdbc; package org.springframework.session.jdbc;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.convert.support.GenericConversionService;
@@ -61,6 +45,14 @@ import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
/** /**
* A {@link org.springframework.session.SessionRepository} implementation that uses * A {@link org.springframework.session.SessionRepository} implementation that uses
* Spring's {@link JdbcOperations} to store sessions in a relational database. This * Spring's {@link JdbcOperations} to store sessions in a relational database. This
@@ -395,7 +387,7 @@ public class JdbcOperationsSessionRepository implements
String attributeName = attributeNames.get(i); String attributeName = attributeNames.get(i);
ps.setString(1, session.getId()); ps.setString(1, session.getId());
ps.setString(2, attributeName); ps.setString(2, attributeName);
serialize(ps, 3, session.getAttribute(attributeName).orElse(null)); serialize(ps, 3, session.getAttribute(attributeName));
} }
public int getBatchSize() { public int getBatchSize() {
@@ -639,7 +631,7 @@ public class JdbcOperationsSessionRepository implements
return this.delegate.getId(); return this.delegate.getId();
} }
public <T> Optional<T> getAttribute(String attributeName) { public <T> T getAttribute(String attributeName) {
return this.delegate.getAttribute(attributeName); return this.delegate.getAttribute(attributeName);
} }
@@ -699,15 +691,15 @@ public class JdbcOperationsSessionRepository implements
private SpelExpressionParser parser = new SpelExpressionParser(); private SpelExpressionParser parser = new SpelExpressionParser();
public String resolvePrincipal(Session session) { public String resolvePrincipal(Session session) {
Optional<String> principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME); String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);
if (principalName.isPresent()) { if (principalName != null) {
return principalName.get(); return principalName;
} }
Optional<Object> authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (authentication.isPresent()) { if (authentication != null) {
Expression expression = this.parser Expression expression = this.parser
.parseExpression("authentication?.name"); .parseExpression("authentication?.name");
return expression.getValue(authentication.get(), String.class); return expression.getValue(authentication, String.class);
} }
return null; return null;
} }

View File

@@ -445,7 +445,7 @@ public class JdbcOperationsSessionRepositoryTests {
assertThat(session.getId()).isEqualTo(saved.getId()); assertThat(session.getId()).isEqualTo(saved.getId());
assertThat(session.isNew()).isFalse(); assertThat(session.isNew()).isFalse();
assertThat(session.<String>getAttribute("savedName").orElse(null)).isEqualTo("savedValue"); assertThat(session.<String>getAttribute("savedName")).isEqualTo("savedValue");
assertPropagationRequiresNew(); assertPropagationRequiresNew();
verify(this.jdbcOperations, times(1)).query(isA(String.class), verify(this.jdbcOperations, times(1)).query(isA(String.class),
isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class));