Java Code Examples for org.springframework.web.reactive.function.client.ExchangeFilterFunction

The following examples show how to use org.springframework.web.reactive.function.client.ExchangeFilterFunction. These examples are extracted from open source projects. 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 Project: Moss   Source File: InstanceExchangeFilterFunctions.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: Moss   Source File: InstanceExchangeFilterFunctionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: Moss   Source File: InstanceExchangeFilterFunctionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
Source Project: Moss   Source File: InstanceExchangeFilterFunctionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: Moss   Source File: InstanceExchangeFilterFunctionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
Source Project: Moss   Source File: InstanceExchangeFilterFunctionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: tutorials   Source File: LogFilters.java    License: MIT License 6 votes vote down vote up
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 8
Source Project: tutorials   Source File: LogFilters.java    License: MIT License 6 votes vote down vote up
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 9
Source Project: influx-proxy   Source File: BackendService.java    License: Apache License 2.0 5 votes vote down vote up
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 10
Source Project: Moss   Source File: InstanceExchangeFilterFunctions.java    License: Apache License 2.0 5 votes vote down vote up
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 11
Source Project: Moss   Source File: InstanceExchangeFilterFunctions.java    License: Apache License 2.0 5 votes vote down vote up
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 12
Source Project: Moss   Source File: InstanceExchangeFilterFunctions.java    License: Apache License 2.0 5 votes vote down vote up
public static ExchangeFilterFunction toExchangeFilterFunction(InstanceExchangeFilterFunction delegate) {
    return (request, next) -> {
        Optional<?> instance = request.attribute(ATTRIBUTE_INSTANCE);
        if (instance.isPresent() && instance.get() instanceof Instance) {
            return delegate.exchange((Instance) instance.get(), request, next);
        }
        return next.exchange(request);
    };
}
 
Example 13
Source Project: Moss   Source File: InstanceExchangeFilterFunctions.java    License: Apache License 2.0 5 votes vote down vote up
public static ExchangeFilterFunction rewriteEndpointUrl() {
    return toExchangeFilterFunction((instance, request, next) -> {
        if (request.url().isAbsolute()) {
            log.trace("Absolute URL '{}' for instance {} not rewritten", request.url(), instance.getId());
            if (request.url().toString().equals(instance.getRegistration().getManagementUrl())) {
                return next.exchange(ClientRequest.from(request)
                                                  .attribute(ATTRIBUTE_ENDPOINT, Endpoint.ACTUATOR_INDEX)
                                                  .build());
            }
            return next.exchange(request);
        }

        UriComponents oldUrl = UriComponentsBuilder.fromUri(request.url()).build();
        if (oldUrl.getPathSegments().isEmpty()) {
            return Mono.error(new ResolveEndpointException("No endpoint specified"));
        }

        String endpointId = oldUrl.getPathSegments().get(0);
        Optional<Endpoint> endpoint = instance.getEndpoints().get(endpointId);

        if (!endpoint.isPresent()) {
            return Mono.error(new ResolveEndpointException("Endpoint '" + endpointId + "' not found"));
        }

        URI newUrl = rewriteUrl(oldUrl, endpoint.get().getUrl());
        log.trace("URL '{}' for Endpoint {} of instance {} rewritten to {}",
            oldUrl,
            endpoint.get().getId(),
            instance.getId(),
            newUrl
        );
        ClientRequest newRequest = ClientRequest.from(request)
                                                .attribute(ATTRIBUTE_ENDPOINT, endpoint.get().getId())
                                                .url(newUrl)
                                                .build();
        return next.exchange(newRequest);
    });
}
 
Example 14
Source Project: Moss   Source File: InstanceExchangeFilterFunctions.java    License: Apache License 2.0 5 votes vote down vote up
public static ExchangeFilterFunction setDefaultAcceptHeader() {
    return (request, next) -> {
        if (request.headers().getAccept().isEmpty()) {
            Boolean isRequestForLogfile = request.attribute(ATTRIBUTE_ENDPOINT)
                                                 .map(Endpoint.LOGFILE::equals)
                                                 .orElse(false);
            List<MediaType> acceptedHeaders = isRequestForLogfile ? DEFAULT_LOGFILE_ACCEPT_MEDIATYPES : DEFAULT_ACCEPT_MEDIATYPES;
            return next.exchange(ClientRequest.from(request)
                                              .headers(headers -> headers.setAccept(acceptedHeaders))
                                              .build());
        }
        return next.exchange(request);
    };
}
 
Example 15
Source Project: Moss   Source File: InstanceExchangeFilterFunctions.java    License: Apache License 2.0 5 votes vote down vote up
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);
    };
}
 
Example 16
Source Project: Moss   Source File: InstanceExchangeFilterFunctionsTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 17
Source Project: training   Source File: ReservationClientApplication.java    License: Apache License 2.0 5 votes vote down vote up
@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 18
Source Project: blog-tutorials   Source File: SimpleWebClientConfiguration.java    License: MIT License 5 votes vote down vote up
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 19
Source Project: blog-tutorials   Source File: SimpleWebClientConfiguration.java    License: MIT License 5 votes vote down vote up
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 20
Source Project: blog-tutorials   Source File: ResponseLoggingCustomizer.java    License: MIT License 5 votes vote down vote up
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 21
Source Project: blog-tutorials   Source File: ResponseLoggingCustomizer.java    License: MIT License 5 votes vote down vote up
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 22
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 23
private Consumer<List<ExchangeFilterFunction>> addTraceExchangeFilterFunctionIfNotPresent() {
	return functions -> {
		if (functions.stream()
				.noneMatch(function -> function instanceof TracingExchangeFilterFunction)) {
			functions.add(new TracingExchangeFilterFunction(tracer, spanDecorators));
		}
	};
}
 
Example 24
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 25
Source Project: spring-vault   Source File: WebClientBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 26
Source Project: spring-vault   Source File: ReactiveVaultTemplate.java    License: Apache License 2.0 5 votes vote down vote up
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 27
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 28
private Consumer<List<ExchangeFilterFunction>> addTraceExchangeFilterFunctionIfNotPresent() {
	return functions -> {
		boolean noneMatch = noneMatchTraceExchangeFunction(functions);
		if (noneMatch) {
			functions.add(new TraceExchangeFilterFunction(this.springContext));
		}
	};
}
 
Example 29
private boolean noneMatchTraceExchangeFunction(
		List<ExchangeFilterFunction> functions) {
	for (ExchangeFilterFunction function : functions) {
		if (function instanceof TraceExchangeFilterFunction) {
			return false;
		}
	}
	return true;
}
 
Example 30
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);
        };
    }