/** * Consume up to the specified number of bytes from the response body and * cancel if any more data arrives. * <p>Internally delegates to {@link DataBufferUtils#takeUntilByteCount}. * @param maxByteCount the limit as number of bytes * @return the filter to limit the response size with * @since 5.1 */ public static ExchangeFilterFunction limitResponseSize(long maxByteCount) { return (request, next) -> next.exchange(request).map(response -> { Flux<DataBuffer> body = response.body(BodyExtractors.toDataBuffers()); body = DataBufferUtils.takeUntilByteCount(body, maxByteCount); return ClientResponse.from(response).body(body).build(); }); }
private static Function<ClientResponse, Mono<ClientResponse>> convertClientResponse(Function<Flux<DataBuffer>, Flux<DataBuffer>> bodConverter, MediaType contentType) { return response -> { ClientResponse convertedResponse = ClientResponse.from(response).headers(headers -> { headers.replace(HttpHeaders.CONTENT_TYPE, singletonList(contentType.toString())); headers.remove(HttpHeaders.CONTENT_LENGTH); }).body(response.bodyToFlux(DataBuffer.class).transform(bodConverter)).build(); return Mono.just(convertedResponse); }; }
@Override public void onNext(ClientResponse response) { this.done = true; try { // decorate response body this.actual .onNext(ClientResponse.from(response) .body(response.bodyToFlux(DataBuffer.class) .transform(this.scopePassingTransformer)) .build()); } finally { terminateSpan(response, null); } }
@Test public void from() { Flux<DataBuffer> otherBody = Flux.just("foo", "bar") .map(s -> s.getBytes(StandardCharsets.UTF_8)) .map(dataBufferFactory::wrap); ClientResponse other = ClientResponse.create(HttpStatus.BAD_REQUEST, ExchangeStrategies.withDefaults()) .header("foo", "bar") .cookie("baz", "qux") .body(otherBody) .build(); Flux<DataBuffer> body = Flux.just("baz") .map(s -> s.getBytes(StandardCharsets.UTF_8)) .map(dataBufferFactory::wrap); ClientResponse result = ClientResponse.from(other) .headers(httpHeaders -> httpHeaders.set("foo", "baar")) .cookies(cookies -> cookies.set("baz", ResponseCookie.from("baz", "quux").build())) .body(body) .build(); assertEquals(HttpStatus.BAD_REQUEST, result.statusCode()); assertEquals(1, result.headers().asHttpHeaders().size()); assertEquals("baar", result.headers().asHttpHeaders().getFirst("foo")); assertEquals(1, result.cookies().size()); assertEquals("quux", result.cookies().getFirst("baz").getValue()); StepVerifier.create(result.bodyToFlux(String.class)) .expectNext("baz") .verifyComplete(); }
@Override public void onNext(ClientResponse response) { this.done = true; try { // decorate response body this.actual .onNext(ClientResponse.from(response) .body(response.bodyToFlux(DataBuffer.class) .transform(this.scopePassingTransformer)) .build()); } finally { terminateSpan(response, null); } }