X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=blobdiff_plain;f=policy-agent%2Fsrc%2Fmain%2Fjava%2Forg%2Foransc%2Fpolicyagent%2Fclients%2FAsyncRestClient.java;h=26d5152895a46ba50951d494e51acb0bc638ce6a;hb=51716d5ce50b8e9b776a2f648261e5191ed921b8;hp=2e6df942c4c8bc61460935415c4822bf67b486c4;hpb=f0273617b916cdc8633382291b9986e33cc13fa1;p=nonrtric.git diff --git a/policy-agent/src/main/java/org/oransc/policyagent/clients/AsyncRestClient.java b/policy-agent/src/main/java/org/oransc/policyagent/clients/AsyncRestClient.java index 2e6df942..26d51528 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/clients/AsyncRestClient.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/clients/AsyncRestClient.java @@ -17,47 +17,208 @@ * limitations under the License. * ========================LICENSE_END=================================== */ + package org.oransc.policyagent.clients; -import org.oransc.policyagent.exceptions.AsyncRestClientException; -import org.springframework.http.HttpStatus; +import io.netty.channel.ChannelOption; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.handler.timeout.WriteTimeoutHandler; + +import java.lang.invoke.MethodHandles; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.net.ssl.SSLException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.lang.Nullable; import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec; +import org.springframework.web.reactive.function.client.WebClientResponseException; + import reactor.core.publisher.Mono; +import reactor.netty.http.client.HttpClient; +import reactor.netty.tcp.TcpClient; +/** + * Generic reactive REST client. + */ public class AsyncRestClient { - private final WebClient client; + private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private WebClient webClient = null; + private final String baseUrl; + private static final AtomicInteger sequenceNumber = new AtomicInteger(); public AsyncRestClient(String baseUrl) { - this.client = WebClient.create(baseUrl); + this.baseUrl = baseUrl; + } + + public Mono> postForEntity(String uri, @Nullable String body) { + Object traceTag = createTraceTag(); + logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri); + logger.trace("{} POST body: {}", traceTag, body); + Mono bodyProducer = body != null ? Mono.just(body) : Mono.empty(); + return getWebClient() // + .flatMap(client -> { + RequestHeadersSpec request = client.post() // + .uri(uri) // + .contentType(MediaType.APPLICATION_JSON) // + .body(bodyProducer, String.class); + return retrieve(traceTag, request); + }); + } + + public Mono post(String uri, @Nullable String body) { + return postForEntity(uri, body) // + .flatMap(this::toBody); + } + + public Mono postWithAuthHeader(String uri, String body, String username, String password) { + Object traceTag = createTraceTag(); + logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri); + logger.trace("{} POST body: {}", traceTag, body); + return getWebClient() // + .flatMap(client -> { + RequestHeadersSpec request = client.post() // + .uri(uri) // + .headers(headers -> headers.setBasicAuth(username, password)) // + .contentType(MediaType.APPLICATION_JSON) // + .bodyValue(body); + return retrieve(traceTag, request) // + .flatMap(this::toBody); + }); + } + + public Mono> putForEntity(String uri, String body) { + Object traceTag = createTraceTag(); + logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri); + logger.trace("{} PUT body: {}", traceTag, body); + return getWebClient() // + .flatMap(client -> { + RequestHeadersSpec request = client.put() // + .uri(uri) // + .contentType(MediaType.APPLICATION_JSON) // + .bodyValue(body); + return retrieve(traceTag, request); + }); + } + + public Mono> putForEntity(String uri) { + Object traceTag = createTraceTag(); + logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri); + logger.trace("{} PUT body: ", traceTag); + return getWebClient() // + .flatMap(client -> { + RequestHeadersSpec request = client.put() // + .uri(uri); + return retrieve(traceTag, request); + }); } public Mono put(String uri, String body) { - return client.put() // - .uri(uri) // - .contentType(MediaType.APPLICATION_JSON) // - .syncBody(body) // - .retrieve() // - .onStatus(HttpStatus::isError, - response -> Mono.error(new AsyncRestClientException(response.statusCode().toString()))) // - .bodyToMono(String.class); + return putForEntity(uri, body) // + .flatMap(this::toBody); + } + + public Mono> getForEntity(String uri) { + Object traceTag = createTraceTag(); + logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri); + return getWebClient() // + .flatMap(client -> { + RequestHeadersSpec request = client.get().uri(uri); + return retrieve(traceTag, request); + }); } public Mono get(String uri) { - return client.get() // - .uri(uri) // - .retrieve() // - .onStatus(HttpStatus::isError, - response -> Mono.error(new AsyncRestClientException(response.statusCode().toString()))) // - .bodyToMono(String.class); - } - - public Mono delete(String uri) { - return client.delete() // - .uri(uri) // - .retrieve() // - .onStatus(HttpStatus::isError, - response -> Mono.error(new AsyncRestClientException(response.statusCode().toString()))) // - .bodyToMono(Void.class); + return getForEntity(uri) // + .flatMap(this::toBody); + } + + public Mono> deleteForEntity(String uri) { + Object traceTag = createTraceTag(); + logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri); + return getWebClient() // + .flatMap(client -> { + RequestHeadersSpec request = client.delete().uri(uri); + return retrieve(traceTag, request); + }); + } + + public Mono delete(String uri) { + return deleteForEntity(uri) // + .flatMap(this::toBody); + } + + private Mono> retrieve(Object traceTag, RequestHeadersSpec request) { + return request.retrieve() // + .toEntity(String.class) // + .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody())) + .doOnError(throwable -> onHttpError(traceTag, throwable)); } + + private static Object createTraceTag() { + return sequenceNumber.incrementAndGet(); + } + + private void onHttpError(Object traceTag, Throwable t) { + if (t instanceof WebClientResponseException) { + WebClientResponseException exception = (WebClientResponseException) t; + logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(), + exception.getResponseBodyAsString()); + } else { + logger.debug("{} HTTP error: {}", traceTag, t.getMessage()); + } + } + + private Mono toBody(ResponseEntity entity) { + if (entity.getBody() == null) { + return Mono.just(""); + } else { + return Mono.just(entity.getBody()); + } + } + + private static SslContext createSslContext() throws SSLException { + return SslContextBuilder.forClient() // + .trustManager(InsecureTrustManagerFactory.INSTANCE) // + .build(); + } + + private static WebClient createWebClient(String baseUrl, SslContext sslContext) { + TcpClient tcpClient = TcpClient.create() // + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) // + .secure(c -> c.sslContext(sslContext)) // + .doOnConnected(connection -> { + connection.addHandler(new ReadTimeoutHandler(30)); + connection.addHandler(new WriteTimeoutHandler(30)); + }); + HttpClient httpClient = HttpClient.from(tcpClient); + ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient); + + return WebClient.builder() // + .clientConnector(connector) // + .baseUrl(baseUrl) // + .build(); + } + + private Mono getWebClient() { + if (this.webClient == null) { + try { + SslContext sslContext = createSslContext(); + this.webClient = createWebClient(this.baseUrl, sslContext); + } catch (SSLException e) { + logger.error("Could not create WebClient {}", e.getMessage()); + return Mono.error(e); + } + } + return Mono.just(this.webClient); + } + }