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

The following examples show how to use org.springframework.web.reactive.function.client.WebClient. 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
private WebClient.Builder of(String serviceUrl) {
	String url = serviceUrl;
	WebClient.Builder builder = WebClient.builder();
	try {
		URI serviceURI = new URI(serviceUrl);
		if (serviceURI.getUserInfo() != null) {
			String[] credentials = serviceURI.getUserInfo().split(":");
			if (credentials.length == 2) {
				builder.filter(ExchangeFilterFunctions
						.basicAuthentication(credentials[0], credentials[1]));
				url = serviceUrl.replace(credentials[0] + ":" + credentials[1] + "@",
						"");
			}
		}
	}
	catch (URISyntaxException ignore) {
	}
	return builder.baseUrl(url);
}
 
Example 2
Source Project: tutorials   Source File: SpringWebFluxUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenReactiveClient_whenRequested_shouldReturnResponse() throws Exception {
    
    HttpClient httpClient = new HttpClient();
    httpClient.start();

    ClientHttpConnector clientConnector = new JettyClientHttpConnector(httpClient);
    WebClient client = WebClient.builder()
        .clientConnector(clientConnector)
        .build();
    String responseContent = client.post()
        .uri(uri())
        .contentType(MediaType.TEXT_PLAIN)
        .body(BodyInserters.fromPublisher(Mono.just(CONTENT), String.class))
        .retrieve()
        .bodyToMono(String.class)
        .block();
    Assert.assertNotNull(responseContent);
    Assert.assertEquals(CONTENT, responseContent);
}
 
Example 3
@Test
void should_add_filter_only_once_to_web_client_via_builder() {
	TraceWebClientBeanPostProcessor processor = new TraceWebClientBeanPostProcessor(
			this.springContext);
	WebClient.Builder builder = WebClient.builder();

	builder = (WebClient.Builder) processor.postProcessAfterInitialization(builder,
			"foo");
	builder = (WebClient.Builder) processor.postProcessAfterInitialization(builder,
			"foo");

	builder.build().mutate().filters(filters -> {
		BDDAssertions.then(filters).hasSize(1);
		BDDAssertions.then(filters.get(0))
				.isInstanceOf(TraceExchangeFilterFunction.class);
	});
}
 
Example 4
@Test
public void testHello() {
       Mono<String> userName =
   		WebClient.create("http://localhost:8080/")
   		         .get()
	             .uri("hello/caterpillar")
	             .accept(MediaType.APPLICATION_JSON)
	             .exchange()
	             .flatMap(response -> response.bodyToMono(User.class))
	             .map(User::getName);
       
       StepVerifier.create(userName)
                   .expectNext("caterpillar")
                   .expectComplete()
                   .verify();
}
 
Example 5
Source Project: training   Source File: ReservationClientApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> routes(WebClient client,
                                      Source src) {
	return route(GET("/reservations/names"), req -> {

		Flux<String> names = client
				.get()
				.uri("http://reservation-service/reservations")
				.retrieve()
				.bodyToFlux(Reservation.class)
				.map(Reservation::getReservationName);

		Publisher<String> fallback = HystrixCommands
				.from(names)
				.commandName("reservation-names")
				.fallback(Flux.just("EEK!"))
				.eager()
				.build();

		return ServerResponse.ok().body(fallback, String.class);
	})
			.andRoute(POST("/reservations"), req -> {
						Flux<Boolean> sendResult = req.bodyToFlux(Reservation.class)
								.map(Reservation::getReservationName)
								.map(r -> MessageBuilder.withPayload(r).build())
								.map(msg -> src.output().send(msg));
						return ServerResponse.ok().body(sendResult, Boolean.class);
					}
			);
}
 
Example 6
Source Project: openapi-generator   Source File: ApiClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add cookies to the request that is being built
 * @param cookies The cookies to add
 * @param requestBuilder The current request
 */
protected void addCookiesToRequest(MultiValueMap<String, String> cookies, WebClient.RequestBodySpec requestBuilder) {
    for (Entry<String, List<String>> entry : cookies.entrySet()) {
        List<String> values = entry.getValue();
        for(String value : values) {
            if (value != null) {
                requestBuilder.cookie(entry.getKey(), value);
            }
        }
    }
}
 
Example 7
Source Project: Spring-5.0-By-Example   Source File: BookingService.java    License: MIT License 5 votes vote down vote up
public BookingService(WebClient webClient, DiscoveryService discoveryService,TokenService tokenService,
    @Value("${bookings.service}") String bookingsService,@Qualifier("bookingsCredentials") Credentials bookingsCredentials) {
  this.webClient = webClient;
  this.discoveryService = discoveryService;
  this.bookingsService = bookingsService;
  this.tokenService = tokenService;
  this.bookingsCredentials = bookingsCredentials;
}
 
Example 8
@Autowired
public ProductCompositeIntegration(
    WebClient.Builder webClientBuilder,
    ObjectMapper mapper,
    MessageSources messageSources
) {
    this.webClientBuilder = webClientBuilder;
    this.mapper = mapper;
    this.messageSources = messageSources;
}
 
Example 9
Source Project: tutorials   Source File: FilteredWebClientUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testLoggingFilter() throws IOException {
    stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200)
        .withBody("done")));

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos);) {
        WebClient webClient = WebClient.builder()
            .filter(loggingFilter(ps))
            .build();
        String actual = sendGetRequest(webClient);

        assertThat(actual).isEqualTo("done");
        assertThat(baos.toString()).isEqualTo("Sending request GET " + getUrl());
    }
}
 
Example 10
Source Project: tutorials   Source File: AppSyncClientHelper.java    License: MIT License 5 votes vote down vote up
public static WebClient.ResponseSpec getResponseBodySpec(Map<String, Object> requestBody) {
    return WebClient
            .builder()
            .baseUrl(apiUrl)
            .defaultHeader(API_KEY_HEADER, apiKey)
            .defaultHeader("Content-Type", "application/json")
            .build()
            .method(HttpMethod.POST)
            .uri("/graphql")
            .body(BodyInserters.fromValue(requestBody))
            .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
            .acceptCharset(StandardCharsets.UTF_8)
            .retrieve();
}
 
Example 11
public HealthCheckServiceInstanceListSupplier(ServiceInstanceListSupplier delegate,
		LoadBalancerProperties.HealthCheck healthCheck, WebClient webClient) {
	super(delegate);
	this.healthCheck = healthCheck;
	defaultHealthCheckPath = healthCheck.getPath().getOrDefault("default",
			"/actuator/health");
	this.webClient = webClient;
	aliveInstancesReplay = Flux.defer(delegate)
			.delaySubscription(healthCheck.getInitialDelay())
			.switchMap(serviceInstances -> healthCheckFlux(serviceInstances).map(
					alive -> Collections.unmodifiableList(new ArrayList<>(alive))))
			.replay(1).refCount(1);
}
 
Example 12
Source Project: spring-vault   Source File: ReactiveVaultTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <V, T extends Publisher<V>> T doWithVault(Function<WebClient, ? extends T> clientCallback)
		throws VaultException, WebClientException {

	Assert.notNull(clientCallback, "Client callback must not be null");

	try {
		return (T) clientCallback.apply(this.statelessClient);
	}
	catch (HttpStatusCodeException e) {
		throw VaultResponses.buildException(e);
	}
}
 
Example 13
Source Project: spring-5-examples   Source File: GithubRoutesConfig.java    License: MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> githubRoutes(final GithubProperties props,
                                            final WebClient githubWebClient) {
  return

      route(GET("/github/props/manual"),
            request -> ok().body(Mono.just(
                singletonMap("github",
                             singletonMap("token", props.getToken()))),
                                 Map.class))

          .andRoute(GET("/github/props/**"),
                    request -> ok().body(Mono.just(props), GithubProperties.class))

          .andRoute(GET("/github/search/users/{username}"), // ?page=1&size=2
                    request -> ok().body(githubWebClient.get()
                                                        .uri(
                                                            "/search/users?q={q}&page={page}&per_page={per_page}",
                                                            HashMap.of(
                                                                "q", request.pathVariable("username"),
                                                                "page", request.queryParam("page").orElse("0"),
                                                                "per_page", request.queryParam("size").orElse("3")
                                                            ).toJavaMap()
                                                        )
                                                        .exchange()
                                                        .subscribeOn(Schedulers.elastic())
                                                        .flatMapMany(response -> response.bodyToFlux(Map.class)),
                                         Map.class))

          .andRoute(GET("/**"),
                    request -> ok().body(Mono.just(singletonMap("result", "TODO")),
                                         Map.class))
      ;
}
 
Example 14
Source Project: oauth2-protocol-patterns   Source File: WebClientConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
	ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
			new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
	return WebClient.builder()
			.apply(oauth2Client.oauth2Configuration())
			.build();
}
 
Example 15
Source Project: spring-vault   Source File: PrepareVault.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link PrepareVault} object.
 * @param webClient must not be {@literal null}.
 * @param restTemplate must not be {@literal null}.
 * @param vaultOperations must not be {@literal null}.
 */
public PrepareVault(WebClient webClient, RestTemplate restTemplate, VaultOperations vaultOperations) {

	this.webClient = webClient;
	this.restTemplate = restTemplate;
	this.vaultOperations = vaultOperations;
	this.adminOperations = vaultOperations.opsForSys();
}
 
Example 16
Source Project: spring-security-samples   Source File: SecurityConfig.java    License: MIT License 5 votes vote down vote up
@Bean
WebClient tokenAugmentingWebClient(final ReactiveClientRegistrationRepository clientRegistrationRepository,
								   final ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
	return WebClient.builder()
		.filter(new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository))
		.build();
}
 
Example 17
Source Project: coditori   Source File: CustomerControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test2_add_customer_done() {
    WebClient webClient = WebClient.create("http://localhost:" + port);
    Customer customer = webClient.post().uri("/customers")
            .contentType(MediaType.APPLICATION_JSON)
            .body(BodyInserters.fromObject(newCustomer))
            .retrieve()
            .bodyToMono(Customer.class)
            .block();

    id = customer.getId();
    System.out.println("id " + id);
    assertThat(customer.getName(), is(newCustomer.getName()));
}
 
Example 18
Source Project: spring-vault   Source File: ReactiveVaultTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link ReactiveVaultTemplate} with a {@link VaultEndpointProvider} and
 * {@link ClientHttpConnector}. This constructor does not use a
 * {@link VaultTokenSupplier}. It is intended for usage with Vault Agent to inherit
 * Vault Agent's authentication without using the {@link VaultHttpHeaders#VAULT_TOKEN
 * authentication token header}.
 * @param endpointProvider must not be {@literal null}.
 * @param connector must not be {@literal null}.
 * @since 2.2.1
 */
public ReactiveVaultTemplate(VaultEndpointProvider endpointProvider, ClientHttpConnector connector) {

	Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null");
	Assert.notNull(connector, "ClientHttpConnector must not be null");

	WebClient webClient = doCreateWebClient(endpointProvider, connector);

	this.vaultTokenSupplier = NoTokenSupplier.INSTANCE;
	this.statelessClient = webClient;
	this.sessionClient = webClient;
}
 
Example 19
@Test
public void testSample() throws UnsupportedEncodingException {
	String messagePostingUrl = UriComponentsBuilder.newInstance()
		.scheme("http")
		.host("localhost")
		.port(this.port)
		.path("/postMessage")
		.toUriString();

	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	map.add("message", "reactive test msg");
	map.add("count", "2");

	HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

	testRestTemplate.postForObject(messagePostingUrl, request, String.class);

	List<String> streamedMessages = WebClient.create("http://localhost:" + this.port).get()
		.uri("/getmessages")
		.accept(MediaType.TEXT_EVENT_STREAM)
		.retrieve()
		.bodyToFlux(String.class)
		.limitRequest(2)
		.collectList().block(Duration.ofSeconds(10));

	assertThat(streamedMessages).containsExactlyInAnyOrder("reactive test msg 0", "reactive test msg 1");
}
 
Example 20
Source Project: tutorials   Source File: FilteredWebClientUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenUrlModifyingFilter_thenPathModified() {
    stubFor(get(urlPathEqualTo(PATH + "/1.0")).willReturn(aResponse().withStatus(200)
        .withBody("done")));

    WebClient webClient = WebClient.builder()
        .filter(urlModifyingFilter("1.0"))
        .build();
    String actual = sendGetRequest(webClient);

    assertThat(actual).isEqualTo("done");
    verify(getRequestedFor(urlPathEqualTo(PATH + "/1.0")));
}
 
Example 21
@Test
void shouldSelectKey() {

	WebClient webClient = TestWebClientFactory.create(
			prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "1")));

	AuthenticationStepsOperator operator = new AuthenticationStepsOperator(
			ClientCertificateAuthentication.createAuthenticationSteps(), webClient);

	operator.getVaultToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();
}
 
Example 22
Source Project: spring-credhub   Source File: ReactiveCredHubTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Allow interaction with the configured {@link WebClient} not provided by other
 * methods.
 * @param callback wrapper for the callback method
 * @param <T> the credential implementation type
 * @return the return value from the callback method
 */
@Override
public <V, T extends Publisher<V>> T doWithWebClient(Function<WebClient, ? extends T> callback) {
	Assert.notNull(callback, "callback must not be null");

	try {
		return callback.apply(this.webClient);
	}
	catch (HttpStatusCodeException ex) {
		throw new CredHubException(ex);
	}
}
 
Example 23
@Autowired
public ProductCompositeIntegration(
    WebClient.Builder webClientBuilder,
    ObjectMapper mapper,
    MessageSources messageSources,
    @Value("${app.product-service.timeoutSec}") int productServiceTimeoutSec

) {
    this.webClientBuilder = webClientBuilder;
    this.mapper = mapper;
    this.messageSources = messageSources;
    this.productServiceTimeoutSec = productServiceTimeoutSec;
}
 
Example 24
@Test
public void nonStandardHeadersInResponse() {
	URI uri = UriComponentsBuilder.fromUriString(this.baseUri + "/get-image")
			.build(true).toUri();

	String contentType = WebClient.builder().baseUrl(baseUri).build().get().uri(uri)
			.exchange().map(clientResponse -> clientResponse.headers().asHttpHeaders()
					.getFirst(HttpHeaders.CONTENT_TYPE))
			.block();

	assertThat(contentType).isEqualTo(CONTENT_TYPE_IMAGE);
}
 
Example 25
Source Project: spring-5-examples   Source File: ReactiveBackendWebClientConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public WebClient webClient(final ReactiveBackendConfig backend) {

  return WebClient.builder()
                  .baseUrl(backend.getBaseUrl())
                  .filter(ExchangeFilterFunctions.basicAuthentication(backend.getCredentials().getUsername(),
                                                                      backend.getCredentials().getPassword()))
                  .build();
}
 
Example 26
Source Project: Spring-5.0-By-Example   Source File: BookingService.java    License: MIT License 5 votes vote down vote up
public BookingService(WebClient webClient, DiscoveryService discoveryService,
    @Value("${bookings.service}") String bookingsService,
    TokenService tokenService,
    @Qualifier("bookingsCredentials") Credentials credentials) {
  this.webClient = webClient;
  this.discoveryService = discoveryService;
  this.bookingsService = bookingsService;
  this.tokenService = tokenService;
  this.credentials = credentials;
}
 
Example 27
Source Project: Spring-5.0-By-Example   Source File: TokenService.java    License: MIT License 5 votes vote down vote up
public TokenService(WebClient webClient,
    @Value("${auth.service}") String authService,
    @Value("${auth.path}") String authServiceApiPath,
    DiscoveryService discoveryService) {
  this.webClient = webClient;
  this.authService = authService;
  this.authServiceApiPath = authServiceApiPath;
  this.discoveryService = discoveryService;
}
 
Example 28
Source Project: spring-cloud-function   Source File: SupplierExporter.java    License: Apache License 2.0 5 votes vote down vote up
SupplierExporter(RequestBuilder requestBuilder,
		DestinationResolver destinationResolver, FunctionCatalog catalog,
		WebClient client, ExporterProperties exporterProperties) {
	this.requestBuilder = requestBuilder;
	this.destinationResolver = destinationResolver;
	this.catalog = catalog;
	this.client = client;
	this.debug = exporterProperties.isDebug();
	this.autoStartup = exporterProperties.isAutoStartup();
	this.supplier = exporterProperties.getSink().getName();
	this.contentType = exporterProperties.getSink().getContentType();
}
 
Example 29
@Test
void correctResponseReturnedForExistingHostAndInstancePresent() {
	ClientResponse clientResponse = WebClient.builder().baseUrl("http://testservice")
			.filter(this.loadBalancerFunction).build().get().uri("/hello").exchange()
			.block();
	then(clientResponse.statusCode()).isEqualTo(HttpStatus.OK);
	then(clientResponse.bodyToMono(String.class).block()).isEqualTo("Hello World");
}
 
Example 30
@Autowired
public HealthCheckConfiguration(
    WebClient.Builder webClientBuilder,
    HealthAggregator healthAggregator
) {
    this.webClientBuilder = webClientBuilder;
    this.healthAggregator = healthAggregator;
}