Search in sources :

Example 1 with BindingContext

use of org.springframework.web.reactive.BindingContext in project spring-framework by spring-projects.

the class ModelAttributeMethodArgumentResolver method resolveArgument.

@Override
public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {
    ResolvableType type = ResolvableType.forMethodParameter(parameter);
    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(type.resolve());
    ResolvableType valueType = (adapter != null ? type.getGeneric(0) : type);
    Assert.state(adapter == null || !adapter.isMultiValue(), getClass().getSimpleName() + " doesn't support multi-value reactive type wrapper: " + parameter.getGenericParameterType());
    String name = getAttributeName(valueType, parameter);
    Mono<?> valueMono = getAttributeMono(name, valueType, context.getModel());
    Map<String, Object> model = context.getModel().asMap();
    MonoProcessor<BindingResult> bindingResultMono = MonoProcessor.create();
    model.put(BindingResult.MODEL_KEY_PREFIX + name, bindingResultMono);
    return valueMono.then(value -> {
        WebExchangeDataBinder binder = context.createDataBinder(exchange, value, name);
        return binder.bind(exchange).doOnError(bindingResultMono::onError).doOnSuccess(aVoid -> {
            validateIfApplicable(binder, parameter);
            BindingResult errors = binder.getBindingResult();
            model.put(BindingResult.MODEL_KEY_PREFIX + name, errors);
            model.put(name, value);
            bindingResultMono.onNext(errors);
        }).then(Mono.fromCallable(() -> {
            BindingResult errors = binder.getBindingResult();
            if (adapter != null) {
                return adapter.fromPublisher(errors.hasErrors() ? Mono.error(new WebExchangeBindException(parameter, errors)) : valueMono);
            } else {
                if (errors.hasErrors() && !hasErrorsArgument(parameter)) {
                    throw new WebExchangeBindException(parameter, errors);
                }
                return value;
            }
        }));
    });
}
Also used : ReactiveAdapter(org.springframework.core.ReactiveAdapter) Errors(org.springframework.validation.Errors) Validated(org.springframework.validation.annotation.Validated) ClassUtils(org.springframework.util.ClassUtils) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) MonoProcessor(reactor.core.publisher.MonoProcessor) Mono(reactor.core.publisher.Mono) BindingResult(org.springframework.validation.BindingResult) BindingContext(org.springframework.web.reactive.BindingContext) HandlerMethodArgumentResolver(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver) ServerWebExchange(org.springframework.web.server.ServerWebExchange) HandlerMethodArgumentResolverSupport(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport) Model(org.springframework.ui.Model) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) Annotation(java.lang.annotation.Annotation) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) BeanUtils(org.springframework.beans.BeanUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) BindingResult(org.springframework.validation.BindingResult) ResolvableType(org.springframework.core.ResolvableType) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 2 with BindingContext

use of org.springframework.web.reactive.BindingContext in project spring-framework by spring-projects.

the class RequestMappingHandlerAdapter method handle.

@Override
public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
    Assert.notNull(handler, "Expected handler");
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    BindingContext bindingContext = new InitBinderBindingContext(getWebBindingInitializer(), getBinderMethods(handlerMethod));
    return this.modelInitializer.initModel(bindingContext, getAttributeMethods(handlerMethod), exchange).then(() -> {
        Function<Throwable, Mono<HandlerResult>> exceptionHandler = ex -> handleException(exchange, handlerMethod, bindingContext, ex);
        InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod);
        invocable.setArgumentResolvers(getArgumentResolvers());
        return invocable.invoke(exchange, bindingContext).doOnNext(result -> result.setExceptionHandler(exceptionHandler)).otherwise(exceptionHandler);
    });
}
Also used : InvocableHandlerMethod(org.springframework.web.reactive.result.method.InvocableHandlerMethod) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) BindingContext(org.springframework.web.reactive.BindingContext) MethodIntrospector.selectMethods(org.springframework.core.MethodIntrospector.selectMethods) Function(java.util.function.Function) HandlerMethodArgumentResolver(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver) InitializingBean(org.springframework.beans.factory.InitializingBean) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) LinkedHashMap(java.util.LinkedHashMap) HandlerMethod(org.springframework.web.method.HandlerMethod) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) ExceptionHandlerMethodResolver(org.springframework.web.method.annotation.ExceptionHandlerMethodResolver) Map(java.util.Map) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) DataBufferDecoder(org.springframework.core.codec.DataBufferDecoder) Method(java.lang.reflect.Method) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) HandlerAdapter(org.springframework.web.reactive.HandlerAdapter) WebBindingInitializer(org.springframework.web.bind.support.WebBindingInitializer) StringDecoder(org.springframework.core.codec.StringDecoder) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) SyncHandlerMethodArgumentResolver(org.springframework.web.reactive.result.method.SyncHandlerMethodArgumentResolver) Mono(reactor.core.publisher.Mono) ByteBufferDecoder(org.springframework.core.codec.ByteBufferDecoder) ApplicationContext(org.springframework.context.ApplicationContext) ByteArrayDecoder(org.springframework.core.codec.ByteArrayDecoder) HandlerResult(org.springframework.web.reactive.HandlerResult) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) Objects(java.util.Objects) List(java.util.List) ReflectionUtils(org.springframework.util.ReflectionUtils) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) ControllerAdviceBean(org.springframework.web.method.ControllerAdviceBean) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) InitBinder(org.springframework.web.bind.annotation.InitBinder) SyncInvocableHandlerMethod(org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod) ApplicationContextAware(org.springframework.context.ApplicationContextAware) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator) Assert(org.springframework.util.Assert) InvocableHandlerMethod(org.springframework.web.reactive.result.method.InvocableHandlerMethod) SyncInvocableHandlerMethod(org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod) Mono(reactor.core.publisher.Mono) BindingContext(org.springframework.web.reactive.BindingContext) InvocableHandlerMethod(org.springframework.web.reactive.result.method.InvocableHandlerMethod) HandlerMethod(org.springframework.web.method.HandlerMethod) SyncInvocableHandlerMethod(org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod)

Example 3 with BindingContext

use of org.springframework.web.reactive.BindingContext in project spring-framework by spring-projects.

the class ViewResolutionResultHandler method addBindingResult.

private void addBindingResult(BindingContext context, ServerWebExchange exchange) {
    Map<String, Object> model = context.getModel().asMap();
    model.keySet().stream().filter(name -> isBindingCandidate(name, model.get(name))).filter(name -> !model.containsKey(BindingResult.MODEL_KEY_PREFIX + name)).forEach(name -> {
        WebExchangeDataBinder binder = context.createDataBinder(exchange, model.get(name), name);
        model.put(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
    });
}
Also used : HttpRequestPathHelper(org.springframework.web.server.support.HttpRequestPathHelper) Ordered(org.springframework.core.Ordered) RequestedContentTypeResolver(org.springframework.web.reactive.accept.RequestedContentTypeResolver) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) BindingResult(org.springframework.validation.BindingResult) BindingContext(org.springframework.web.reactive.BindingContext) HandlerResultHandlerSupport(org.springframework.web.reactive.result.HandlerResultHandlerSupport) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Model(org.springframework.ui.Model) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) Locale(java.util.Locale) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) HandlerResultHandler(org.springframework.web.reactive.HandlerResultHandler) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) ReactiveAdapter(org.springframework.core.ReactiveAdapter) ClassUtils(org.springframework.util.ClassUtils) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) Mono(reactor.core.publisher.Mono) NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) Collectors(java.util.stream.Collectors) HandlerResult(org.springframework.web.reactive.HandlerResult) Flux(reactor.core.publisher.Flux) List(java.util.List) Collections(java.util.Collections) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator) BeanUtils(org.springframework.beans.BeanUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder)

Example 4 with BindingContext

use of org.springframework.web.reactive.BindingContext in project spring-framework by spring-projects.

the class ModelInitializerTests method basic.

@SuppressWarnings("unchecked")
@Test
public void basic() throws Exception {
    TestController controller = new TestController();
    Validator validator = mock(Validator.class);
    controller.setValidator(validator);
    List<SyncInvocableHandlerMethod> binderMethods = getBinderMethods(controller);
    List<InvocableHandlerMethod> attributeMethods = getAttributeMethods(controller);
    WebBindingInitializer bindingInitializer = new ConfigurableWebBindingInitializer();
    BindingContext bindingContext = new InitBinderBindingContext(bindingInitializer, binderMethods);
    this.modelInitializer.initModel(bindingContext, attributeMethods, this.exchange).block(Duration.ofMillis(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).block(Duration.ofMillis(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());
}
Also used : InvocableHandlerMethod(org.springframework.web.reactive.result.method.InvocableHandlerMethod) SyncInvocableHandlerMethod(org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod) Mono(reactor.core.publisher.Mono) SyncInvocableHandlerMethod(org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod) BindingContext(org.springframework.web.reactive.BindingContext) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) ConfigurableWebBindingInitializer(org.springframework.web.bind.support.ConfigurableWebBindingInitializer) Validator(org.springframework.validation.Validator) WebBindingInitializer(org.springframework.web.bind.support.WebBindingInitializer) ConfigurableWebBindingInitializer(org.springframework.web.bind.support.ConfigurableWebBindingInitializer) Test(org.junit.Test)

Example 5 with BindingContext

use of org.springframework.web.reactive.BindingContext in project spring-framework by spring-projects.

the class PathVariableMapMethodArgumentResolverTests method resolveArgumentNoUriVars.

@Test
public void resolveArgumentNoUriVars() throws Exception {
    Mono<Object> mono = this.resolver.resolveArgument(this.paramMap, new BindingContext(), this.exchange);
    Object result = mono.block();
    assertEquals(Collections.emptyMap(), result);
}
Also used : BindingContext(org.springframework.web.reactive.BindingContext) Test(org.junit.Test)

Aggregations

BindingContext (org.springframework.web.reactive.BindingContext)43 Test (org.junit.Test)26 ServerWebExchange (org.springframework.web.server.ServerWebExchange)16 MethodParameter (org.springframework.core.MethodParameter)14 SynthesizingMethodParameter (org.springframework.core.annotation.SynthesizingMethodParameter)10 ReactiveAdapterRegistry (org.springframework.core.ReactiveAdapterRegistry)9 ConfigurableWebBindingInitializer (org.springframework.web.bind.support.ConfigurableWebBindingInitializer)8 WebDataBinder (org.springframework.web.bind.WebDataBinder)7 DefaultFormattingConversionService (org.springframework.format.support.DefaultFormattingConversionService)6 Mono (reactor.core.publisher.Mono)6 Map (java.util.Map)5 Before (org.junit.Before)5 HashMap (java.util.HashMap)4 Optional (java.util.Optional)4 WebExchangeDataBinder (org.springframework.web.bind.support.WebExchangeDataBinder)4 ServerWebInputException (org.springframework.web.server.ServerWebInputException)4 Method (java.lang.reflect.Method)3 List (java.util.List)3 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)3 ReactiveAdapter (org.springframework.core.ReactiveAdapter)3