org.springframework.web.reactive.function.client.ExchangeFilterFunction Java Examples
The following examples show how to use
org.springframework.web.reactive.function.client.ExchangeFilterFunction.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InstanceExchangeFilterFunctions.java From Moss with Apache License 2.0 | 7 votes |
public static ExchangeFilterFunction convertLegacyEndpoint(LegacyEndpointConverter converter) { return (ClientRequest request, ExchangeFunction next) -> { Mono<ClientResponse> clientResponse = next.exchange(request); if (request.attribute(ATTRIBUTE_ENDPOINT).map(converter::canConvert).orElse(false)) { return clientResponse.flatMap(response -> { if (response.headers() .contentType() .map(t -> ACTUATOR_V1_MEDIATYPE.isCompatibleWith(t) || APPLICATION_JSON.isCompatibleWith(t)) .orElse(false)) { return convertClientResponse(converter::convert, ACTUATOR_V2_MEDIATYPE).apply(response); } return Mono.just(response); }); } return clientResponse; }; }
Example #2
Source File: LogFilters.java From tutorials with MIT License | 6 votes |
private static ExchangeFilterFunction logResponse() { return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("Response: \n") .append("Status: ") .append(clientResponse.rawStatusCode()); clientResponse .headers() .asHttpHeaders() .forEach((key, value1) -> value1.forEach(value -> sb .append("\n") .append(key) .append(":") .append(value))); log.debug(sb.toString()); } return Mono.just(clientResponse); }); }
Example #3
Source File: LogFilters.java From tutorials with MIT License | 6 votes |
private static ExchangeFilterFunction logRequest() { return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> { if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("Request: \n") .append(clientRequest.method()) .append(" ") .append(clientRequest.url()); clientRequest .headers() .forEach((name, values) -> values.forEach(value -> sb .append("\n") .append(name) .append(":") .append(value))); log.debug(sb.toString()); } return Mono.just(clientRequest); }); }
Example #4
Source File: MainController.java From keycloak-springsecurity5-sample with GNU General Public License v3.0 | 6 votes |
private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) { return ExchangeFilterFunction.ofRequestProcessor( clientRequest -> { ClientRequest authorizedRequest = ClientRequest.from(clientRequest) .header(HttpHeaders.AUTHORIZATION, "Bearer " + authorizedClient.getAccessToken().getTokenValue()) .build(); return Mono.just(authorizedRequest); }); }
Example #5
Source File: InstanceExchangeFilterFunctionsTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void should_convert_v1_actuator() { ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoint(new TestLegacyEndpointConverter()); ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")) .attribute(ATTRIBUTE_ENDPOINT, "test") .build(); ClientResponse response = ClientResponse.create(HttpStatus.OK) .header(CONTENT_TYPE, ActuatorMediaType.V1_JSON) .body(Flux.just(ORIGINAL)) .build(); Mono<ClientResponse> convertedResponse = filter.filter(request, r -> Mono.just(response)); StepVerifier.create(convertedResponse) .assertNext(r -> StepVerifier.create(r.body(BodyExtractors.toDataBuffers())) .expectNext(CONVERTED) .verifyComplete()) .verifyComplete(); }
Example #6
Source File: InstanceExchangeFilterFunctionsTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void should_convert_json() { ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoint(new TestLegacyEndpointConverter()); ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")) .attribute(ATTRIBUTE_ENDPOINT, "test") .build(); ClientResponse response = ClientResponse.create(HttpStatus.OK) .header(CONTENT_TYPE, APPLICATION_JSON_VALUE) .body(Flux.just(ORIGINAL)) .build(); Mono<ClientResponse> convertedResponse = filter.filter(request, r -> Mono.just(response)); StepVerifier.create(convertedResponse) .assertNext(r -> StepVerifier.create(r.body(BodyExtractors.toDataBuffers())) .expectNext(CONVERTED) .verifyComplete()) .verifyComplete(); }
Example #7
Source File: InstanceExchangeFilterFunctionsTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void should_not_convert_v2_actuator() { ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoint(new TestLegacyEndpointConverter()); ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")) .attribute(ATTRIBUTE_ENDPOINT, "test") .build(); ClientResponse response = ClientResponse.create(HttpStatus.OK) .header(CONTENT_TYPE, ActuatorMediaType.V2_JSON) .body(Flux.just(ORIGINAL)) .build(); Mono<ClientResponse> convertedResponse = filter.filter(request, r -> Mono.just(response)); StepVerifier.create(convertedResponse) .assertNext(r -> StepVerifier.create(r.body(BodyExtractors.toDataBuffers())) .expectNext(ORIGINAL) .verifyComplete()) .verifyComplete(); }
Example #8
Source File: InstanceExchangeFilterFunctionsTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void should_retry_using_default() { ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(1, emptyMap()); ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")).build(); ClientResponse response = mock(ClientResponse.class); AtomicLong invocationCount = new AtomicLong(0L); ExchangeFunction exchange = r -> Mono.fromSupplier(() -> { if (invocationCount.getAndIncrement() == 0) { throw new IllegalStateException("Test"); } return response; }); StepVerifier.create(filter.filter(request, exchange)).expectNext(response).verifyComplete(); assertThat(invocationCount.get()).isEqualTo(2); }
Example #9
Source File: InstanceExchangeFilterFunctionsTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void should_retry_using_endpoint_value_default() { ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(0, singletonMap("test", 1)); ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")) .attribute(ATTRIBUTE_ENDPOINT, "test") .build(); ClientResponse response = mock(ClientResponse.class); AtomicLong invocationCount = new AtomicLong(0L); ExchangeFunction exchange = r -> Mono.fromSupplier(() -> { if (invocationCount.getAndIncrement() == 0) { throw new IllegalStateException("Test"); } return response; }); StepVerifier.create(filter.filter(request, exchange)).expectNext(response).verifyComplete(); assertThat(invocationCount.get()).isEqualTo(2); }
Example #10
Source File: ResponseLoggingCustomizer.java From blog-tutorials with MIT License | 5 votes |
private ExchangeFilterFunction logResponse() { return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { logger.info("Response: {}", clientResponse.statusCode()); logger.info("--- Http Headers of Response: ---"); clientResponse.headers().asHttpHeaders() .forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value))); return Mono.just(clientResponse); }); }
Example #11
Source File: ResponseLoggingCustomizer.java From blog-tutorials with MIT License | 5 votes |
private ExchangeFilterFunction logRequest() { return (clientRequest, next) -> { logger.info("Request: {} {}", clientRequest.method(), clientRequest.url()); logger.info("--- Http Headers of Request: ---"); clientRequest.headers().forEach(this::logHeader); return next.exchange(clientRequest); }; }
Example #12
Source File: BackendService.java From influx-proxy with Apache License 2.0 | 5 votes |
public static ExchangeFilterFunction logRequest() { return (clientRequest, next) -> { if (requestLog.isDebugEnabled()) { requestLog.debug("Request: {} {}", clientRequest.method(), clientRequest.url()); clientRequest.headers() .forEach((name, values) -> values.forEach(value -> requestLog.debug("{}={}", name, value))); } return next.exchange(clientRequest); }; }
Example #13
Source File: TracingWebClientBeanPostProcessor.java From java-spring-web with Apache License 2.0 | 5 votes |
private Consumer<List<ExchangeFilterFunction>> addTraceExchangeFilterFunctionIfNotPresent() { return functions -> { if (functions.stream() .noneMatch(function -> function instanceof TracingExchangeFilterFunction)) { functions.add(new TracingExchangeFilterFunction(tracer, spanDecorators)); } }; }
Example #14
Source File: MainController.java From okta-spring-security-5-example with Apache License 2.0 | 5 votes |
private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) { return ExchangeFilterFunction.ofRequestProcessor( clientRequest -> { ClientRequest authorizedRequest = ClientRequest.from(clientRequest) .header(HttpHeaders.AUTHORIZATION, "Bearer " + authorizedClient.getAccessToken().getTokenValue()) .build(); return Mono.just(authorizedRequest); }); }
Example #15
Source File: WebClientBuilder.java From spring-vault with Apache License 2.0 | 5 votes |
/** * Add the {@link ExchangeFilterFunction ExchangeFilterFunctions} that should be * applied to the {@link ClientRequest}. {@link ExchangeFilterFunction}s are applied * in the order that they were added. * @param filterFunctions the request customizers to add. * @return {@code this} {@link WebClientBuilder}. */ public WebClientBuilder filter(ExchangeFilterFunction... filterFunctions) { Assert.notNull(filterFunctions, "ExchangeFilterFunctions must not be null"); this.filterFunctions.addAll(Arrays.asList(filterFunctions)); return this; }
Example #16
Source File: ReactiveVaultTemplate.java From spring-vault with Apache License 2.0 | 5 votes |
private ExchangeFilterFunction getSessionFilter() { return ofRequestProcessor(request -> this.vaultTokenSupplier.getVaultToken().map(token -> { return ClientRequest.from(request).headers(headers -> { headers.set(VaultHttpHeaders.VAULT_TOKEN, token.getToken()); }).build(); })); }
Example #17
Source File: WebClientConfiguration.java From charon-spring-boot-starter with Apache License 2.0 | 5 votes |
WebClient configure(RequestMappingConfiguration configuration) { ClientHttpConnector connector = clientHttpConnectorCreator.createConnector(timeoutConfiguration); List<ExchangeFilterFunction> interceptors = new ArrayList<>(createHttpRequestInterceptors(configuration)); interceptors.addAll(exchangeFilterFunctions); return builder() .clientConnector(connector) .filters(filters -> filters.addAll(interceptors)) .build(); }
Example #18
Source File: TraceWebClientBeanPostProcessor.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
private Consumer<List<ExchangeFilterFunction>> addTraceExchangeFilterFunctionIfNotPresent() { return functions -> { boolean noneMatch = noneMatchTraceExchangeFunction(functions); if (noneMatch) { functions.add(new TraceExchangeFilterFunction(this.springContext)); } }; }
Example #19
Source File: TraceWebClientBeanPostProcessor.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
private boolean noneMatchTraceExchangeFunction( List<ExchangeFilterFunction> functions) { for (ExchangeFilterFunction function : functions) { if (function instanceof TraceExchangeFilterFunction) { return false; } } return true; }
Example #20
Source File: WebTestClientTestBase.java From spring-auto-restdocs with Apache License 2.0 | 5 votes |
protected ExchangeFilterFunction userToken() { return (request, next) -> { // If the tests requires setup logic for users, you can place it here. // Authorization headers or cookies for users should be added here as well. // TODO: enable oAuth // String accessToken = getAccessToken("test", "test"); // request.headers().add("Authorization", "Bearer " + accessToken); // documentAuthorization(request, "User access token required."); return next.exchange(request); }; }
Example #21
Source File: LoadBalancerTestUtils.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
static void assertLoadBalanced(WebClient.Builder webClientBuilder, Class<?> exchangeFilterFunctionClass) { List<ExchangeFilterFunction> filters = getFilters(webClientBuilder); then(filters).hasSize(1); then(filters.get(0)) .isInstanceOf(DeferringLoadBalancerExchangeFilterFunction.class); DeferringLoadBalancerExchangeFilterFunction interceptor = (DeferringLoadBalancerExchangeFilterFunction) filters .get(0); interceptor.tryResolveDelegate(); then(interceptor.getDelegate()).isInstanceOf(exchangeFilterFunctionClass); }
Example #22
Source File: WebClientTransportClientFactory.java From spring-cloud-netflix with Apache License 2.0 | 5 votes |
private ExchangeFilterFunction http4XxErrorExchangeFilterFunction() { return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { // literally 400 pass the tests, not 4xxClientError if (clientResponse.statusCode().value() == 400) { ClientResponse newResponse = ClientResponse.from(clientResponse) .statusCode(HttpStatus.OK).build(); newResponse.body((clientHttpResponse, context) -> { return clientHttpResponse.getBody(); }); return Mono.just(newResponse); } return Mono.just(clientResponse); }); }
Example #23
Source File: WebClientFilters.java From tutorials with MIT License | 5 votes |
public static ExchangeFilterFunction demoFilter() { ExchangeFilterFunction filterFunction = (clientRequest, nextFilter) -> { LOG.info("WebClient fitler executed"); return nextFilter.exchange(clientRequest); }; return filterFunction; }
Example #24
Source File: SimpleWebClientConfiguration.java From blog-tutorials with MIT License | 5 votes |
private ExchangeFilterFunction logResponse() { return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { logger.info("Response: {}", clientResponse.statusCode()); clientResponse.headers().asHttpHeaders() .forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value))); return Mono.just(clientResponse); }); }
Example #25
Source File: SimpleWebClientConfiguration.java From blog-tutorials with MIT License | 5 votes |
private ExchangeFilterFunction logRequest() { return (clientRequest, next) -> { logger.info("Request: {} {}", clientRequest.method(), clientRequest.url()); logger.info("--- Http Headers: ---"); clientRequest.headers().forEach(this::logHeader); logger.info("--- Http Cookies: ---"); clientRequest.cookies().forEach(this::logHeader); return next.exchange(clientRequest); }; }
Example #26
Source File: ReservationClientApplication.java From training with Apache License 2.0 | 5 votes |
@Bean WebClient webClient(LoadBalancerExchangeFilterFunction eff) { ExchangeFilterFunction fallback = (clientRequest, exchangeFunction) -> { try { return eff.filter(clientRequest, exchangeFunction); } catch (Exception e) { return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE).build()); } }; return WebClient.builder() .filter(fallback) .build(); }
Example #27
Source File: InstanceExchangeFilterFunctions.java From Moss with Apache License 2.0 | 5 votes |
public static ExchangeFilterFunction setInstance(Mono<Instance> instance) { return (request, next) -> instance.map(i -> ClientRequest.from(request) .attribute(ATTRIBUTE_INSTANCE, i) .build()) .switchIfEmpty(request.url().isAbsolute() ? Mono.just(request) : Mono.error( new ResolveInstanceException("Could not resolve Instance"))) .flatMap(next::exchange); }
Example #28
Source File: InstanceExchangeFilterFunctionsTest.java From Moss with Apache License 2.0 | 5 votes |
@Test public void should_not_retry_for_put_post_patch_delete() { ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(1, emptyMap()); AtomicLong invocationCount = new AtomicLong(0L); ExchangeFunction exchange = r -> Mono.fromSupplier(() -> { invocationCount.incrementAndGet(); throw new IllegalStateException("Test"); }); ClientRequest patchRequest = ClientRequest.create(HttpMethod.PATCH, URI.create("/test")).build(); StepVerifier.create(filter.filter(patchRequest, exchange)).expectError(IllegalStateException.class).verify(); assertThat(invocationCount.get()).isEqualTo(1); invocationCount.set(0L); ClientRequest putRequest = ClientRequest.create(HttpMethod.PUT, URI.create("/test")).build(); StepVerifier.create(filter.filter(putRequest, exchange)).expectError(IllegalStateException.class).verify(); assertThat(invocationCount.get()).isEqualTo(1); invocationCount.set(0L); ClientRequest postRequest = ClientRequest.create(HttpMethod.POST, URI.create("/test")).build(); StepVerifier.create(filter.filter(postRequest, exchange)).expectError(IllegalStateException.class).verify(); assertThat(invocationCount.get()).isEqualTo(1); invocationCount.set(0L); ClientRequest deleteRequest = ClientRequest.create(HttpMethod.DELETE, URI.create("/test")).build(); StepVerifier.create(filter.filter(deleteRequest, exchange)).expectError(IllegalStateException.class).verify(); assertThat(invocationCount.get()).isEqualTo(1); }
Example #29
Source File: InstanceExchangeFilterFunctions.java From Moss with Apache License 2.0 | 5 votes |
public static ExchangeFilterFunction addHeaders(HttpHeadersProvider httpHeadersProvider) { return toExchangeFilterFunction((instance, request, next) -> { ClientRequest newRequest = ClientRequest.from(request) .headers(headers -> headers.addAll(httpHeadersProvider.getHeaders( instance))) .build(); return next.exchange(newRequest); }); }
Example #30
Source File: InstanceExchangeFilterFunctions.java From Moss with Apache License 2.0 | 5 votes |
public static ExchangeFilterFunction retry(int defaultRetries, Map<String, Integer> retriesPerEndpoint) { return (request, next) -> { int retries = 0; if (!request.method().equals(HttpMethod.DELETE) && !request.method().equals(HttpMethod.PATCH) && !request.method().equals(HttpMethod.POST) && !request.method().equals(HttpMethod.PUT)) { retries = request.attribute(ATTRIBUTE_ENDPOINT).map(retriesPerEndpoint::get).orElse(defaultRetries); } return next.exchange(request).retry(retries); }; }