org.springframework.web.server.WebSession Java Examples

The following examples show how to use org.springframework.web.server.WebSession. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSessionIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange) {
	if (exchange.getRequest().getQueryParams().containsKey("expire")) {
		return exchange.getSession().doOnNext(session -> {
			// Don't do anything, leave it expired...
		}).then();
	}
	else if (exchange.getRequest().getQueryParams().containsKey("changeId")) {
		return exchange.getSession().flatMap(session ->
				session.changeSessionId().doOnSuccess(aVoid -> updateSessionAttribute(session)));
	}
	else if (exchange.getRequest().getQueryParams().containsKey("invalidate")) {
		return exchange.getSession().doOnNext(WebSession::invalidate).then();
	}
	else {
		return exchange.getSession().doOnSuccess(this::updateSessionAttribute).then();
	}
}
 
Example #2
Source File: WebSessionMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resolverArgument() {

	BindingContext context = new BindingContext();
	WebSession session = mock(WebSession.class);
	MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
	ServerWebExchange exchange = MockServerWebExchange.builder(request).session(session).build();

	MethodParameter param = this.testMethod.arg(WebSession.class);
	Object actual = this.resolver.resolveArgument(param, context, exchange).block();
	assertSame(session, actual);

	param = this.testMethod.arg(Mono.class, WebSession.class);
	actual = this.resolver.resolveArgument(param, context, exchange).block();
	assertNotNull(actual);
	assertTrue(Mono.class.isAssignableFrom(actual.getClass()));
	assertSame(session, ((Mono<?>) actual).block());

	param = this.testMethod.arg(Single.class, WebSession.class);
	actual = this.resolver.resolveArgument(param, context, exchange).block();
	assertNotNull(actual);
	assertTrue(Single.class.isAssignableFrom(actual.getClass()));
	assertSame(session, ((Single<?>) actual).blockingGet());
}
 
Example #3
Source File: SessionAttributesHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void cleanupAttributes() {
	WebSession session = new MockWebSession();
	session.getAttributes().put("attr1", "value1");
	session.getAttributes().put("attr2", "value2");
	session.getAttributes().put("attr3", new TestBean());

	this.sessionAttributesHandler.cleanupAttributes(session);

	assertNull(session.getAttributes().get("attr1"));
	assertNull(session.getAttributes().get("attr2"));
	assertNotNull(session.getAttributes().get("attr3"));

	// Resolve 'attr3' by type
	this.sessionAttributesHandler.isHandlerSessionAttribute("attr3", TestBean.class);
	this.sessionAttributesHandler.cleanupAttributes(session);

	assertNull(session.getAttributes().get("attr3"));
}
 
Example #4
Source File: ServerWebExchangeMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void supportsParameter() {
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerWebExchange.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpRequest.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpResponse.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(HttpMethod.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Locale.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(TimeZone.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ZoneId.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(UriComponentsBuilder.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(UriBuilder.class)));

	assertFalse(this.resolver.supportsParameter(this.testMethod.arg(WebSession.class)));
	assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class)));
	try {
		this.resolver.supportsParameter(this.testMethod.arg(Mono.class, ServerWebExchange.class));
		fail();
	}
	catch (IllegalStateException ex) {
		assertTrue("Unexpected error message:\n" + ex.getMessage(),
				ex.getMessage().startsWith(
						"ServerWebExchangeMethodArgumentResolver does not support reactive type wrapper"));
	}
}
 
Example #5
Source File: InMemoryWebSessionStore.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Mono<WebSession> retrieveSession(String id) {
	Instant now = this.clock.instant();
	this.expiredSessionChecker.checkIfNecessary(now);
	InMemoryWebSession session = this.sessions.get(id);
	if (session == null) {
		return Mono.empty();
	}
	else if (session.isExpired(now)) {
		this.sessions.remove(id);
		return Mono.empty();
	}
	else {
		session.updateLastAccessTime(now);
		return Mono.just(session);
	}
}
 
Example #6
Source File: SessionAttributesHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void retrieveAttributes() {
	WebSession session = new MockWebSession();
	session.getAttributes().put("attr1", "value1");
	session.getAttributes().put("attr2", "value2");
	session.getAttributes().put("attr3", new TestBean());
	session.getAttributes().put("attr4", new TestBean());

	assertEquals("Named attributes (attr1, attr2) should be 'known' right away",
			new HashSet<>(asList("attr1", "attr2")),
			sessionAttributesHandler.retrieveAttributes(session).keySet());

	// Resolve 'attr3' by type
	sessionAttributesHandler.isHandlerSessionAttribute("attr3", TestBean.class);

	assertEquals("Named attributes (attr1, attr2) and resolved attribute (att3) should be 'known'",
			new HashSet<>(asList("attr1", "attr2", "attr3")),
			sessionAttributesHandler.retrieveAttributes(session).keySet());
}
 
Example #7
Source File: MockServerRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
		MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
		Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
		Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal,
		@Nullable InetSocketAddress remoteAddress, List<HttpMessageReader<?>> messageReaders,
		@Nullable ServerWebExchange exchange) {

	this.method = method;
	this.uri = uri;
	this.pathContainer = RequestPath.parse(uri, contextPath);
	this.headers = headers;
	this.cookies = cookies;
	this.body = body;
	this.attributes = attributes;
	this.queryParams = queryParams;
	this.pathVariables = pathVariables;
	this.session = session;
	this.principal = principal;
	this.remoteAddress = remoteAddress;
	this.messageReaders = messageReaders;
	this.exchange = exchange;
}
 
Example #8
Source File: ModelInitializerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void retrieveModelAttributeFromSession() throws Exception {
	WebSession session = this.exchange.getSession().block(Duration.ZERO);
	assertNotNull(session);

	TestBean testBean = new TestBean("Session Bean");
	session.getAttributes().put("bean", testBean);

	TestController controller = new TestController();
	InitBinderBindingContext context = getBindingContext(controller);

	Method method = ResolvableMethod.on(TestController.class).annotPresent(GetMapping.class).resolveMethod();
	HandlerMethod handlerMethod = new HandlerMethod(controller, method);
	this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));

	context.saveModel();
	assertEquals(1, session.getAttributes().size());
	assertEquals("Session Bean", ((TestBean) session.getRequiredAttribute("bean")).getName());
}
 
Example #9
Source File: SessionAttributesHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void retrieveAttributes() {
	WebSession session = new MockWebSession();
	session.getAttributes().put("attr1", "value1");
	session.getAttributes().put("attr2", "value2");
	session.getAttributes().put("attr3", new TestBean());
	session.getAttributes().put("attr4", new TestBean());

	assertEquals("Named attributes (attr1, attr2) should be 'known' right away",
			new HashSet<>(asList("attr1", "attr2")),
			sessionAttributesHandler.retrieveAttributes(session).keySet());

	// Resolve 'attr3' by type
	sessionAttributesHandler.isHandlerSessionAttribute("attr3", TestBean.class);

	assertEquals("Named attributes (attr1, attr2) and resolved attribute (att3) should be 'known'",
			new HashSet<>(asList("attr1", "attr2", "attr3")),
			sessionAttributesHandler.retrieveAttributes(session).keySet());
}
 
Example #10
Source File: SessionAttributesHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void cleanupAttributes() {
	WebSession session = new MockWebSession();
	session.getAttributes().put("attr1", "value1");
	session.getAttributes().put("attr2", "value2");
	session.getAttributes().put("attr3", new TestBean());

	this.sessionAttributesHandler.cleanupAttributes(session);

	assertNull(session.getAttributes().get("attr1"));
	assertNull(session.getAttributes().get("attr2"));
	assertNotNull(session.getAttributes().get("attr3"));

	// Resolve 'attr3' by type
	this.sessionAttributesHandler.isHandlerSessionAttribute("attr3", TestBean.class);
	this.sessionAttributesHandler.cleanupAttributes(session);

	assertNull(session.getAttributes().get("attr3"));
}
 
Example #11
Source File: InMemoryWebSessionStoreTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void lastAccessTimeIsUpdatedOnRetrieve() {
	WebSession session1 = this.store.createWebSession().block();
	assertNotNull(session1);
	String id = session1.getId();
	Instant time1 = session1.getLastAccessTime();
	session1.start();
	session1.save().block();

	// Fast-forward a few seconds
	this.store.setClock(Clock.offset(this.store.getClock(), Duration.ofSeconds(5)));

	WebSession session2 = this.store.retrieveSession(id).block();
	assertNotNull(session2);
	assertSame(session1, session2);
	Instant time2 = session2.getLastAccessTime();
	assertTrue(time1.isBefore(time2));
}
 
Example #12
Source File: InMemoryWebSessionStoreTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void retrieveExpiredSession() {
	WebSession session = this.store.createWebSession().block();
	assertNotNull(session);
	session.getAttributes().put("foo", "bar");
	session.save().block();

	String id = session.getId();
	WebSession retrieved = this.store.retrieveSession(id).block();
	assertNotNull(retrieved);
	assertSame(session, retrieved);

	// Fast-forward 31 minutes
	this.store.setClock(Clock.offset(this.store.getClock(), Duration.ofMinutes(31)));
	WebSession retrievedAgain = this.store.retrieveSession(id).block();
	assertNull(retrievedAgain);
}
 
Example #13
Source File: SpringSessionWebSessionStoreTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void retrieveSessionThenStarted() {
	String id = "id";
	WebSession retrievedWebSession = this.webSessionStore.retrieveSession(id).block();

	assertThat(retrievedWebSession.isStarted()).isTrue();
	verify(this.findByIdSession).setLastAccessedTime(any());
}
 
Example #14
Source File: SpringSessionWebSessionStoreTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void createSessionWhenGetAttributesAndValuesThenDelegatesToCreateSession() {
	given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a"));
	given(this.createSession.getAttribute("a")).willReturn("b");
	WebSession createdWebSession = this.webSessionStore.createWebSession().block();

	Map<String, Object> attributes = createdWebSession.getAttributes();

	assertThat(attributes.values()).containsExactly("b");
}
 
Example #15
Source File: SpringSessionWebSessionStoreTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void createSessionWhenGetAttributesAndPutNullThenDelegatesToCreateSession() {
	WebSession createdWebSession = this.webSessionStore.createWebSession().block();

	Map<String, Object> attributes = createdWebSession.getAttributes();
	attributes.put("a", null);

	verify(this.createSession).setAttribute("a", null);
}
 
Example #16
Source File: DefaultWebSessionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getSessionSaveWhenCreatedAndNotStartedThenNotSaved() {

	when(this.sessionIdResolver.resolveSessionIds(this.exchange)).thenReturn(Collections.emptyList());
	WebSession session = this.sessionManager.getSession(this.exchange).block();
	this.exchange.getResponse().setComplete().block();

	assertSame(this.createSession, session);
	assertFalse(session.isStarted());
	assertFalse(session.isExpired());
	verify(this.createSession, never()).save();
	verify(this.sessionIdResolver, never()).setSessionId(any(), any());
}
 
Example #17
Source File: WebSessionIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void expiredSessionIsRecreated() throws Exception {

	// First request: no session yet, new session created
	RequestEntity<Void> request = RequestEntity.get(createUri()).build();
	ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	String id = extractSessionId(response.getHeaders());
	assertNotNull(id);
	assertEquals(1, this.handler.getSessionRequestCount());

	// Second request: same session
	request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build();
	response = this.restTemplate.exchange(request, Void.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	assertNull(response.getHeaders().get("Set-Cookie"));
	assertEquals(2, this.handler.getSessionRequestCount());

	// Now fast-forward by 31 minutes
	InMemoryWebSessionStore store = (InMemoryWebSessionStore) this.sessionManager.getSessionStore();
	WebSession session = store.retrieveSession(id).block();
	assertNotNull(session);
	store.setClock(Clock.offset(store.getClock(), Duration.ofMinutes(31)));

	// Third request: expired session, new session created
	request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build();
	response = this.restTemplate.exchange(request, Void.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	id = extractSessionId(response.getHeaders());
	assertNotNull("Expected new session id", id);
	assertEquals(1, this.handler.getSessionRequestCount());
}
 
Example #18
Source File: MockWebSession.java    From java-technology-stack with MIT License 5 votes vote down vote up
public MockWebSession(@Nullable Clock clock) {
	InMemoryWebSessionStore sessionStore = new InMemoryWebSessionStore();
	if (clock != null) {
		sessionStore.setClock(clock);
	}
	WebSession session = sessionStore.createWebSession().block();
	Assert.state(session != null, "WebSession must not be null");
	this.delegate = session;
}
 
Example #19
Source File: SessionAttributesHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void storeAttributes() {

	ModelMap model = new ModelMap();
	model.put("attr1", "value1");
	model.put("attr2", "value2");
	model.put("attr3", new TestBean());

	WebSession session = new MockWebSession();
	sessionAttributesHandler.storeAttributes(session, model);

	assertEquals("value1", session.getAttributes().get("attr1"));
	assertEquals("value2", session.getAttributes().get("attr2"));
	assertTrue(session.getAttributes().get("attr3") instanceof TestBean);
}
 
Example #20
Source File: ServerWebExchangeArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public void handle(
		ServerWebExchange exchange,
		ServerHttpRequest request,
		ServerHttpResponse response,
		WebSession session,
		HttpMethod httpMethod,
		Locale locale,
		TimeZone timeZone,
		ZoneId zoneId,
		UriComponentsBuilder uriComponentsBuilder,
		UriBuilder uriBuilder,
		String s,
		Mono<ServerWebExchange> monoExchange) {
}
 
Example #21
Source File: MockWebSession.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public MockWebSession(@Nullable Clock clock) {
	InMemoryWebSessionStore sessionStore = new InMemoryWebSessionStore();
	if (clock != null) {
		sessionStore.setClock(clock);
	}
	WebSession session = sessionStore.createWebSession().block();
	Assert.state(session != null, "WebSession must not be null");
	this.delegate = session;
}
 
Example #22
Source File: SpringSessionWebSessionStoreTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void createSessionWhenAddAttributeThenStarted() {
	given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a"));
	WebSession createdWebSession = this.webSessionStore.createWebSession().block();

	assertThat(createdWebSession.isStarted()).isTrue();
}
 
Example #23
Source File: SpringSessionWebSessionStoreTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void createSessionWhenGetAttributesAndContainsKeyAndFoundThenTrue() {
	given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a"));
	WebSession createdWebSession = this.webSessionStore.createWebSession().block();

	Map<String, Object> attributes = createdWebSession.getAttributes();

	assertThat(attributes.containsKey("a")).isTrue();
}
 
Example #24
Source File: DefaultWebSessionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getSessionSaveWhenCreatedAndStartedThenSavesAndSetsId() {

	given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(Collections.emptyList());
	WebSession session = this.sessionManager.getSession(this.exchange).block();
	assertSame(this.createSession, session);
	String sessionId = this.createSession.getId();

	given(this.createSession.isStarted()).willReturn(true);
	this.exchange.getResponse().setComplete().block();

	verify(this.sessionStore).createWebSession();
	verify(this.sessionIdResolver).setSessionId(any(), eq(sessionId));
	verify(this.createSession).save();
}
 
Example #25
Source File: DefaultWebSessionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getSessionSaveWhenCreatedAndNotStartedThenNotSaved() {

	given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(Collections.emptyList());
	WebSession session = this.sessionManager.getSession(this.exchange).block();
	this.exchange.getResponse().setComplete().block();

	assertSame(this.createSession, session);
	assertFalse(session.isStarted());
	assertFalse(session.isExpired());
	verify(this.createSession, never()).save();
	verify(this.sessionIdResolver, never()).setSessionId(any(), any());
}
 
Example #26
Source File: InMemoryWebSessionStoreTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void startsSessionImplicitly() {
	WebSession session = this.store.createWebSession().block();
	assertNotNull(session);
	session.start();
	session.getAttributes().put("foo", "bar");
	assertTrue(session.isStarted());
}
 
Example #27
Source File: WebSessionIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void expiredSessionIsRecreated() throws Exception {

	// First request: no session yet, new session created
	RequestEntity<Void> request = RequestEntity.get(createUri()).build();
	ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	String id = extractSessionId(response.getHeaders());
	assertNotNull(id);
	assertEquals(1, this.handler.getSessionRequestCount());

	// Second request: same session
	request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build();
	response = this.restTemplate.exchange(request, Void.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	assertNull(response.getHeaders().get("Set-Cookie"));
	assertEquals(2, this.handler.getSessionRequestCount());

	// Now fast-forward by 31 minutes
	InMemoryWebSessionStore store = (InMemoryWebSessionStore) this.sessionManager.getSessionStore();
	WebSession session = store.retrieveSession(id).block();
	assertNotNull(session);
	store.setClock(Clock.offset(store.getClock(), Duration.ofMinutes(31)));

	// Third request: expired session, new session created
	request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build();
	response = this.restTemplate.exchange(request, Void.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	id = extractSessionId(response.getHeaders());
	assertNotNull("Expected new session id", id);
	assertEquals(1, this.handler.getSessionRequestCount());
}
 
Example #28
Source File: InMemoryWebSessionStoreTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private WebSession insertSession() {
	WebSession session = this.store.createWebSession().block();
	assertNotNull(session);
	session.start();
	session.save().block();
	return session;
}
 
Example #29
Source File: InMemoryWebSessionStoreTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-17051
public void sessionInvalidatedBeforeSave() {
	// Request 1 creates session
	WebSession session1 = this.store.createWebSession().block();
	assertNotNull(session1);
	String id = session1.getId();
	session1.start();
	session1.save().block();

	// Request 2 retrieves session
	WebSession session2 = this.store.retrieveSession(id).block();
	assertNotNull(session2);
	assertSame(session1, session2);

	// Request 3 retrieves and invalidates
	WebSession session3 = this.store.retrieveSession(id).block();
	assertNotNull(session3);
	assertSame(session1, session3);
	session3.invalidate().block();

	// Request 2 saves session after invalidated
	session2.save().block();

	// Session should not be present
	WebSession session4 = this.store.retrieveSession(id).block();
	assertNull(session4);
}
 
Example #30
Source File: InMemoryWebSessionStoreTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void startsSessionImplicitly() {
	WebSession session = this.store.createWebSession().block();
	assertNotNull(session);
	session.start();
	session.getAttributes().put("foo", "bar");
	assertTrue(session.isStarted());
}