Fix Sonar issues
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / clients / AsyncRestClient.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 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.oransc.enrichment.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.oransc.enrichment.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.ExchangeStrategies;
39 import org.springframework.web.reactive.function.client.WebClient;
40 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
41 import org.springframework.web.reactive.function.client.WebClientResponseException;
42
43 import reactor.core.publisher.Mono;
44 import reactor.netty.http.client.HttpClient;
45 import reactor.netty.transport.ProxyProvider;
46
47 /**
48  * Generic reactive REST client.
49  */
50 public class AsyncRestClient {
51
52     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
53     private WebClient webClient = null;
54     private final String baseUrl;
55     private static final AtomicInteger sequenceNumber = new AtomicInteger();
56     private final SslContext sslContext;
57     private final HttpProxyConfig httpProxyConfig;
58
59     public AsyncRestClient(String baseUrl, @Nullable SslContext sslContext, @Nullable HttpProxyConfig httpProxyConfig) {
60         this.baseUrl = baseUrl;
61         this.sslContext = sslContext;
62         this.httpProxyConfig = httpProxyConfig;
63     }
64
65     public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
66         Object traceTag = createTraceTag();
67         logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
68         logger.trace("{} POST body: {}", traceTag, body);
69         Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
70         return getWebClient() //
71             .flatMap(client -> {
72                 RequestHeadersSpec<?> request = client.post() //
73                     .uri(uri) //
74                     .contentType(MediaType.APPLICATION_JSON) //
75                     .body(bodyProducer, String.class);
76                 return retrieve(traceTag, request);
77             });
78     }
79
80     public Mono<String> post(String uri, @Nullable String body) {
81         return postForEntity(uri, body) //
82             .flatMap(this::toBody);
83     }
84
85     public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
86         Object traceTag = createTraceTag();
87         logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
88         logger.trace("{} POST body: {}", traceTag, body);
89         return getWebClient() //
90             .flatMap(client -> {
91                 RequestHeadersSpec<?> request = client.post() //
92                     .uri(uri) //
93                     .headers(headers -> headers.setBasicAuth(username, password)) //
94                     .contentType(MediaType.APPLICATION_JSON) //
95                     .bodyValue(body);
96                 return retrieve(traceTag, request) //
97                     .flatMap(this::toBody);
98             });
99     }
100
101     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
102         Object traceTag = createTraceTag();
103         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
104         logger.trace("{} PUT body: {}", traceTag, body);
105         return getWebClient() //
106             .flatMap(client -> {
107                 RequestHeadersSpec<?> request = client.put() //
108                     .uri(uri) //
109                     .contentType(MediaType.APPLICATION_JSON) //
110                     .bodyValue(body);
111                 return retrieve(traceTag, request);
112             });
113     }
114
115     public Mono<ResponseEntity<String>> putForEntity(String uri) {
116         Object traceTag = createTraceTag();
117         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
118         logger.trace("{} PUT body: <empty>", traceTag);
119         return getWebClient() //
120             .flatMap(client -> {
121                 RequestHeadersSpec<?> request = client.put() //
122                     .uri(uri);
123                 return retrieve(traceTag, request);
124             });
125     }
126
127     public Mono<String> put(String uri, String body) {
128         return putForEntity(uri, body) //
129             .flatMap(this::toBody);
130     }
131
132     public Mono<ResponseEntity<String>> getForEntity(String uri) {
133         Object traceTag = createTraceTag();
134         logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
135         return getWebClient() //
136             .flatMap(client -> {
137                 RequestHeadersSpec<?> request = client.get().uri(uri);
138                 return retrieve(traceTag, request);
139             });
140     }
141
142     public Mono<String> get(String uri) {
143         return getForEntity(uri) //
144             .flatMap(this::toBody);
145     }
146
147     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
148         Object traceTag = createTraceTag();
149         logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
150         return getWebClient() //
151             .flatMap(client -> {
152                 RequestHeadersSpec<?> request = client.delete().uri(uri);
153                 return retrieve(traceTag, request);
154             });
155     }
156
157     public Mono<String> delete(String uri) {
158         return deleteForEntity(uri) //
159             .flatMap(this::toBody);
160     }
161
162     private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
163         final Class<String> clazz = String.class;
164         return request.retrieve() //
165             .toEntity(clazz) //
166             .doOnNext(entity -> logReceivedData(traceTag, entity)) //
167             .doOnError(throwable -> onHttpError(traceTag, throwable));
168     }
169
170     private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
171         logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
172     }
173
174     private static Object createTraceTag() {
175         return sequenceNumber.incrementAndGet();
176     }
177
178     private void onHttpError(Object traceTag, Throwable t) {
179         if (t instanceof WebClientResponseException) {
180             WebClientResponseException exception = (WebClientResponseException) t;
181             logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
182                 exception.getResponseBodyAsString());
183         } else {
184             logger.debug("{} HTTP error {}", traceTag, t.getMessage());
185         }
186     }
187
188     private Mono<String> toBody(ResponseEntity<String> entity) {
189         if (entity.getBody() == null) {
190             return Mono.just("");
191         } else {
192             return Mono.just(entity.getBody());
193         }
194     }
195
196     private boolean isHttpProxyConfigured() {
197         return httpProxyConfig != null && httpProxyConfig.httpProxyPort() > 0
198             && !httpProxyConfig.httpProxyHost().isEmpty();
199     }
200
201     private HttpClient buildHttpClient() {
202         HttpClient httpClient = HttpClient.create() //
203             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
204             .doOnConnected(connection -> {
205                 connection.addHandlerLast(new ReadTimeoutHandler(30));
206                 connection.addHandlerLast(new WriteTimeoutHandler(30));
207             });
208
209         if (this.sslContext != null) {
210             httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
211         }
212
213         if (isHttpProxyConfigured()) {
214             httpClient = httpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP)
215                 .host(httpProxyConfig.httpProxyHost()).port(httpProxyConfig.httpProxyPort()));
216         }
217         return httpClient;
218     }
219
220     private WebClient buildWebClient(String baseUrl) {
221         final HttpClient httpClient = buildHttpClient();
222         ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
223             .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
224             .build();
225         return WebClient.builder() //
226             .clientConnector(new ReactorClientHttpConnector(httpClient)) //
227             .baseUrl(baseUrl) //
228             .exchangeStrategies(exchangeStrategies) //
229             .build();
230     }
231
232     private Mono<WebClient> getWebClient() {
233         if (this.webClient == null) {
234             this.webClient = buildWebClient(baseUrl);
235         }
236         return Mono.just(buildWebClient(baseUrl));
237     }
238
239 }