Skip to content

Commit

Permalink
Improve Session API to use Java 8
Browse files Browse the repository at this point in the history
  • Loading branch information
vpavic authored and rwinch committed Jun 16, 2017
1 parent 4cf26d9 commit f7e07b7
Show file tree
Hide file tree
Showing 33 changed files with 370 additions and 310 deletions.
9 changes: 6 additions & 3 deletions docs/src/test/java/docs/IndexDocTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

package docs;

import java.time.Duration;
import java.util.Optional;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
Expand Down Expand Up @@ -70,8 +73,8 @@ public void demo() {
S session = this.repository.getSession(toSave.getId()); // <5>

// <6>
User user = session.getAttribute(ATTR_USER);
assertThat(user).isEqualTo(rwinch);
Optional<User> user = session.getAttribute(ATTR_USER);
assertThat(user.orElse(null)).isEqualTo(rwinch);
}

// ... setter methods ...
Expand All @@ -93,7 +96,7 @@ public class ExpiringRepositoryDemo<S extends Session> {
public void demo() {
S toSave = this.repository.createSession(); // <2>
// ...
toSave.setMaxInactiveIntervalInSeconds(30); // <3>
toSave.setMaxInactiveInterval(Duration.ofSeconds(30)); // <3>

this.repository.save(toSave); // <4>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

package docs.security;

import java.time.Duration;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;

Expand Down Expand Up @@ -82,8 +82,8 @@ public void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSes
assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE);
T session = this.sessions
.getSession(new String(Base64.getDecoder().decode(cookie.getValue())));
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo((int) TimeUnit.DAYS.toSeconds(30));
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofDays(30));

}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

package docs.security;

import java.time.Duration;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;

Expand Down Expand Up @@ -82,8 +82,8 @@ public void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSes
assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE);
T session = this.sessions
.getSession(new String(Base64.getDecoder().decode(cookie.getValue())));
assertThat(session.getMaxInactiveIntervalInSeconds())
.isEqualTo((int) TimeUnit.DAYS.toSeconds(30));
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofDays(30));

}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ dependencies {
compile "org.springframework.boot:spring-boot-starter-security"
compile "org.springframework.boot:spring-boot-devtools"
compile "nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect"
compile "org.thymeleaf.extras:thymeleaf-extras-java8time"
compile "org.webjars:bootstrap"
compile "org.webjars:html5shiv"
compile "org.webjars:webjars-locator"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ <h1>Secured Page</h1>
<th>Information</th>
<th>Terminate</th>
</tr>
<tr th:each="sessionElement : ${sessions}" th:with="details=${sessionElement.getAttribute('SESSION_DETAILS')}">
<tr th:each="sessionElement : ${sessions}" th:with="details=${sessionElement.getAttribute('SESSION_DETAILS').orElse(null)}">
<td th:text="${sessionElement.id.substring(30)}"></td>
<td th:text="${details?.location}"></td>
<td th:text="${#dates.format(new java.util.Date(sessionElement.creationTime),'dd/MMM/yyyy HH:mm:ss')}"></td>
<td th:text="${#dates.format(new java.util.Date(sessionElement.lastAccessedTime),'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>
<td th:text="${#temporals.format(sessionElement.lastAccessedTime.atZone(T(java.time.ZoneId).systemDefault()),'dd/MMM/yyyy HH:mm:ss')}"></td>
<td th:text="${details?.accessType}"></td>
<td>
<form th:action="@{'/sessions/' + ${sessionElement.id}}" th:method="delete">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
Expand Down Expand Up @@ -66,15 +67,15 @@ public void doFilter(ServletRequest request, ServletResponse response,
continue;
}

String username = session.getAttribute("username");
if (username == null) {
Optional<String> username = session.getAttribute("username");
if (!username.isPresent()) {
unauthenticatedAlias = alias;
continue;
}

String logoutUrl = sessionManager.encodeURL("./logout", alias);
String switchAccountUrl = sessionManager.encodeURL("./", alias);
Account account = new Account(username, logoutUrl, switchAccountUrl);
Account account = new Account(username.get(), logoutUrl, switchAccountUrl);
if (currentSessionAlias.equals(alias)) {
currentAccount = account;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,7 @@
package org.springframework.session.data.redis;

import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import org.junit.Test;
Expand Down Expand Up @@ -100,7 +101,8 @@ public void saves() throws InterruptedException {
.doesNotContain(toSave.getId());

assertThat(this.registry.getEvent(toSave.getId()).getSession()
.<String>getAttribute(expectedAttributeName)).isEqualTo(expectedAttributeValue);
.<String>getAttribute(expectedAttributeName))
.isEqualTo(Optional.of(expectedAttributeValue));
}

@Test
Expand All @@ -118,8 +120,8 @@ public void putAllOnSingleAttrDoesNotRemoveOld() {

Session session = this.repository.getSession(toSave.getId());
assertThat(session.getAttributeNames().size()).isEqualTo(2);
assertThat(session.<String>getAttribute("a")).isEqualTo("b");
assertThat(session.<String>getAttribute("1")).isEqualTo("2");
assertThat(session.<String>getAttribute("a")).isEqualTo(Optional.of("b"));
assertThat(session.<String>getAttribute("1")).isEqualTo(Optional.of("2"));

this.repository.delete(toSave.getId());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public void expireFiresSessionExpiredEvent() throws InterruptedException {
this.repository.save(toSave);

synchronized (this.lock) {
this.lock.wait((toSave.getMaxInactiveIntervalInSeconds() * 1000) + 1);
this.lock.wait(toSave.getMaxInactiveInterval().plusMillis(1).toMillis());
}
if (!this.registry.receivedEvent()) {
// Redis makes no guarantees on when an expired event will be fired
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

package org.springframework.session.hazelcast.config.annotation.web.http;

import java.time.Duration;
import java.time.Instant;

import com.hazelcast.core.HazelcastInstance;
import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -111,8 +114,8 @@ public void expiredSessionTest() throws InterruptedException {
.isInstanceOf(SessionCreatedEvent.class);
this.registry.clear();

assertThat(sessionToSave.getMaxInactiveIntervalInSeconds())
.isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS);
assertThat(sessionToSave.getMaxInactiveInterval())
.isEqualTo(Duration.ofSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS));

assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
assertThat(this.registry.<SessionExpiredEvent>getEvent(sessionToSave.getId()))
Expand Down Expand Up @@ -150,16 +153,16 @@ public void saveUpdatesTimeToLiveTest() throws InterruptedException {
this.repository.save(sessionToSave);

synchronized (lock) {
lock.wait((sessionToSave.getMaxInactiveIntervalInSeconds() * 1000) - 500);
lock.wait(sessionToSave.getMaxInactiveInterval().minusMillis(500).toMillis());
}

// Get and save the session like SessionRepositoryFilter would.
S sessionToUpdate = this.repository.getSession(sessionToSave.getId());
sessionToUpdate.setLastAccessedTime(System.currentTimeMillis());
sessionToUpdate.setLastAccessedTime(Instant.now());
this.repository.save(sessionToUpdate);

synchronized (lock) {
lock.wait((sessionToUpdate.getMaxInactiveIntervalInSeconds() * 1000) - 100);
lock.wait(sessionToUpdate.getMaxInactiveInterval().minusMillis(100).toMillis());
}

assertThat(this.repository.getSession(sessionToUpdate.getId())).isNotNull();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package org.springframework.session.hazelcast.config.annotation.web.http;

import java.time.Duration;

import com.hazelcast.config.ClasspathXmlConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.NetworkConfig;
Expand Down Expand Up @@ -62,7 +64,8 @@ public void saveSessionTest() throws InterruptedException {
S session = this.repository.getSession(sessionToSave.getId());

assertThat(session.getId()).isEqualTo(sessionToSave.getId());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(1800);
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofMinutes(30));
}

@Configuration
Expand Down Expand Up @@ -99,7 +102,8 @@ public void saveSessionTest() throws InterruptedException {
S session = this.repository.getSession(sessionToSave.getId());

assertThat(session.getId()).isEqualTo(sessionToSave.getId());
assertThat(session.getMaxInactiveIntervalInSeconds()).isEqualTo(1200);
assertThat(session.getMaxInactiveInterval())
.isEqualTo(Duration.ofMinutes(20));
}

@Configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@

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 java.util.concurrent.TimeUnit;

import javax.sql.DataSource;

Expand Down Expand Up @@ -136,8 +139,8 @@ public void putAllOnSingleAttrDoesNotRemoveOld() {

Session session = this.repository.getSession(toSave.getId());
assertThat(session.getAttributeNames().size()).isEqualTo(2);
assertThat(session.<String>getAttribute("a")).isEqualTo("b");
assertThat(session.<String>getAttribute("1")).isEqualTo("2");
assertThat(session.<String>getAttribute("a")).isEqualTo(Optional.of("b"));
assertThat(session.<String>getAttribute("1")).isEqualTo(Optional.of("2"));

this.repository.delete(toSave.getId());
}
Expand All @@ -146,12 +149,12 @@ public void putAllOnSingleAttrDoesNotRemoveOld() {
public void updateLastAccessedTime() {
JdbcOperationsSessionRepository.JdbcSession toSave = this.repository
.createSession();
toSave.setLastAccessedTime(System.currentTimeMillis()
- (MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS * 1000 + 1000));
toSave.setLastAccessedTime(Instant.now().minusSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));

this.repository.save(toSave);

long lastAccessedTime = System.currentTimeMillis();
Instant lastAccessedTime = Instant.now();
toSave.setLastAccessedTime(lastAccessedTime);
this.repository.save(toSave);

Expand Down Expand Up @@ -193,8 +196,8 @@ public void findByPrincipalNameExpireRemovesIndex() throws Exception {
JdbcOperationsSessionRepository.JdbcSession toSave = this.repository
.createSession();
toSave.setAttribute(INDEX_NAME, principalName);
toSave.setLastAccessedTime(System.currentTimeMillis()
- (MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS * 1000 + 1000));
toSave.setLastAccessedTime(Instant.now().minusSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS+ 1));

this.repository.save(toSave);
this.repository.cleanUpExpiredSessions();
Expand Down Expand Up @@ -365,8 +368,8 @@ public void findBySecurityPrincipalNameExpireRemovesIndex() throws Exception {
JdbcOperationsSessionRepository.JdbcSession toSave = this.repository
.createSession();
toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context);
toSave.setLastAccessedTime(System.currentTimeMillis()
- (MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS * 1000 + 1000));
toSave.setLastAccessedTime(Instant.now().minusSeconds(
MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));

this.repository.save(toSave);
this.repository.cleanUpExpiredSessions();
Expand Down Expand Up @@ -513,15 +516,15 @@ public void cleanupInactiveSessionsUsingRepositoryDefinedInterval() {

assertThat(this.repository.getSession(session.getId())).isNotNull();

long now = System.currentTimeMillis();
Instant now = Instant.now();

session.setLastAccessedTime(now - TimeUnit.MINUTES.toMillis(10));
session.setLastAccessedTime(now.minus(10, ChronoUnit.MINUTES));
this.repository.save(session);
this.repository.cleanUpExpiredSessions();

assertThat(this.repository.getSession(session.getId())).isNotNull();

session.setLastAccessedTime(now - TimeUnit.MINUTES.toMillis(30));
session.setLastAccessedTime(now.minus(30, ChronoUnit.MINUTES));
this.repository.save(session);
this.repository.cleanUpExpiredSessions();

Expand All @@ -533,7 +536,7 @@ public void cleanupInactiveSessionsUsingRepositoryDefinedInterval() {
public void cleanupInactiveSessionsUsingSessionDefinedInterval() {
JdbcOperationsSessionRepository.JdbcSession session = this.repository
.createSession();
session.setMaxInactiveIntervalInSeconds((int) TimeUnit.MINUTES.toSeconds(45));
session.setMaxInactiveInterval(Duration.ofMinutes(45));

this.repository.save(session);

Expand All @@ -543,15 +546,15 @@ public void cleanupInactiveSessionsUsingSessionDefinedInterval() {

assertThat(this.repository.getSession(session.getId())).isNotNull();

long now = System.currentTimeMillis();
Instant now = Instant.now();

session.setLastAccessedTime(now - TimeUnit.MINUTES.toMillis(40));
session.setLastAccessedTime(now.minus(40, ChronoUnit.MINUTES));
this.repository.save(session);
this.repository.cleanUpExpiredSessions();

assertThat(this.repository.getSession(session.getId())).isNotNull();

session.setLastAccessedTime(now - TimeUnit.MINUTES.toMillis(50));
session.setLastAccessedTime(now.minus(50, ChronoUnit.MINUTES));
this.repository.save(session);
this.repository.cleanUpExpiredSessions();

Expand Down
Loading

0 comments on commit f7e07b7

Please sign in to comment.