Reactive support for @ModelAttribute methods
Issue: SPR-14542
This commit is contained in:
@@ -108,28 +108,13 @@ public class DispatcherHandlerErrorTests {
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unknownMethodArgumentType() throws Exception {
|
||||
this.request.setUri("/unknown-argument-type");
|
||||
Mono<Void> publisher = this.dispatcherHandler.handle(this.exchange);
|
||||
|
||||
StepVerifier.create(publisher)
|
||||
.consumeErrorWith(error -> {
|
||||
assertThat(error, instanceOf(IllegalStateException.class));
|
||||
assertThat(error.getMessage(), startsWith("No resolver for argument [0]"));
|
||||
})
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void controllerReturnsMonoError() throws Exception {
|
||||
this.request.setUri("/error-signal");
|
||||
Mono<Void> publisher = this.dispatcherHandler.handle(this.exchange);
|
||||
|
||||
StepVerifier.create(publisher)
|
||||
.consumeErrorWith(error -> {
|
||||
assertSame(EXCEPTION, error);
|
||||
})
|
||||
.consumeErrorWith(error -> assertSame(EXCEPTION, error))
|
||||
.verify();
|
||||
}
|
||||
|
||||
@@ -138,10 +123,8 @@ public class DispatcherHandlerErrorTests {
|
||||
this.request.setUri("/raise-exception");
|
||||
Mono<Void> publisher = this.dispatcherHandler.handle(this.exchange);
|
||||
|
||||
StepVerifier.<Void>create(publisher)
|
||||
.consumeErrorWith(error -> {
|
||||
assertSame(EXCEPTION, error);
|
||||
})
|
||||
StepVerifier.create(publisher)
|
||||
.consumeErrorWith(error -> assertSame(EXCEPTION, error))
|
||||
.verify();
|
||||
}
|
||||
|
||||
@@ -164,9 +147,7 @@ public class DispatcherHandlerErrorTests {
|
||||
Mono<Void> publisher = this.dispatcherHandler.handle(this.exchange);
|
||||
|
||||
StepVerifier.create(publisher)
|
||||
.consumeErrorWith(error -> {
|
||||
assertThat(error, instanceOf(NotAcceptableStatusException.class));
|
||||
})
|
||||
.consumeErrorWith(error -> assertThat(error, instanceOf(NotAcceptableStatusException.class)))
|
||||
.verify();
|
||||
}
|
||||
|
||||
@@ -226,10 +207,6 @@ public class DispatcherHandlerErrorTests {
|
||||
@SuppressWarnings("unused")
|
||||
private static class TestController {
|
||||
|
||||
@RequestMapping("/unknown-argument-type")
|
||||
public void unknownArgumentType(Foo arg) {
|
||||
}
|
||||
|
||||
@RequestMapping("/error-signal")
|
||||
@ResponseBody
|
||||
public Publisher<String> errorSignal() {
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/*
|
||||
* Copyright 2002-2016 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.web.reactive.result.method.annotation;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import reactor.core.publisher.Mono;
|
||||
import rx.Single;
|
||||
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
|
||||
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.validation.Validator;
|
||||
import org.springframework.web.bind.WebDataBinder;
|
||||
import org.springframework.web.bind.WebExchangeDataBinder;
|
||||
import org.springframework.web.bind.annotation.InitBinder;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.reactive.config.WebReactiveConfigurationSupport;
|
||||
import org.springframework.web.reactive.result.ResolvableMethod;
|
||||
import org.springframework.web.reactive.result.method.BindingContext;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.adapter.DefaultServerWebExchange;
|
||||
import org.springframework.web.server.session.DefaultWebSessionManager;
|
||||
import org.springframework.web.server.session.WebSessionManager;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link BindingContextFactory}.
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class BindingContextFactoryTests {
|
||||
|
||||
private BindingContextFactory contextFactory;
|
||||
|
||||
private ServerWebExchange exchange;
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
WebReactiveConfigurationSupport configurationSupport = new WebReactiveConfigurationSupport();
|
||||
configurationSupport.setApplicationContext(new StaticApplicationContext());
|
||||
RequestMappingHandlerAdapter adapter = configurationSupport.requestMappingHandlerAdapter();
|
||||
adapter.afterPropertiesSet();
|
||||
this.contextFactory = new BindingContextFactory(adapter);
|
||||
|
||||
MockServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, "/path");
|
||||
MockServerHttpResponse response = new MockServerHttpResponse();
|
||||
WebSessionManager manager = new DefaultWebSessionManager();
|
||||
this.exchange = new DefaultServerWebExchange(request, response, manager);
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void basic() throws Exception {
|
||||
|
||||
Validator validator = mock(Validator.class);
|
||||
TestController controller = new TestController(validator);
|
||||
|
||||
HandlerMethod handlerMethod = ResolvableMethod.on(controller)
|
||||
.annotated(RequestMapping.class)
|
||||
.resolveHandlerMethod();
|
||||
|
||||
BindingContext bindingContext =
|
||||
this.contextFactory.createBindingContext(handlerMethod, this.exchange)
|
||||
.blockMillis(5000);
|
||||
|
||||
WebExchangeDataBinder binder = bindingContext.createDataBinder(this.exchange, "name");
|
||||
assertEquals(Collections.singletonList(validator), binder.getValidators());
|
||||
|
||||
Map<String, Object> model = bindingContext.getModel().asMap();
|
||||
assertEquals(5, model.size());
|
||||
|
||||
Object value = model.get("bean");
|
||||
assertEquals("Bean", ((TestBean) value).getName());
|
||||
|
||||
value = model.get("monoBean");
|
||||
assertEquals("Mono Bean", ((Mono<TestBean>) value).blockMillis(5000).getName());
|
||||
|
||||
value = model.get("singleBean");
|
||||
assertEquals("Single Bean", ((Single<TestBean>) value).toBlocking().value().getName());
|
||||
|
||||
value = model.get("voidMethodBean");
|
||||
assertEquals("Void Method Bean", ((TestBean) value).getName());
|
||||
|
||||
value = model.get("voidMonoMethodBean");
|
||||
assertEquals("Void Mono Method Bean", ((TestBean) value).getName());
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static class TestController {
|
||||
|
||||
private Validator[] validators;
|
||||
|
||||
|
||||
public TestController(Validator... validators) {
|
||||
this.validators = validators;
|
||||
}
|
||||
|
||||
|
||||
@InitBinder
|
||||
public void initDataBinder(WebDataBinder dataBinder) {
|
||||
if (!ObjectUtils.isEmpty(this.validators)) {
|
||||
dataBinder.addValidators(this.validators);
|
||||
}
|
||||
}
|
||||
|
||||
@ModelAttribute("bean")
|
||||
public TestBean returnValue() {
|
||||
return new TestBean("Bean");
|
||||
}
|
||||
|
||||
@ModelAttribute("monoBean")
|
||||
public Mono<TestBean> returnValueMono() {
|
||||
return Mono.just(new TestBean("Mono Bean"));
|
||||
}
|
||||
|
||||
@ModelAttribute("singleBean")
|
||||
public Single<TestBean> returnValueSingle() {
|
||||
return Single.just(new TestBean("Single Bean"));
|
||||
}
|
||||
|
||||
@ModelAttribute
|
||||
public void voidMethodBean(Model model) {
|
||||
model.addAttribute("voidMethodBean", new TestBean("Void Method Bean"));
|
||||
}
|
||||
|
||||
@ModelAttribute
|
||||
public Mono<Void> voidMonoMethodBean(Model model) {
|
||||
return Mono.just("Void Mono Method Bean")
|
||||
.doOnNext(name -> model.addAttribute("voidMonoMethodBean", new TestBean(name)))
|
||||
.then();
|
||||
}
|
||||
|
||||
@RequestMapping
|
||||
public void handle() {}
|
||||
}
|
||||
|
||||
private static class TestBean {
|
||||
|
||||
private final String name;
|
||||
|
||||
TestBean(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TestBean[name=" + this.name + "]";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -91,7 +91,7 @@ public class ModelAttributeMethodArgumentResolverTests {
|
||||
public void supports() throws Exception {
|
||||
|
||||
ModelAttributeMethodArgumentResolver resolver =
|
||||
new ModelAttributeMethodArgumentResolver(false, new ReactiveAdapterRegistry());
|
||||
new ModelAttributeMethodArgumentResolver(new ReactiveAdapterRegistry(), false);
|
||||
|
||||
ResolvableType type = forClass(Foo.class);
|
||||
assertTrue(resolver.supportsParameter(parameter(type)));
|
||||
@@ -110,7 +110,7 @@ public class ModelAttributeMethodArgumentResolverTests {
|
||||
public void supportsWithDefaultResolution() throws Exception {
|
||||
|
||||
ModelAttributeMethodArgumentResolver resolver =
|
||||
new ModelAttributeMethodArgumentResolver(true, new ReactiveAdapterRegistry());
|
||||
new ModelAttributeMethodArgumentResolver(new ReactiveAdapterRegistry(), true);
|
||||
|
||||
ResolvableType type = forClass(Foo.class);
|
||||
assertTrue(resolver.supportsParameter(parameterNotAnnotated(type)));
|
||||
@@ -282,7 +282,7 @@ public class ModelAttributeMethodArgumentResolverTests {
|
||||
|
||||
|
||||
private ModelAttributeMethodArgumentResolver createResolver() {
|
||||
return new ModelAttributeMethodArgumentResolver(false, new ReactiveAdapterRegistry());
|
||||
return new ModelAttributeMethodArgumentResolver(new ReactiveAdapterRegistry());
|
||||
}
|
||||
|
||||
private MethodParameter parameter(ResolvableType type) {
|
||||
|
||||
@@ -18,8 +18,10 @@ package org.springframework.web.reactive.result.method.annotation;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.beans.propertyeditors.CustomDateEditor;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
@@ -27,12 +29,17 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.web.bind.WebDataBinder;
|
||||
import org.springframework.web.bind.annotation.InitBinder;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.reactive.config.EnableWebReactive;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
@@ -62,6 +69,18 @@ public class RequestMappingDataBindingIntegrationTests extends AbstractRequestMa
|
||||
new HttpHeaders(), null, String.class).getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handleForm() throws Exception {
|
||||
|
||||
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
|
||||
formData.add("name", "George");
|
||||
formData.add("age", "5");
|
||||
|
||||
assertEquals("Processed form: Foo[id=1, name='George', age=5]",
|
||||
performPost("/foos/1", MediaType.APPLICATION_FORM_URLENCODED, formData,
|
||||
MediaType.TEXT_PLAIN, String.class).getBody());
|
||||
}
|
||||
|
||||
|
||||
@Configuration
|
||||
@EnableWebReactive
|
||||
@@ -70,21 +89,73 @@ public class RequestMappingDataBindingIntegrationTests extends AbstractRequestMa
|
||||
static class WebConfig {
|
||||
}
|
||||
|
||||
@Controller
|
||||
@SuppressWarnings("unused")
|
||||
@RestController
|
||||
@SuppressWarnings({"unused", "OptionalUsedAsFieldOrParameterType"})
|
||||
private static class TestController {
|
||||
|
||||
@InitBinder
|
||||
public void initBinder(WebDataBinder dataBinder, @RequestParam("date-pattern") String pattern) {
|
||||
CustomDateEditor dateEditor = new CustomDateEditor(new SimpleDateFormat(pattern), false);
|
||||
dataBinder.registerCustomEditor(Date.class, dateEditor);
|
||||
public void initBinder(WebDataBinder binder,
|
||||
@RequestParam("date-pattern") Optional<String> optionalPattern) {
|
||||
|
||||
optionalPattern.ifPresent(pattern -> {
|
||||
CustomDateEditor dateEditor = new CustomDateEditor(new SimpleDateFormat(pattern), false);
|
||||
binder.registerCustomEditor(Date.class, dateEditor);
|
||||
});
|
||||
}
|
||||
|
||||
@PostMapping("/date-param")
|
||||
@ResponseBody
|
||||
public String handleDateParam(@RequestParam Date date) {
|
||||
return "Processed date!";
|
||||
}
|
||||
|
||||
@ModelAttribute
|
||||
public Mono<Foo> addFooAttribute(@PathVariable("id") Optional<Long> optiponalId) {
|
||||
return optiponalId.map(id -> Mono.just(new Foo(id))).orElse(Mono.empty());
|
||||
}
|
||||
|
||||
@PostMapping("/foos/{id}")
|
||||
public String handleForm(@ModelAttribute Foo foo, Errors errors) {
|
||||
return (errors.hasErrors() ?
|
||||
"Form not processed" : "Processed form: " + foo);
|
||||
}
|
||||
}
|
||||
|
||||
private static class Foo {
|
||||
|
||||
private final Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
private int age;
|
||||
|
||||
public Foo(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return this.age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo[id=" + this.id + ", name='" + this.name + "', age=" + this.age + "]";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user