/** * Adapt the given request processor function to a filter function that only * operates on the {@code ClientRequest}. * @param processor the request processor * @return the resulting filter adapter */ static ExchangeFilterFunction ofRequestProcessor(Function<ClientRequest, Mono<ClientRequest>> processor) { Assert.notNull(processor, "ClientRequest Function must not be null"); return (request, next) -> processor.apply(request).flatMap(next::exchange); }
/** * Adapt the given request processor function to a filter function that only operates * on the {@code ServerRequest}. * @param requestProcessor the request processor * @return the filter adaptation of the request processor */ static HandlerFilterFunction<?, ?> ofRequestProcessor( Function<ServerRequest, Mono<ServerRequest>> requestProcessor) { Assert.notNull(requestProcessor, "Function must not be null"); return (request, next) -> requestProcessor.apply(request).flatMap(next::handle); }
/** * Adapt the given response processor function to a filter function that only operates * on the {@code ServerResponse}. * @param responseProcessor the response processor * @return the filter adaptation of the request processor */ static <T extends ServerResponse, R extends ServerResponse> HandlerFilterFunction<T, R> ofResponseProcessor( Function<T, Mono<R>> responseProcessor) { Assert.notNull(responseProcessor, "Function must not be null"); return (request, next) -> next.handle(request).flatMap(responseProcessor); }
/** * Adapt the given response processor function to a filter function that * only operates on the {@code ClientResponse}. * @param processor the response processor * @return the resulting filter adapter */ static ExchangeFilterFunction ofResponseProcessor(Function<ClientResponse, Mono<ClientResponse>> processor) { Assert.notNull(processor, "ClientResponse Function must not be null"); return (request, next) -> next.exchange(request).flatMap(processor); }
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); }
@Override public Mono<Void> write(Publisher<? extends Resource> inputStream, ResolvableType elementType, @Nullable MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints) { return Mono.from(inputStream).flatMap(resource -> writeResource(resource, elementType, mediaType, message, hints)); }
@Override public Mono<Void> write(Publisher<? extends MultiValueMap<String, ?>> inputStream, ResolvableType elementType, @Nullable MediaType mediaType, ReactiveHttpOutputMessage outputMessage, Map<String, Object> hints) { return Mono.from(inputStream).flatMap(map -> { if (this.formWriter == null || isMultipart(map, mediaType)) { return writeMultipart(map, outputMessage, hints); } else { @SuppressWarnings("unchecked") MultiValueMap<String, String> formData = (MultiValueMap<String, String>) map; return this.formWriter.write(Mono.just(formData), elementType, mediaType, outputMessage, hints); } }); }
protected Mono<Resource> getResource(ServerWebExchange exchange) { String name = HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE; PathContainer pathWithinHandler = exchange.getRequiredAttribute(name); String path = processPath(pathWithinHandler.value()); if (!StringUtils.hasText(path) || isInvalidPath(path)) { return Mono.empty(); } if (isInvalidEncodedPath(path)) { return Mono.empty(); } Assert.state(this.resolverChain != null, "ResourceResolverChain not initialized"); Assert.state(this.transformerChain != null, "ResourceTransformerChain not initialized"); return this.resolverChain.resolveResource(exchange, path, getLocations()) .flatMap(resource -> this.transformerChain.transform(exchange, resource)); }
@Override public Mono<Void> doFilter(ServerWebExchange exchange, WebFilterChain chain) { return doAsyncWork().flatMap(asyncResult -> { logger.debug("Async result: " + asyncResult); return chain.filter(exchange); }); }
@Override public Mono<Void> handle(ServerWebExchange exchange) { if (this.handlerMappings == null) { return createNotFoundError(); } return Flux.fromIterable(this.handlerMappings) .concatMap(mapping -> mapping.getHandler(exchange)) .next() .switchIfEmpty(createNotFoundError()) .flatMap(handler -> invokeHandler(exchange, handler)) .flatMap(result -> handleResult(exchange, result)); }
private Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { return getResultHandler(result).handleResult(exchange, result) .onErrorResume(ex -> result.applyExceptionHandler(ex).flatMap(exceptionResult -> getResultHandler(exceptionResult).handleResult(exchange, exceptionResult))); }
@Bean public RouterFunction<?> handler() { return RouterFunctions.route() .GET("/sessionClassName", request -> request.session().flatMap(session -> { String className = session.getClass().getSimpleName(); return ServerResponse.ok().syncBody(className); })) .build(); }
@Test public void defaultContentType() { Mono<RenderingResponse> result = RenderingResponse.create("view").build(); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost")); TestView view = new TestView(); ViewResolver viewResolver = mock(ViewResolver.class); when(viewResolver.resolveViewName(any(), any())).thenReturn(Mono.just(view)); List<ViewResolver> viewResolvers = new ArrayList<>(); viewResolvers.add(viewResolver); ServerResponse.Context context = mock(ServerResponse.Context.class); when(context.viewResolvers()).thenReturn(viewResolvers); StepVerifier.create(result.flatMap(response -> response.writeTo(exchange, context))) .verifyComplete(); assertEquals(ViewResolverSupport.DEFAULT_CONTENT_TYPE, exchange.getResponse().getHeaders().getContentType()); }
public Mono<ServerResponse> parts(ServerRequest request) { return request.body(BodyExtractors.toParts()).collectList() .flatMap(parts -> { try { assertEquals(2, parts.size()); assertEquals("foo.txt", ((FilePart) parts.get(0)).filename()); assertEquals("bar", ((FormFieldPart) parts.get(1)).value()); } catch(Exception e) { return Mono.error(e); } return ServerResponse.ok().build(); }); } }
@Test public void buildVoidPublisher() { Mono<Void> mono = Mono.empty(); Mono<ServerResponse> result = ServerResponse.ok().build(mono); MockServerHttpRequest request = MockServerHttpRequest.get("http://example.com").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); result.flatMap(res -> res.writeTo(exchange, EMPTY_CONTEXT)).block(); MockServerHttpResponse response = exchange.getResponse(); StepVerifier.create(response.getBody()).expectComplete().verify(); }
@Test public void value() { Mono<Msg> result = this.webClient.get() .uri("/message") .exchange() .doOnNext(response -> { Assert.assertFalse(response.headers().contentType().get().getParameters().containsKey("delimited")); Assert.assertEquals("sample.proto", response.headers().header("X-Protobuf-Schema").get(0)); Assert.assertEquals("Msg", response.headers().header("X-Protobuf-Message").get(0)); }) .flatMap(response -> response.bodyToMono(Msg.class)); StepVerifier.create(result) .expectNext(TEST_MSG) .verifyComplete(); }
@Test public void shouldReceiveEmptyResponse() { prepareResponse(response -> response.setHeader("Content-Length", "0").setBody("")); Mono<ResponseEntity<Void>> result = this.webClient.get() .uri("/noContent") .exchange() .flatMap(response -> response.toEntity(Void.class)); StepVerifier.create(result).assertNext(r -> { assertTrue(r.getStatusCode().is2xxSuccessful()); }).verifyComplete(); }
@Test public void build() { ResponseCookie cookie = ResponseCookie.from("name", "value").build(); Mono<ServerResponse> result = ServerResponse.status(HttpStatus.CREATED) .header("MyKey", "MyValue") .cookie(cookie).build(); MockServerHttpRequest request = MockServerHttpRequest.get("http://example.com").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); result.flatMap(res -> res.writeTo(exchange, EMPTY_CONTEXT)).block(); MockServerHttpResponse response = exchange.getResponse(); assertEquals(HttpStatus.CREATED, response.getStatusCode()); assertEquals("MyValue", response.getHeaders().getFirst("MyKey")); assertEquals("value", response.getCookies().getFirst("name").getValue()); StepVerifier.create(response.getBody()).expectComplete().verify(); }