Add default methods to Session

Fixes gh-819
This commit is contained in:
Rob Winch
2017-06-30 10:19:58 -05:00
parent 8ef36e4f3e
commit 36bb65e4b5
2 changed files with 70 additions and 0 deletions

View File

@@ -16,6 +16,8 @@
package org.springframework.session;
import org.springframework.util.Assert;
import java.time.Duration;
import java.time.Instant;
import java.util.Set;
@@ -48,6 +50,33 @@ public interface Session {
*/
<T> T getAttribute(String attributeName);
/**
* Return the session attribute value or if not present raise an
* {@link IllegalArgumentException}.
* @param name the attribute name
* @param <T> the attribute type
* @return the attribute value
*/
@SuppressWarnings("unchecked")
default <T> T getRequiredAttribute(String name) {
T result = getAttribute(name);
Assert.notNull(result, "Required attribute '" + name + "' is missing.");
return result;
}
/**
* Return the session attribute value, or a default, fallback value.
* @param name the attribute name
* @param defaultValue a default value to return instead
* @param <T> the attribute type
* @return the attribute value
*/
@SuppressWarnings("unchecked")
default <T> T getAttributeOrDefault(String name, T defaultValue) {
T result = getAttribute(name);
return result == null ? defaultValue : result;
}
/**
* Gets the attribute names that have a value associated with it. Each value can be
* passed into {@link org.springframework.session.Session#getAttribute(String)} to

View File

@@ -40,6 +40,47 @@ public class MapSessionTests {
new MapSession((Session) null);
}
@Test
public void getAttributeWhenNullThenNull() {
String result = this.session.getAttribute("attrName");
assertThat(result).isNull();
}
@Test
public void getAttributeOrDefaultWhenNullThenDefaultValue() {
String defaultValue = "default";
String result = this.session.getAttributeOrDefault("attrName", defaultValue);
assertThat(result).isEqualTo(defaultValue);
}
@Test
public void getAttributeOrDefaultWhenNotNullThenDefaultValue() {
String defaultValue = "default";
String attrValue = "value";
String attrName = "attrName";
this.session.setAttribute(attrName, attrValue);
String result = this.session.getAttributeOrDefault(attrName, defaultValue);
assertThat(result).isEqualTo(attrValue);
}
@Test(expected = IllegalArgumentException.class)
public void getRequiredAttributeWhenNullThenException() {
this.session.getRequiredAttribute("attrName");
}
@Test
public void getRequiredAttributeWhenNotNullThenReturns() {
String attrValue = "value";
String attrName = "attrName";
this.session.setAttribute(attrName, attrValue);
String result = this.session.getRequiredAttribute("attrName");
assertThat(result).isEqualTo(attrValue);
}
/**
* Ensure conforms to the javadoc of {@link Session}
*/