b7f23b1f5d20df269b8a8e36dc83fee317c5e7ba
[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
71         RequestHeadersSpec<?> request = getWebClient() //
72             .post() //
73             .uri(uri) //
74             .contentType(MediaType.APPLICATION_JSON) //
75             .body(bodyProducer, String.class);
76         return retrieve(traceTag, request);
77     }
78
79     public Mono<String> post(String uri, @Nullable String body) {
80         return postForEntity(uri, body) //
81             .map(this::toBody);
82     }
83
84     public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
85         Object traceTag = createTraceTag();
86         logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
87         logger.trace("{} POST body: {}", traceTag, body);
88
89         RequestHeadersSpec<?> request = getWebClient() //
90             .post() //
91             .uri(uri) //
92             .headers(headers -> headers.setBasicAuth(username, password)) //
93             .contentType(MediaType.APPLICATION_JSON) //
94             .bodyValue(body);
95         return retrieve(traceTag, request) //
96             .map(this::toBody);
97     }
98
99     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
100         Object traceTag = createTraceTag();
101         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
102         logger.trace("{} PUT body: {}", traceTag, body);
103
104         RequestHeadersSpec<?> request = getWebClient() //
105             .put() //
106             .uri(uri) //
107             .contentType(MediaType.APPLICATION_JSON) //
108             .bodyValue(body);
109         return retrieve(traceTag, request);
110     }
111
112     public Mono<ResponseEntity<String>> putForEntity(String uri) {
113         Object traceTag = createTraceTag();
114         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
115         logger.trace("{} PUT body: <empty>", traceTag);
116         RequestHeadersSpec<?> request = getWebClient() //
117             .put() //
118             .uri(uri);
119         return retrieve(traceTag, request);
120     }
121
122     public Mono<String> put(String uri, String body) {
123         return putForEntity(uri, body) //
124             .map(this::toBody);
125     }
126
127     public Mono<ResponseEntity<String>> getForEntity(String uri) {
128         Object traceTag = createTraceTag();
129         logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
130         RequestHeadersSpec<?> request = getWebClient().get().uri(uri);
131         return retrieve(traceTag, request);
132     }
133
134     public Mono<String> get(String uri) {
135         return getForEntity(uri) //
136             .map(this::toBody);
137     }
138
139     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
140         Object traceTag = createTraceTag();
141         logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
142         RequestHeadersSpec<?> request = getWebClient().delete().uri(uri);
143         return retrieve(traceTag, request);
144     }
145
146     public Mono<String> delete(String uri) {
147         return deleteForEntity(uri) //
148             .map(this::toBody);
149     }
150
151     private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
152         final Class<String> clazz = String.class;
153         return request.retrieve() //
154             .toEntity(clazz) //
155             .doOnNext(entity -> logReceivedData(traceTag, entity)) //
156             .doOnError(throwable -> onHttpError(traceTag, throwable));
157     }
158
159     private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
160         logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
161     }
162
163     private static Object createTraceTag() {
164         return sequenceNumber.incrementAndGet();
165     }
166
167     private void onHttpError(Object traceTag, Throwable t) {
168         if (t instanceof WebClientResponseException) {
169             WebClientResponseException exception = (WebClientResponseException) t;
170             logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
171                 exception.getResponseBodyAsString());
172         } else {
173             logger.debug("{} HTTP error {}", traceTag, t.getMessage());
174         }
175     }
176
177     private String toBody(ResponseEntity<String> entity) {
178         if (entity.getBody() == null) {
179             return "";
180         } else {
181             return entity.getBody();
182         }
183     }
184
185     private boolean isHttpProxyConfigured() {
186         return httpProxyConfig != null && httpProxyConfig.httpProxyPort() > 0
187             && !httpProxyConfig.httpProxyHost().isEmpty();
188     }
189
190     private HttpClient buildHttpClient() {
191         HttpClient httpClient = HttpClient.create() //
192             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
193             .doOnConnected(connection -> {
194                 connection.addHandlerLast(new ReadTimeoutHandler(30));
195                 connection.addHandlerLast(new WriteTimeoutHandler(30));
196             });
197
198         if (this.sslContext != null) {
199             httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
200         }
201
202         if (isHttpProxyConfigured()) {
203             httpClient = httpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP)
204                 .host(httpProxyConfig.httpProxyHost()).port(httpProxyConfig.httpProxyPort()));
205         }
206         return httpClient;
207     }
208
209     private WebClient buildWebClient(String baseUrl) {
210         final HttpClient httpClient = buildHttpClient();
211         ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
212             .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
213             .build();
214         return WebClient.builder() //
215             .clientConnector(new ReactorClientHttpConnector(httpClient)) //
216             .baseUrl(baseUrl) //
217             .exchangeStrategies(exchangeStrategies) //
218             .build();
219     }
220
221     private WebClient getWebClient() {
222         if (this.webClient == null) {
223             this.webClient = buildWebClient(baseUrl);
224         }
225         return this.webClient;
226     }
227 }