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