Merge "Stepping to springboot 3"
[nonrtric.git] / pmlog / src / main / java / org / oran / pmlog / clients / AsyncRestClient.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2022 Nordix Foundation
6  * %%
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.oran.pmlog.clients;
22
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;
27
28 import java.lang.invoke.MethodHandles;
29 import java.util.concurrent.atomic.AtomicInteger;
30
31 import org.oran.pmlog.configuration.WebClientConfig.HttpProxyConfig;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.http.MediaType;
35 import org.springframework.http.ResponseEntity;
36 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
37 import org.springframework.lang.Nullable;
38 import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
39 import org.springframework.web.reactive.function.client.ExchangeStrategies;
40 import org.springframework.web.reactive.function.client.WebClient;
41 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
42 import org.springframework.web.reactive.function.client.WebClientResponseException;
43
44 import reactor.core.publisher.Mono;
45 import reactor.netty.http.client.HttpClient;
46 import reactor.netty.transport.ProxyProvider;
47
48 /**
49  * Generic reactive REST client.
50  */
51 public class AsyncRestClient {
52
53     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
54     private WebClient webClient = null;
55     private final String baseUrl;
56     private static final AtomicInteger sequenceNumber = new AtomicInteger();
57     private final SslContext sslContext;
58     private final HttpProxyConfig httpProxyConfig;
59     private final SecurityContext securityContext;
60
61     public AsyncRestClient(String baseUrl, @Nullable SslContext sslContext, @Nullable HttpProxyConfig httpProxyConfig,
62             SecurityContext securityContext) {
63         this.baseUrl = baseUrl;
64         this.sslContext = sslContext;
65         this.httpProxyConfig = httpProxyConfig;
66         this.securityContext = securityContext;
67     }
68
69     @SuppressWarnings("java:S4449") // contentType, is not @Nullable
70     public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body,
71             @Nullable MediaType mediaType) {
72         Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
73
74         RequestHeadersSpec<?> request = getWebClient() //
75                 .post() //
76                 .uri(uri) //
77                 .contentType(mediaType) //
78                 .body(bodyProducer, String.class);
79         return retrieve(request);
80     }
81
82     public Mono<String> post(String uri, @Nullable String body, @Nullable MediaType mediaType) {
83         return postForEntity(uri, body, mediaType) //
84                 .map(this::toBody);
85     }
86
87     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
88         RequestHeadersSpec<?> request = getWebClient() //
89                 .put() //
90                 .uri(uri) //
91                 .contentType(MediaType.APPLICATION_JSON) //
92                 .bodyValue(body);
93         return retrieve(request);
94     }
95
96     public Mono<String> put(String uri, String body) {
97         return putForEntity(uri, body) //
98                 .map(this::toBody);
99     }
100
101     public Mono<ResponseEntity<String>> getForEntity(String uri) {
102         RequestHeadersSpec<?> request = getWebClient().get().uri(uri);
103         return retrieve(request);
104     }
105
106     public Mono<String> get(String uri) {
107         return getForEntity(uri) //
108                 .map(this::toBody);
109     }
110
111     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
112         RequestHeadersSpec<?> request = getWebClient().delete().uri(uri);
113         return retrieve(request);
114     }
115
116     public Mono<String> delete(String uri) {
117         return deleteForEntity(uri) //
118                 .map(this::toBody);
119     }
120
121     public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
122         Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
123
124         RequestHeadersSpec<?> request = getWebClient() //
125                 .post() //
126                 .uri(uri) //
127                 .contentType(MediaType.APPLICATION_JSON) //
128                 .body(bodyProducer, String.class);
129         return retrieve(request);
130     }
131
132     public Mono<String> post(String uri, @Nullable String body) {
133         return postForEntity(uri, body) //
134                 .map(this::toBody);
135     }
136
137     private Mono<ResponseEntity<String>> retrieve(RequestHeadersSpec<?> request) {
138         if (securityContext.isConfigured()) {
139             request.headers(h -> h.setBearerAuth(securityContext.getBearerAuthToken()));
140         }
141         return request.retrieve() //
142                 .toEntity(String.class) //
143                 .doOnError(this::onError); //
144     }
145
146     private void onError(Throwable t) {
147         if (t instanceof WebClientResponseException) {
148             WebClientResponseException e = (WebClientResponseException) t;
149             logger.debug("Response error: {}", e.getResponseBodyAsString());
150         }
151     }
152
153     private static Object createTraceTag() {
154         return sequenceNumber.incrementAndGet();
155     }
156
157     private String toBody(ResponseEntity<String> entity) {
158         if (entity.getBody() == null) {
159             return "";
160         } else {
161             return entity.getBody();
162         }
163     }
164
165     private boolean isHttpProxyConfigured() {
166         return httpProxyConfig != null && httpProxyConfig.getHttpProxyPort() > 0
167                 && !httpProxyConfig.getHttpProxyHost().isEmpty();
168     }
169
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));
176                 });
177
178         if (this.sslContext != null) {
179             httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
180         }
181
182         if (isHttpProxyConfigured()) {
183             httpClient = httpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP)
184                     .host(httpProxyConfig.getHttpProxyHost()).port(httpProxyConfig.getHttpProxyPort()));
185         }
186         return httpClient;
187     }
188
189     public WebClient buildWebClient(String baseUrl) {
190         Object traceTag = createTraceTag();
191
192         final HttpClient httpClient = buildHttpClient();
193         ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
194                 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
195                 .build();
196
197         ExchangeFilterFunction reqLogger = ExchangeFilterFunction.ofRequestProcessor(req -> {
198             logger.debug("{} {} uri = '{}''", traceTag, req.method(), req.url());
199             return Mono.just(req);
200         });
201
202         ExchangeFilterFunction respLogger = ExchangeFilterFunction.ofResponseProcessor(resp -> {
203             logger.debug("{} resp: {}", traceTag, resp.statusCode());
204             return Mono.just(resp);
205         });
206
207         return WebClient.builder() //
208                 .clientConnector(new ReactorClientHttpConnector(httpClient)) //
209                 .baseUrl(baseUrl) //
210                 .exchangeStrategies(exchangeStrategies) //
211                 .filter(reqLogger) //
212                 .filter(respLogger) //
213                 .build();
214     }
215
216     private WebClient getWebClient() {
217         if (this.webClient == null) {
218             this.webClient = buildWebClient(baseUrl);
219         }
220         return this.webClient;
221     }
222 }