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