org.springframework.web.reactive.HandlerResult Java Examples

The following examples show how to use org.springframework.web.reactive.HandlerResult. 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: ResponseEntityResultHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleReturnValueETagAndLastModified() throws Exception {
	String eTag = "\"deadb33f8badf00d\"";

	Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
	Instant oneMinAgo = currentTime.minusSeconds(60);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")
			.ifNoneMatch(eTag)
			.ifModifiedSince(currentTime.toEpochMilli())
			);

	ResponseEntity<String> entity = ok().eTag(eTag).lastModified(oneMinAgo.toEpochMilli()).body("body");
	MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
	HandlerResult result = handlerResult(entity, returnType);
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, eTag, oneMinAgo);
}
 
Example #2
Source File: ViewResolutionResultHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void testDefaultViewName(Object returnValue, MethodParameter returnType) {
	this.bindingContext.getModel().addAttribute("id", "123");
	HandlerResult result = new HandlerResult(new Object(), returnValue, returnType, this.bindingContext);
	ViewResolutionResultHandler handler = resultHandler(new TestViewResolver("account"));

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/account"));
	handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
	assertResponseBody(exchange, "account: {id=123}");

	exchange = MockServerWebExchange.from(get("/account/"));
	handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
	assertResponseBody(exchange, "account: {id=123}");

	exchange = MockServerWebExchange.from(get("/account.123"));
	handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
	assertResponseBody(exchange, "account: {id=123}");
}
 
Example #3
Source File: SyncInvocableHandlerMethod.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Invoke the method for the given exchange.
 * @param exchange the current exchange
 * @param bindingContext the binding context to use
 * @param providedArgs optional list of argument values to match by type
 * @return a Mono with a {@link HandlerResult}.
 * @throws ServerErrorException if method argument resolution or method invocation fails
 */
@Nullable
public HandlerResult invokeForHandlerResult(ServerWebExchange exchange,
		BindingContext bindingContext, Object... providedArgs) {

	MonoProcessor<HandlerResult> processor = MonoProcessor.create();
	this.delegate.invoke(exchange, bindingContext, providedArgs).subscribeWith(processor);

	if (processor.isTerminated()) {
		Throwable ex = processor.getError();
		if (ex != null) {
			throw (ex instanceof ServerErrorException ? (ServerErrorException) ex :
					new ServerErrorException("Failed to invoke: " + getShortLogMessage(), getMethod(), ex));
		}
		return processor.peek();
	}
	else {
		// Should never happen...
		throw new IllegalStateException(
				"SyncInvocableHandlerMethod should have completed synchronously.");
	}
}
 
Example #4
Source File: ResponseEntityResultHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void handleReturnValueChangedETagAndLastModified() throws Exception {
	String etag = "\"deadb33f8badf00d\"";
	String newEtag = "\"changed-etag-value\"";

	Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
	Instant oneMinAgo = currentTime.minusSeconds(60);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")
			.ifNoneMatch(etag)
			.ifModifiedSince(currentTime.toEpochMilli())
			);

	ResponseEntity<String> entity = ok().eTag(newEtag).lastModified(oneMinAgo.toEpochMilli()).body("body");
	MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
	HandlerResult result = handlerResult(entity, returnType);
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertConditionalResponse(exchange, HttpStatus.OK, "body", newEtag, oneMinAgo);
}
 
Example #5
Source File: InvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void illegalArgumentException() {
	this.resolvers.add(stubResolver(1));
	Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	try {
		mono.block();
		fail("Expected IllegalStateException");
	}
	catch (IllegalStateException ex) {
		assertNotNull("Exception not wrapped", ex.getCause());
		assertTrue(ex.getCause() instanceof IllegalArgumentException);
		assertTrue(ex.getMessage().contains("Controller ["));
		assertTrue(ex.getMessage().contains("Method ["));
		assertTrue(ex.getMessage().contains("with argument values:"));
		assertTrue(ex.getMessage().contains("[0] [type=java.lang.Integer] [value=1]"));
	}
}
 
Example #6
Source File: ViewResolutionResultHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void contentNegotiation() {
	TestBean value = new TestBean("Joe");
	MethodParameter returnType = on(Handler.class).resolveReturnType(TestBean.class);
	HandlerResult handlerResult = new HandlerResult(new Object(), value, returnType, this.bindingContext);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/account").accept(APPLICATION_JSON));

	TestView defaultView = new TestView("jsonView", APPLICATION_JSON);

	resultHandler(Collections.singletonList(defaultView), new TestViewResolver("account"))
			.handleResult(exchange, handlerResult)
			.block(Duration.ofSeconds(5));

	assertEquals(APPLICATION_JSON, exchange.getResponse().getHeaders().getContentType());
	assertResponseBody(exchange, "jsonView: {" +
			"org.springframework.validation.BindingResult.testBean=" +
			"org.springframework.validation.BeanPropertyBindingResult: 0 errors, " +
			"testBean=TestBean[name=Joe]" +
			"}");
}
 
Example #7
Source File: ViewResolutionResultHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-15291
public void contentNegotiationWithRedirect() {
	HandlerResult handlerResult = new HandlerResult(new Object(), "redirect:/",
			on(Handler.class).annotNotPresent(ModelAttribute.class).resolveReturnType(String.class),
			this.bindingContext);

	UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
	viewResolver.setApplicationContext(new StaticApplicationContext());
	ViewResolutionResultHandler resultHandler = resultHandler(viewResolver);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/account").accept(APPLICATION_JSON));
	resultHandler.handleResult(exchange, handlerResult).block(Duration.ZERO);

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(303, response.getStatusCode().value());
	assertEquals("/", response.getHeaders().getLocation().toString());
}
 
Example #8
Source File: ResponseEntityResultHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void handleReturnValueETagAndLastModified() throws Exception {
	String eTag = "\"deadb33f8badf00d\"";

	Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
	Instant oneMinAgo = currentTime.minusSeconds(60);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")
			.ifNoneMatch(eTag)
			.ifModifiedSince(currentTime.toEpochMilli())
			);

	ResponseEntity<String> entity = ok().eTag(eTag).lastModified(oneMinAgo.toEpochMilli()).body("body");
	MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
	HandlerResult result = handlerResult(entity, returnType);
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, eTag, oneMinAgo);
}
 
Example #9
Source File: ResponseEntityResultHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleReturnValueChangedETagAndLastModified() throws Exception {
	String etag = "\"deadb33f8badf00d\"";
	String newEtag = "\"changed-etag-value\"";

	Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
	Instant oneMinAgo = currentTime.minusSeconds(60);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")
			.ifNoneMatch(etag)
			.ifModifiedSince(currentTime.toEpochMilli())
			);

	ResponseEntity<String> entity = ok().eTag(newEtag).lastModified(oneMinAgo.toEpochMilli()).body("body");
	MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
	HandlerResult result = handlerResult(entity, returnType);
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertConditionalResponse(exchange, HttpStatus.OK, "body", newEtag, oneMinAgo);
}
 
Example #10
Source File: ViewResolutionResultHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-15291
public void contentNegotiationWithRedirect() {
	HandlerResult handlerResult = new HandlerResult(new Object(), "redirect:/",
			on(Handler.class).annotNotPresent(ModelAttribute.class).resolveReturnType(String.class),
			this.bindingContext);

	UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
	viewResolver.setApplicationContext(new StaticApplicationContext());
	ViewResolutionResultHandler resultHandler = resultHandler(viewResolver);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/account").accept(APPLICATION_JSON));
	resultHandler.handleResult(exchange, handlerResult).block(Duration.ZERO);

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(303, response.getStatusCode().value());
	assertEquals("/", response.getHeaders().getLocation().toString());
}
 
Example #11
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void testHttpOptions(String requestURI, Set<HttpMethod> allowedMethods) {
	ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options(requestURI));
	HandlerMethod handlerMethod = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();

	BindingContext bindingContext = new BindingContext();
	InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod);
	Mono<HandlerResult> mono = invocable.invoke(exchange, bindingContext);

	HandlerResult result = mono.block();
	assertNotNull(result);

	Object value = result.getReturnValue();
	assertNotNull(value);
	assertEquals(HttpHeaders.class, value.getClass());
	assertEquals(allowedMethods, ((HttpHeaders) value).getAllow());
}
 
Example #12
Source File: ViewResolutionResultHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public boolean supports(HandlerResult result) {
	if (hasModelAnnotation(result.getReturnTypeSource())) {
		return true;
	}

	Class<?> type = result.getReturnType().toClass();
	ReactiveAdapter adapter = getAdapter(result);
	if (adapter != null) {
		if (adapter.isNoValue()) {
			return true;
		}
		type = result.getReturnType().getGeneric().toClass();
	}

	return (CharSequence.class.isAssignableFrom(type) || Rendering.class.isAssignableFrom(type) ||
			Model.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type) ||
			void.class.equals(type) || View.class.isAssignableFrom(type) ||
			!BeanUtils.isSimpleProperty(type));
}
 
Example #13
Source File: ViewResolutionResultHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void testDefaultViewName(Object returnValue, MethodParameter returnType) {
	this.bindingContext.getModel().addAttribute("id", "123");
	HandlerResult result = new HandlerResult(new Object(), returnValue, returnType, this.bindingContext);
	ViewResolutionResultHandler handler = resultHandler(new TestViewResolver("account"));

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/account"));
	handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
	assertResponseBody(exchange, "account: {id=123}");

	exchange = MockServerWebExchange.from(get("/account/"));
	handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
	assertResponseBody(exchange, "account: {id=123}");

	exchange = MockServerWebExchange.from(get("/account.123"));
	handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
	assertResponseBody(exchange, "account: {id=123}");
}
 
Example #14
Source File: InitBinderBindingContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void invokeBinderMethod(
		WebExchangeDataBinder dataBinder, ServerWebExchange exchange, SyncInvocableHandlerMethod binderMethod) {

	HandlerResult result = binderMethod.invokeForHandlerResult(exchange, this.binderMethodContext, dataBinder);
	if (result != null && result.getReturnValue() != null) {
		throw new IllegalStateException(
				"@InitBinder methods must not return a value (should be void): " + binderMethod);
	}
	// Should not happen (no Model argument resolution) ...
	if (!this.binderMethodContext.getModel().asMap().isEmpty()) {
		throw new IllegalStateException(
				"@InitBinder methods are not allowed to add model attributes: " + binderMethod);
	}
}
 
Example #15
Source File: ResponseEntityResultHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-14559
public void handleReturnValueEtagInvalidIfNoneMatch() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path").ifNoneMatch("unquoted"));

	ResponseEntity<String> entity = ok().eTag("\"deadb33f8badf00d\"").body("body");
	MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
	HandlerResult result = handlerResult(entity, returnType);
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode());
	assertResponseBody(exchange, "body");
}
 
Example #16
Source File: ModelInitializer.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Mono<Void> invokeModelAttributeMethods(BindingContext bindingContext,
		List<InvocableHandlerMethod> modelMethods, ServerWebExchange exchange) {

	List<Mono<HandlerResult>> resultList = new ArrayList<>();
	modelMethods.forEach(invocable -> resultList.add(invocable.invoke(exchange, bindingContext)));

	return Mono
			.zip(resultList, objectArray ->
					Arrays.stream(objectArray)
							.map(object -> handleResult(((HandlerResult) object), bindingContext))
							.collect(Collectors.toList()))
			.flatMap(Mono::when);
}
 
Example #17
Source File: InvocableHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void responseStatusAnnotation() {
	Method method = ResolvableMethod.on(TestController.class).mockCall(TestController::created).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	assertHandlerResultValue(mono, "created");
	assertThat(this.exchange.getResponse().getStatusCode(), is(HttpStatus.CREATED));
}
 
Example #18
Source File: ResponseEntityResultHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleReturnValueLastModified() throws Exception {
	Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
	Instant oneMinAgo = currentTime.minusSeconds(60);
	long timestamp = currentTime.toEpochMilli();
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path").ifModifiedSince(timestamp));

	ResponseEntity<String> entity = ok().lastModified(oneMinAgo.toEpochMilli()).body("body");
	MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
	HandlerResult result = handlerResult(entity, returnType);
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, null, oneMinAgo);
}
 
Example #19
Source File: ResponseEntityResultHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleReturnValueEtag() throws Exception {
	String etagValue = "\"deadb33f8badf00d\"";
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path").ifNoneMatch(etagValue));

	ResponseEntity<String> entity = ok().eTag(etagValue).body("body");
	MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
	HandlerResult result = handlerResult(entity, returnType);
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, etagValue, Instant.MIN);
}
 
Example #20
Source File: InvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void responseStatusAnnotation() {
	Method method = ResolvableMethod.on(TestController.class).mockCall(TestController::created).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	assertHandlerResultValue(mono, "created");
	assertThat(this.exchange.getResponse().getStatusCode(), is(HttpStatus.CREATED));
}
 
Example #21
Source File: WebTestClientInitializerTest.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
/**
 * Test for method
 * {@link WebTestClientInitializer#handle(ServerWebExchange, Object)}.
 */
@Test
public void handleResult_doNothing() {

    // prepare:
    WebTestClientInitializer testInstance = new WebTestClientInitializer();
    ServerWebExchange exchange = mock(ServerWebExchange.class);
    HandlerResult handlerResult = mock(HandlerResult.class);

    // perform:
    Mono<HandlerResult> result = testInstance.handle(exchange, handlerResult);

    // verify:
    assertNull(result.block(Duration.ZERO));
}
 
Example #22
Source File: InvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void invocationTargetException() {
	Method method = ResolvableMethod.on(TestController.class).mockCall(TestController::exceptionMethod).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	try {
		mono.block();
		fail("Expected IllegalStateException");
	}
	catch (IllegalStateException ex) {
		assertThat(ex.getMessage(), is("boo"));
	}
}
 
Example #23
Source File: ResponseBodyResultHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void supports() {
	Object controller = new TestController();
	Method method;

	method = on(TestController.class).annotPresent(ResponseBody.class).resolveMethod();
	testSupports(controller, method);

	method = on(TestController.class).annotNotPresent(ResponseBody.class).resolveMethod("doWork");
	HandlerResult handlerResult = getHandlerResult(controller, method);
	assertFalse(this.resultHandler.supports(handlerResult));
}
 
Example #24
Source File: InvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveProvidedArgFirst() {
	this.resolvers.add(stubResolver("value1"));
	Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method, "value2");

	assertHandlerResultValue(mono, "success:value2");
}
 
Example #25
Source File: ResponseEntityResultHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-14877
public void handleMonoWithWildcardBodyTypeAndNullBody() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path"));
	exchange.getAttributes().put(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(APPLICATION_JSON));

	MethodParameter returnType = on(TestController.class).resolveReturnType(Mono.class, ResponseEntity.class);
	HandlerResult result = new HandlerResult(new TestController(), Mono.just(notFound().build()), returnType);

	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
	assertResponseBodyIsEmpty(exchange);
}
 
Example #26
Source File: InvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void cannotResolveArg() {
	Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	try {
		mono.block();
		fail("Expected IllegalStateException");
	}
	catch (IllegalStateException ex) {
		assertThat(ex.getMessage(), is("Could not resolve parameter [0] in " +
				method.toGenericString() + ": No suitable resolver"));
	}
}
 
Example #27
Source File: InvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveNoArgValue() {
	this.resolvers.add(stubResolver(Mono.empty()));
	Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	assertHandlerResultValue(mono, "success:null");
}
 
Example #28
Source File: InvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveArg() {
	this.resolvers.add(stubResolver("value1"));
	Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	assertHandlerResultValue(mono, "success:value1");
}
 
Example #29
Source File: InvocableHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void voidMethodWithExchangeArg() {
	this.resolvers.add(stubResolver(this.exchange));
	Method method = ResolvableMethod.on(TestController.class).mockCall(c -> c.exchange(exchange)).method();
	HandlerResult result = invokeForResult(new TestController(), method);

	assertNull("Expected no result (i.e. fully handled)", result);
	assertEquals("bar", this.exchange.getResponse().getHeaders().getFirst("foo"));
}
 
Example #30
Source File: ControllerAdviceTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private HandlerResult handle(RequestMappingHandlerAdapter adapter,
		Object controller, String methodName) throws Exception {

	Method method = controller.getClass().getMethod(methodName);
	HandlerMethod handlerMethod = new HandlerMethod(controller, method);
	return adapter.handle(this.exchange, handlerMethod).block(Duration.ZERO);
}