Search in sources :

Example 11 with ServerWebExchange

use of org.springframework.web.server.ServerWebExchange in project spring-framework by spring-projects.

the class ResponseEntityResultHandler method handleResult.

@Override
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
    Mono<?> returnValueMono;
    MethodParameter bodyParameter;
    ReactiveAdapter adapter = getAdapter(result);
    if (adapter != null) {
        Assert.isTrue(!adapter.isMultiValue(), "Only a single ResponseEntity supported");
        returnValueMono = Mono.from(adapter.toPublisher(result.getReturnValue()));
        bodyParameter = result.getReturnTypeSource().nested().nested();
    } else {
        returnValueMono = Mono.justOrEmpty(result.getReturnValue());
        bodyParameter = result.getReturnTypeSource().nested();
    }
    return returnValueMono.then(returnValue -> {
        Assert.isInstanceOf(HttpEntity.class, returnValue, "HttpEntity expected");
        HttpEntity<?> httpEntity = (HttpEntity<?>) returnValue;
        if (httpEntity instanceof ResponseEntity) {
            ResponseEntity<?> responseEntity = (ResponseEntity<?>) httpEntity;
            exchange.getResponse().setStatusCode(responseEntity.getStatusCode());
        }
        HttpHeaders entityHeaders = httpEntity.getHeaders();
        HttpHeaders responseHeaders = exchange.getResponse().getHeaders();
        if (!entityHeaders.isEmpty()) {
            entityHeaders.entrySet().stream().filter(entry -> !responseHeaders.containsKey(entry.getKey())).forEach(entry -> responseHeaders.put(entry.getKey(), entry.getValue()));
        }
        if (httpEntity.getBody() == null) {
            return exchange.getResponse().setComplete();
        }
        String etag = entityHeaders.getETag();
        Instant lastModified = Instant.ofEpochMilli(entityHeaders.getLastModified());
        HttpMethod httpMethod = exchange.getRequest().getMethod();
        if (SAFE_METHODS.contains(httpMethod) && exchange.checkNotModified(etag, lastModified)) {
            return exchange.getResponse().setComplete();
        }
        return writeBody(httpEntity.getBody(), bodyParameter, exchange);
    });
}
Also used : RequestEntity(org.springframework.http.RequestEntity) Arrays(java.util.Arrays) ReactiveAdapter(org.springframework.core.ReactiveAdapter) RequestedContentTypeResolver(org.springframework.web.reactive.accept.RequestedContentTypeResolver) HttpHeaders(org.springframework.http.HttpHeaders) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) Instant(java.time.Instant) HandlerResult(org.springframework.web.reactive.HandlerResult) ServerWebExchange(org.springframework.web.server.ServerWebExchange) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) MethodParameter(org.springframework.core.MethodParameter) HandlerResultHandler(org.springframework.web.reactive.HandlerResultHandler) ResponseEntity(org.springframework.http.ResponseEntity) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Assert(org.springframework.util.Assert) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpEntity(org.springframework.http.HttpEntity) Instant(java.time.Instant) MethodParameter(org.springframework.core.MethodParameter) ReactiveAdapter(org.springframework.core.ReactiveAdapter) HttpMethod(org.springframework.http.HttpMethod)

Example 12 with ServerWebExchange

use of org.springframework.web.server.ServerWebExchange 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 13 with ServerWebExchange

use of org.springframework.web.server.ServerWebExchange in project spring-framework by spring-projects.

the class DispatcherHandlerErrorTests method unknownReturnType.

@Test
public void unknownReturnType() throws Exception {
    ServerWebExchange exchange = MockServerHttpRequest.get("/unknown-return-type").toExchange();
    Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
    StepVerifier.create(publisher).consumeErrorWith(error -> {
        assertThat(error, instanceOf(IllegalStateException.class));
        assertThat(error.getMessage(), startsWith("No HandlerResultHandler"));
    }).verify();
}
Also used : CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) RequestMappingHandlerMapping(org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping) StepVerifier(reactor.test.StepVerifier) RequestMappingHandlerAdapter(org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter) ServerWebInputException(org.springframework.web.server.ServerWebInputException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) Controller(org.springframework.stereotype.Controller) WebHandler(org.springframework.web.server.WebHandler) ServerWebExchange(org.springframework.web.server.ServerWebExchange) RequestBody(org.springframework.web.bind.annotation.RequestBody) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Assert.assertSame(org.junit.Assert.assertSame) Assert.assertThat(org.junit.Assert.assertThat) ResponseBodyResultHandler(org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) Duration(java.time.Duration) HeaderContentTypeResolver(org.springframework.web.reactive.accept.HeaderContentTypeResolver) APPLICATION_JSON(org.springframework.http.MediaType.APPLICATION_JSON) Before(org.junit.Before) ResponseStatusException(org.springframework.web.server.ResponseStatusException) ExceptionHandlingWebHandler(org.springframework.web.server.handler.ExceptionHandlingWebHandler) WebExceptionHandler(org.springframework.web.server.WebExceptionHandler) Publisher(org.reactivestreams.Publisher) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) Configuration(org.springframework.context.annotation.Configuration) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) MockServerHttpRequest(org.springframework.mock.http.server.reactive.test.MockServerHttpRequest) Matchers.is(org.hamcrest.Matchers.is) Bean(org.springframework.context.annotation.Bean) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Test(org.junit.Test)

Example 14 with ServerWebExchange

use of org.springframework.web.server.ServerWebExchange in project spring-framework by spring-projects.

the class PathExtensionContentTypeResolverTests method resolveMediaTypesFromMapping.

@Test
public void resolveMediaTypesFromMapping() throws Exception {
    ServerWebExchange exchange = MockServerHttpRequest.get("/test.html").toExchange();
    PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver();
    List<MediaType> mediaTypes = resolver.resolveMediaTypes(exchange);
    assertEquals(Collections.singletonList(new MediaType("text", "html")), mediaTypes);
    Map<String, MediaType> mapping = Collections.singletonMap("HTML", MediaType.APPLICATION_XHTML_XML);
    resolver = new PathExtensionContentTypeResolver(mapping);
    mediaTypes = resolver.resolveMediaTypes(exchange);
    assertEquals(Collections.singletonList(new MediaType("application", "xhtml+xml")), mediaTypes);
}
Also used : ServerWebExchange(org.springframework.web.server.ServerWebExchange) MediaType(org.springframework.http.MediaType) Test(org.junit.Test)

Example 15 with ServerWebExchange

use of org.springframework.web.server.ServerWebExchange in project spring-framework by spring-projects.

the class WebFluxConfigurationSupportTests method requestMappingHandlerMapping.

@Test
public void requestMappingHandlerMapping() throws Exception {
    ApplicationContext context = loadConfig(WebFluxConfig.class);
    String name = "requestMappingHandlerMapping";
    RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
    assertNotNull(mapping);
    assertEquals(0, mapping.getOrder());
    assertTrue(mapping.useSuffixPatternMatch());
    assertTrue(mapping.useTrailingSlashMatch());
    assertTrue(mapping.useRegisteredSuffixPatternMatch());
    name = "webFluxContentTypeResolver";
    RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
    assertSame(resolver, mapping.getContentTypeResolver());
    ServerWebExchange exchange = MockServerHttpRequest.get("/path.json").toExchange();
    List<MediaType> list = Collections.singletonList(MediaType.APPLICATION_JSON);
    assertEquals(list, resolver.resolveMediaTypes(exchange));
    exchange = MockServerHttpRequest.get("/path.xml").toExchange();
    assertEquals(Collections.emptyList(), resolver.resolveMediaTypes(exchange));
}
Also used : ServerWebExchange(org.springframework.web.server.ServerWebExchange) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) MediaType(org.springframework.http.MediaType) RequestMappingHandlerMapping(org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping) RequestedContentTypeResolver(org.springframework.web.reactive.accept.RequestedContentTypeResolver) Test(org.junit.Test)

Aggregations

ServerWebExchange (org.springframework.web.server.ServerWebExchange)158 Test (org.junit.Test)138 MockServerWebExchange (org.springframework.mock.http.server.reactive.test.MockServerWebExchange)53 Mono (reactor.core.publisher.Mono)22 ServerHttpResponse (org.springframework.http.server.reactive.ServerHttpResponse)20 MediaType (org.springframework.http.MediaType)18 BindingContext (org.springframework.web.reactive.BindingContext)17 MethodParameter (org.springframework.core.MethodParameter)15 List (java.util.List)14 ResolvableType (org.springframework.core.ResolvableType)14 Map (java.util.Map)12 Collections (java.util.Collections)11 HttpStatus (org.springframework.http.HttpStatus)11 StepVerifier (reactor.test.StepVerifier)11 Assert.assertEquals (org.junit.Assert.assertEquals)10 MockServerHttpRequest (org.springframework.mock.http.server.reactive.test.MockServerHttpRequest)10 ResponseStatusException (org.springframework.web.server.ResponseStatusException)9 ServerWebInputException (org.springframework.web.server.ServerWebInputException)9 ReactiveAdapterRegistry (org.springframework.core.ReactiveAdapterRegistry)8 NotAcceptableStatusException (org.springframework.web.server.NotAcceptableStatusException)8