2 * ========================LICENSE_START=================================
5 * Copyright (C) 2023 Nordix Foundation
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
21 package org.oran.pmproducer.clients;
23 import io.netty.channel.ChannelOption;
24 import io.netty.handler.ssl.SslContext;
25 import io.netty.handler.timeout.ReadTimeoutHandler;
26 import io.netty.handler.timeout.WriteTimeoutHandler;
28 import java.lang.invoke.MethodHandles;
29 import java.util.concurrent.atomic.AtomicInteger;
31 import org.oran.pmproducer.configuration.WebClientConfig.HttpProxyConfig;
32 import org.oran.pmproducer.oauth2.SecurityContext;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.http.MediaType;
36 import org.springframework.http.ResponseEntity;
37 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
38 import org.springframework.lang.Nullable;
39 import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
40 import org.springframework.web.reactive.function.client.ExchangeStrategies;
41 import org.springframework.web.reactive.function.client.WebClient;
42 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
43 import org.springframework.web.reactive.function.client.WebClientResponseException;
45 import reactor.core.publisher.Mono;
46 import reactor.netty.http.client.HttpClient;
47 import reactor.netty.transport.ProxyProvider;
50 * Generic reactive REST client.
52 public class AsyncRestClient {
54 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
55 private WebClient webClient = null;
56 private final String baseUrl;
57 private static final AtomicInteger sequenceNumber = new AtomicInteger();
58 private final SslContext sslContext;
59 private final HttpProxyConfig httpProxyConfig;
60 private final SecurityContext securityContext;
62 public AsyncRestClient(String baseUrl, @Nullable SslContext sslContext, @Nullable HttpProxyConfig httpProxyConfig,
63 SecurityContext securityContext) {
64 this.baseUrl = baseUrl;
65 this.sslContext = sslContext;
66 this.httpProxyConfig = httpProxyConfig;
67 this.securityContext = securityContext;
70 @SuppressWarnings("java:S4449") // contentType, is not @Nullable
71 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body,
72 @Nullable MediaType mediaType) {
73 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
75 RequestHeadersSpec<?> request = getWebClient() //
78 .contentType(mediaType) //
79 .body(bodyProducer, String.class);
80 return retrieve(request);
83 public Mono<String> post(String uri, @Nullable String body, @Nullable MediaType mediaType) {
84 return postForEntity(uri, body, mediaType) //
88 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
89 RequestHeadersSpec<?> request = getWebClient() //
92 .contentType(MediaType.APPLICATION_JSON) //
94 return retrieve(request);
97 public Mono<String> put(String uri, String body) {
98 return putForEntity(uri, body) //
102 public Mono<ResponseEntity<String>> getForEntity(String uri) {
103 RequestHeadersSpec<?> request = getWebClient().get().uri(uri);
104 return retrieve(request);
107 public Mono<String> get(String uri) {
108 return getForEntity(uri) //
112 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
113 RequestHeadersSpec<?> request = getWebClient().delete().uri(uri);
114 return retrieve(request);
117 public Mono<String> delete(String uri) {
118 return deleteForEntity(uri) //
122 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
123 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
125 RequestHeadersSpec<?> request = getWebClient() //
128 .contentType(MediaType.APPLICATION_JSON) //
129 .body(bodyProducer, String.class);
130 return retrieve(request);
133 public Mono<String> post(String uri, @Nullable String body) {
134 return postForEntity(uri, body) //
138 private Mono<ResponseEntity<String>> retrieve(RequestHeadersSpec<?> request) {
139 if (securityContext.isConfigured()) {
140 request.headers(h -> h.setBearerAuth(securityContext.getBearerAuthToken()));
142 return request.retrieve() //
143 .toEntity(String.class) //
144 .doOnError(this::onError); //
147 private void onError(Throwable t) {
148 if (t instanceof WebClientResponseException e) {
149 logger.debug("Response error: {}", e.getResponseBodyAsString());
153 private static Object createTraceTag() {
154 return sequenceNumber.incrementAndGet();
157 private String toBody(ResponseEntity<String> entity) {
158 if (entity.getBody() == null) {
161 return entity.getBody();
165 private boolean isHttpProxyConfigured() {
166 return httpProxyConfig != null && httpProxyConfig.getHttpProxyPort() > 0
167 && !httpProxyConfig.getHttpProxyHost().isEmpty();
170 private HttpClient buildHttpClient() {
171 HttpClient httpClient = HttpClient.create() //
172 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
173 .doOnConnected(connection -> {
174 connection.addHandlerLast(new ReadTimeoutHandler(30));
175 connection.addHandlerLast(new WriteTimeoutHandler(30));
178 if (this.sslContext != null) {
179 httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
182 if (isHttpProxyConfigured()) {
183 httpClient = httpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP)
184 .host(httpProxyConfig.getHttpProxyHost()).port(httpProxyConfig.getHttpProxyPort()));
189 public WebClient buildWebClient(String baseUrl) {
190 Object traceTag = createTraceTag();
192 final HttpClient httpClient = buildHttpClient();
193 ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
194 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
197 ExchangeFilterFunction reqLogger = ExchangeFilterFunction.ofRequestProcessor(req -> {
198 logger.debug("{} {} uri = '{}''", traceTag, req.method(), req.url());
199 return Mono.just(req);
202 ExchangeFilterFunction respLogger = ExchangeFilterFunction.ofResponseProcessor(resp -> {
203 logger.debug("{} resp: {}", traceTag, resp.statusCode());
204 return Mono.just(resp);
207 return WebClient.builder() //
208 .clientConnector(new ReactorClientHttpConnector(httpClient)) //
210 .exchangeStrategies(exchangeStrategies) //
211 .filter(reqLogger) //
212 .filter(respLogger) //
216 private WebClient getWebClient() {
217 if (this.webClient == null) {
218 this.webClient = buildWebClient(baseUrl);
220 return this.webClient;