Search in sources :

Example 21 with ResolvableType

use of org.springframework.core.ResolvableType in project spring-framework by spring-projects.

the class ErrorsMethodArgumentResolver method getModelAttributeName.

private String getModelAttributeName(MethodParameter parameter) {
    Assert.isTrue(parameter.getParameterIndex() > 0, "Errors argument must be immediately after a model attribute argument.");
    int index = parameter.getParameterIndex() - 1;
    MethodParameter attributeParam = new MethodParameter(parameter.getMethod(), index);
    Class<?> attributeType = attributeParam.getParameterType();
    ResolvableType type = ResolvableType.forMethodParameter(attributeParam);
    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(type.resolve());
    Assert.isNull(adapter, "Errors/BindingResult cannot be used with an async model attribute. " + "Either declare the model attribute without the async wrapper type " + "or handle WebExchangeBindException through the async type.");
    ModelAttribute annot = parameter.getParameterAnnotation(ModelAttribute.class);
    if (annot != null && StringUtils.hasText(annot.value())) {
        return annot.value();
    }
    // TODO: Conventions does not deal with async wrappers
    return ClassUtils.getShortNameAsProperty(attributeType);
}
Also used : ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) MethodParameter(org.springframework.core.MethodParameter) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 22 with ResolvableType

use of org.springframework.core.ResolvableType 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 23 with ResolvableType

use of org.springframework.core.ResolvableType in project spring-framework by spring-projects.

the class AbstractMessageWriterResultHandler method writeBody.

@SuppressWarnings("unchecked")
protected Mono<Void> writeBody(Object body, MethodParameter bodyParameter, ServerWebExchange exchange) {
    ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
    Class<?> bodyClass = bodyType.resolve();
    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyClass, body);
    Publisher<?> publisher;
    ResolvableType elementType;
    if (adapter != null) {
        publisher = adapter.toPublisher(body);
        elementType = adapter.isNoValue() ? ResolvableType.forClass(Void.class) : bodyType.getGeneric(0);
    } else {
        publisher = Mono.justOrEmpty(body);
        elementType = (bodyClass == null && body != null ? ResolvableType.forInstance(body) : bodyType);
    }
    if (void.class == elementType.getRawClass() || Void.class == elementType.getRawClass()) {
        return Mono.from((Publisher<Void>) publisher);
    }
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    MediaType bestMediaType = selectMediaType(exchange, () -> getProducibleMediaTypes(elementType));
    if (bestMediaType != null) {
        for (HttpMessageWriter<?> messageWriter : getMessageWriters()) {
            if (messageWriter.canWrite(elementType, bestMediaType)) {
                return (messageWriter instanceof ServerHttpMessageWriter ? ((ServerHttpMessageWriter<?>) messageWriter).write((Publisher) publisher, bodyType, elementType, bestMediaType, request, response, Collections.emptyMap()) : messageWriter.write((Publisher) publisher, elementType, bestMediaType, response, Collections.emptyMap()));
            }
        }
    } else {
        if (getProducibleMediaTypes(elementType).isEmpty()) {
            return Mono.error(new IllegalStateException("No converter for return value type: " + elementType));
        }
    }
    return Mono.error(new NotAcceptableStatusException(getProducibleMediaTypes(elementType)));
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) ServerHttpMessageWriter(org.springframework.http.codec.ServerHttpMessageWriter) ReactiveAdapter(org.springframework.core.ReactiveAdapter) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse)

Example 24 with ResolvableType

use of org.springframework.core.ResolvableType in project spring-framework by spring-projects.

the class DefaultEntityResponseBuilderTests method fromPublisherResolvableType.

@Test
public void fromPublisherResolvableType() throws Exception {
    Flux<String> body = Flux.just("foo", "bar");
    ResolvableType type = ResolvableType.forClass(String.class);
    EntityResponse<Flux<String>> response = EntityResponse.fromPublisher(body, type).build().block();
    assertSame(body, response.entity());
}
Also used : Flux(reactor.core.publisher.Flux) ResolvableType(org.springframework.core.ResolvableType) Test(org.junit.Test)

Example 25 with ResolvableType

use of org.springframework.core.ResolvableType in project spring-framework by spring-projects.

the class MessageReaderArgumentResolverTests method emptyBody.

// More extensive "empty body" tests in RequestBody- and HttpEntityArgumentResolverTests
// SPR-9942
@Test
// SPR-9942
@SuppressWarnings("unchecked")
public void emptyBody() throws Exception {
    ServerWebExchange exchange = post("/path").contentType(MediaType.APPLICATION_JSON).toExchange();
    ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class);
    MethodParameter param = this.testMethod.arg(type);
    Mono<TestBean> result = (Mono<TestBean>) this.resolver.readBody(param, true, this.bindingContext, exchange).block();
    StepVerifier.create(result).expectError(ServerWebInputException.class).verify();
}
Also used : ServerWebExchange(org.springframework.web.server.ServerWebExchange) ServerWebInputException(org.springframework.web.server.ServerWebInputException) Mono(reactor.core.publisher.Mono) ResolvableType(org.springframework.core.ResolvableType) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.Test)

Aggregations

ResolvableType (org.springframework.core.ResolvableType)96 Test (org.junit.Test)66 MethodParameter (org.springframework.core.MethodParameter)20 DataBuffer (org.springframework.core.io.buffer.DataBuffer)15 ServerWebExchange (org.springframework.web.server.ServerWebExchange)14 List (java.util.List)11 MediaType (org.springframework.http.MediaType)10 Flux (reactor.core.publisher.Flux)10 Mono (reactor.core.publisher.Mono)10 Map (java.util.Map)9 Assert (org.springframework.util.Assert)7 Collections (java.util.Collections)6 MockServerWebExchange (org.springframework.mock.http.server.reactive.test.MockServerWebExchange)6 ArrayList (java.util.ArrayList)5 ReactiveAdapter (org.springframework.core.ReactiveAdapter)5 Pojo (org.springframework.http.codec.Pojo)5 ServerWebInputException (org.springframework.web.server.ServerWebInputException)5 Publisher (org.reactivestreams.Publisher)4 HttpMessageReader (org.springframework.http.codec.HttpMessageReader)4 Single (rx.Single)4