Search in sources :

Example 1 with ExchangeFunction

use of org.springframework.web.reactive.function.client.ExchangeFunction in project spring-framework by spring-projects.

the class WebTestClientConnectorTests method captureAndClaim.

@Test
@SuppressWarnings("deprecation")
public void captureAndClaim() throws Exception {
    ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, "/test");
    ClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
    ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));
    ClientRequest clientRequest = ClientRequest.method(HttpMethod.GET, URI.create("/test")).header(WiretapConnector.REQUEST_ID_HEADER_NAME, "1").build();
    WiretapConnector wiretapConnector = new WiretapConnector(connector);
    ExchangeFunction function = ExchangeFunctions.create(wiretapConnector);
    function.exchange(clientRequest).blockMillis(0);
    ExchangeResult actual = wiretapConnector.claimRequest("1");
    assertNotNull(actual);
    assertEquals(HttpMethod.GET, actual.getMethod());
    assertEquals("/test", actual.getUrl().toString());
}
Also used : MockClientHttpResponse(org.springframework.mock.http.client.reactive.MockClientHttpResponse) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) Assert.assertNotNull(org.junit.Assert.assertNotNull) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) ClientHttpResponse(org.springframework.http.client.reactive.ClientHttpResponse) HttpStatus(org.springframework.http.HttpStatus) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) ExchangeFunctions(org.springframework.web.reactive.function.client.ExchangeFunctions) ClientHttpRequest(org.springframework.http.client.reactive.ClientHttpRequest) URI(java.net.URI) Assert.assertEquals(org.junit.Assert.assertEquals) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) ClientHttpRequest(org.springframework.http.client.reactive.ClientHttpRequest) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) MockClientHttpResponse(org.springframework.mock.http.client.reactive.MockClientHttpResponse) ClientHttpResponse(org.springframework.http.client.reactive.ClientHttpResponse) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) MockClientHttpResponse(org.springframework.mock.http.client.reactive.MockClientHttpResponse) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) Test(org.junit.Test)

Example 2 with ExchangeFunction

use of org.springframework.web.reactive.function.client.ExchangeFunction in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenUnauthorizedWithWebClientExceptionThenInvokeFailureHandler.

@Test
public void filterWhenUnauthorizedWithWebClientExceptionThenInvokeFailureHandler() {
    this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
    PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
    given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())).willReturn(publisherProbe.mono());
    OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken);
    // @formatter:off
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).build();
    // @formatter:on
    WebClientResponseException exception = WebClientResponseException.create(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
    ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
    // @formatter:off
    assertThatExceptionOfType(WebClientResponseException.class).isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).subscriberContext(serverWebExchange()).block()).isEqualTo(exception);
    // @formatter:on
    assertThat(publisherProbe.wasSubscribed()).isTrue();
    verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture());
    // @formatter:off
    assertThat(this.authorizationExceptionCaptor.getValue()).isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
        assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
        assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token");
        assertThat(ex).hasCause(exception);
        assertThat(ex).hasMessageContaining("[invalid_token]");
    });
    // @formatter:on
    assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
    assertThat(this.attributesCaptor.getValue()).containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
Also used : CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) BeforeEach(org.junit.jupiter.api.BeforeEach) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BodyInserter(org.springframework.web.reactive.function.BodyInserter) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) ReactiveSecurityContextHolder(org.springframework.security.core.context.ReactiveSecurityContextHolder) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) Map(java.util.Map) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) ReactiveOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizationFailureHandler) URI(java.net.URI) Jwt(org.springframework.security.oauth2.jwt.Jwt) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpHeaders(org.springframework.http.HttpHeaders) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) JwtBearerReactiveOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.JwtBearerReactiveOAuth2AuthorizedClientProvider) Context(reactor.util.context.Context) MediaType(org.springframework.http.MediaType) ReactiveOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest) Instant(java.time.Instant) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) PublisherProbe(reactor.test.publisher.PublisherProbe) Test(org.junit.jupiter.api.Test) List(java.util.List) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) Optional(java.util.Optional) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Authentication(org.springframework.security.core.Authentication) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) MultipartHttpMessageWriter(org.springframework.http.codec.multipart.MultipartHttpMessageWriter) Mock(org.mockito.Mock) ByteBufferEncoder(org.springframework.core.codec.ByteBufferEncoder) ReactiveOAuth2AuthorizedClientProviderBuilder(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HashMap(java.util.HashMap) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) Mockito.spy(org.mockito.Mockito.spy) Captor(org.mockito.Captor) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) DefaultReactiveOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager) ArgumentCaptor(org.mockito.ArgumentCaptor) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) UnAuthenticatedServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) HttpMethod(org.springframework.http.HttpMethod) WebClientReactiveClientCredentialsTokenResponseClient(org.springframework.security.oauth2.client.endpoint.WebClientReactiveClientCredentialsTokenResponseClient) Mono(reactor.core.publisher.Mono) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Assertions.entry(org.assertj.core.api.Assertions.entry) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) StringUtils(org.springframework.util.StringUtils) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) Test(org.junit.jupiter.api.Test)

Example 3 with ExchangeFunction

use of org.springframework.web.reactive.function.client.ExchangeFunction in project spring-boot by spring-projects.

the class MetricsWebClientFilterFunctionTests method filterWhenIoExceptionThrownShouldRecordTimer.

@Test
void filterWhenIoExceptionThrownShouldRecordTimer() {
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build();
    ExchangeFunction errorExchange = (r) -> Mono.error(new IOException());
    this.filterFunction.filter(request, errorExchange).onErrorResume(IOException.class, (t) -> Mono.empty()).block(Duration.ofSeconds(5));
    assertThat(this.registry.get("http.client.requests").tags("method", "GET", "uri", "/projects/spring-boot", "status", "IO_ERROR").timer().count()).isEqualTo(1);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) SimpleMeterRegistry(io.micrometer.core.instrument.simple.SimpleMeterRegistry) StepVerifier(reactor.test.StepVerifier) AutoTimer(org.springframework.boot.actuate.metrics.AutoTimer) MockClock(io.micrometer.core.instrument.MockClock) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) WebClient(org.springframework.web.reactive.function.client.WebClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Timer(io.micrometer.core.instrument.Timer) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) URI(java.net.URI) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) MeterNotFoundException(io.micrometer.core.instrument.search.MeterNotFoundException) SimpleConfig(io.micrometer.core.instrument.simple.SimpleConfig) HttpMethod(org.springframework.http.HttpMethod) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) HttpStatus(org.springframework.http.HttpStatus) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) Mockito.mock(org.mockito.Mockito.mock) IOException(java.io.IOException) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) Test(org.junit.jupiter.api.Test)

Example 4 with ExchangeFunction

use of org.springframework.web.reactive.function.client.ExchangeFunction in project spring-boot by spring-projects.

the class MetricsWebClientFilterFunctionTests method filterWhenExceptionThrownShouldRecordTimer.

@Test
void filterWhenExceptionThrownShouldRecordTimer() {
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build();
    ExchangeFunction exchange = (r) -> Mono.error(new IllegalArgumentException());
    this.filterFunction.filter(request, exchange).onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()).block(Duration.ofSeconds(5));
    assertThat(this.registry.get("http.client.requests").tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer().count()).isEqualTo(1);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) SimpleMeterRegistry(io.micrometer.core.instrument.simple.SimpleMeterRegistry) StepVerifier(reactor.test.StepVerifier) AutoTimer(org.springframework.boot.actuate.metrics.AutoTimer) MockClock(io.micrometer.core.instrument.MockClock) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) WebClient(org.springframework.web.reactive.function.client.WebClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Timer(io.micrometer.core.instrument.Timer) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) URI(java.net.URI) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) MeterNotFoundException(io.micrometer.core.instrument.search.MeterNotFoundException) SimpleConfig(io.micrometer.core.instrument.simple.SimpleConfig) HttpMethod(org.springframework.http.HttpMethod) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) HttpStatus(org.springframework.http.HttpStatus) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) Mockito.mock(org.mockito.Mockito.mock) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) Test(org.junit.jupiter.api.Test)

Example 5 with ExchangeFunction

use of org.springframework.web.reactive.function.client.ExchangeFunction in project spring-framework by spring-projects.

the class DefaultWebTestClientBuilder method build.

@Override
public WebTestClient build() {
    ClientHttpConnector connectorToUse = this.connector;
    if (connectorToUse == null) {
        if (this.httpHandlerBuilder != null) {
            connectorToUse = new HttpHandlerConnector(this.httpHandlerBuilder.build());
        }
    }
    if (connectorToUse == null) {
        connectorToUse = initConnector();
    }
    Function<ClientHttpConnector, ExchangeFunction> exchangeFactory = connector -> {
        ExchangeFunction exchange = ExchangeFunctions.create(connector, initExchangeStrategies());
        if (CollectionUtils.isEmpty(this.filters)) {
            return exchange;
        }
        return this.filters.stream().reduce(ExchangeFilterFunction::andThen).map(filter -> filter.apply(exchange)).orElse(exchange);
    };
    return new DefaultWebTestClient(connectorToUse, exchangeFactory, initUriBuilderFactory(), this.defaultHeaders != null ? HttpHeaders.readOnlyHttpHeaders(this.defaultHeaders) : null, this.defaultCookies != null ? CollectionUtils.unmodifiableMultiValueMap(this.defaultCookies) : null, this.entityResultConsumer, this.responseTimeout, new DefaultWebTestClientBuilder(this));
}
Also used : Arrays(java.util.Arrays) WebHttpHandlerBuilder(org.springframework.web.server.adapter.WebHttpHandlerBuilder) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Duration(java.time.Duration) DefaultUriBuilderFactory(org.springframework.web.util.DefaultUriBuilderFactory) Nullable(org.springframework.lang.Nullable) HttpComponentsClientHttpConnector(org.springframework.http.client.reactive.HttpComponentsClientHttpConnector) ReactorClientHttpConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) ClassUtils(org.springframework.util.ClassUtils) JettyClientHttpConnector(org.springframework.http.client.reactive.JettyClientHttpConnector) HttpHeaders(org.springframework.http.HttpHeaders) MultiValueMap(org.springframework.util.MultiValueMap) Consumer(java.util.function.Consumer) ClientCodecConfigurer(org.springframework.http.codec.ClientCodecConfigurer) List(java.util.List) ExchangeFilterFunction(org.springframework.web.reactive.function.client.ExchangeFilterFunction) CollectionUtils(org.springframework.util.CollectionUtils) ExchangeFunctions(org.springframework.web.reactive.function.client.ExchangeFunctions) ExchangeStrategies(org.springframework.web.reactive.function.client.ExchangeStrategies) UriBuilderFactory(org.springframework.web.util.UriBuilderFactory) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) Assert(org.springframework.util.Assert) HttpComponentsClientHttpConnector(org.springframework.http.client.reactive.HttpComponentsClientHttpConnector) ReactorClientHttpConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector) JettyClientHttpConnector(org.springframework.http.client.reactive.JettyClientHttpConnector) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction)

Aggregations

ExchangeFunction (org.springframework.web.reactive.function.client.ExchangeFunction)12 ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)11 Mono (reactor.core.publisher.Mono)11 URI (java.net.URI)10 Duration (java.time.Duration)10 HttpMethod (org.springframework.http.HttpMethod)10 HttpStatus (org.springframework.http.HttpStatus)10 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 Test (org.junit.jupiter.api.Test)9 ClientResponse (org.springframework.web.reactive.function.client.ClientResponse)9 BeforeEach (org.junit.jupiter.api.BeforeEach)8 BDDMockito.given (org.mockito.BDDMockito.given)8 Mockito.mock (org.mockito.Mockito.mock)8 List (java.util.List)7 MockClientHttpRequest (org.springframework.mock.http.client.reactive.MockClientHttpRequest)7 ArrayList (java.util.ArrayList)6 StandardCharsets (java.nio.charset.StandardCharsets)5 Instant (java.time.Instant)5 Collections (java.util.Collections)5 HashMap (java.util.HashMap)5