8409f45c587b8c8a78051bbe8fa35a07116c3190
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
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.onap.ccsdk.oran.a1policymanagementservice.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.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.http.MediaType;
34 import org.springframework.http.ResponseEntity;
35 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
36 import org.springframework.lang.Nullable;
37 import org.springframework.web.reactive.function.client.ExchangeStrategies;
38 import org.springframework.web.reactive.function.client.WebClient;
39 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
40 import org.springframework.web.reactive.function.client.WebClientResponseException;
41
42 import reactor.core.publisher.Mono;
43 import reactor.netty.http.client.HttpClient;
44 import reactor.netty.resources.ConnectionProvider;
45 import reactor.netty.tcp.TcpClient;
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
58     /**
59      * Note that only http (not https) will work when this constructor is used.
60      * 
61      * @param baseUrl
62      */
63     public AsyncRestClient(String baseUrl) {
64         this(baseUrl, null);
65     }
66
67     public AsyncRestClient(String baseUrl, SslContext sslContext) {
68         this.baseUrl = baseUrl;
69         this.sslContext = sslContext;
70     }
71
72     public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
73         Object traceTag = createTraceTag();
74         logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
75         logger.trace("{} POST body: {}", traceTag, body);
76         Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
77         return getWebClient() //
78                 .flatMap(client -> {
79                     RequestHeadersSpec<?> request = client.post() //
80                             .uri(uri) //
81                             .contentType(MediaType.APPLICATION_JSON) //
82                             .body(bodyProducer, String.class);
83                     return retrieve(traceTag, request);
84                 });
85     }
86
87     public Mono<String> post(String uri, @Nullable String body) {
88         return postForEntity(uri, body) //
89                 .flatMap(this::toBody);
90     }
91
92     public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
93         Object traceTag = createTraceTag();
94         logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
95         logger.trace("{} POST body: {}", traceTag, body);
96         return getWebClient() //
97                 .flatMap(client -> {
98                     RequestHeadersSpec<?> request = client.post() //
99                             .uri(uri) //
100                             .headers(headers -> headers.setBasicAuth(username, password)) //
101                             .contentType(MediaType.APPLICATION_JSON) //
102                             .bodyValue(body);
103                     return retrieve(traceTag, request) //
104                             .flatMap(this::toBody);
105                 });
106     }
107
108     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
109         Object traceTag = createTraceTag();
110         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
111         logger.trace("{} PUT body: {}", traceTag, body);
112         return getWebClient() //
113                 .flatMap(client -> {
114                     RequestHeadersSpec<?> request = client.put() //
115                             .uri(uri) //
116                             .contentType(MediaType.APPLICATION_JSON) //
117                             .bodyValue(body);
118                     return retrieve(traceTag, request);
119                 });
120     }
121
122     public Mono<ResponseEntity<String>> putForEntity(String uri) {
123         Object traceTag = createTraceTag();
124         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
125         logger.trace("{} PUT body: <empty>", traceTag);
126         return getWebClient() //
127                 .flatMap(client -> {
128                     RequestHeadersSpec<?> request = client.put() //
129                             .uri(uri);
130                     return retrieve(traceTag, request);
131                 });
132     }
133
134     public Mono<String> put(String uri, String body) {
135         return putForEntity(uri, body) //
136                 .flatMap(this::toBody);
137     }
138
139     public Mono<ResponseEntity<String>> getForEntity(String uri) {
140         Object traceTag = createTraceTag();
141         logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
142         return getWebClient() //
143                 .flatMap(client -> {
144                     RequestHeadersSpec<?> request = client.get().uri(uri);
145                     return retrieve(traceTag, request);
146                 });
147     }
148
149     public Mono<String> get(String uri) {
150         return getForEntity(uri) //
151                 .flatMap(this::toBody);
152     }
153
154     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
155         Object traceTag = createTraceTag();
156         logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
157         return getWebClient() //
158                 .flatMap(client -> {
159                     RequestHeadersSpec<?> request = client.delete().uri(uri);
160                     return retrieve(traceTag, request);
161                 });
162     }
163
164     public Mono<String> delete(String uri) {
165         return deleteForEntity(uri) //
166                 .flatMap(this::toBody);
167     }
168
169     private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
170         final Class<String> clazz = String.class;
171         return request.retrieve() //
172                 .toEntity(clazz) //
173                 .doOnNext(entity -> logReceivedData(traceTag, entity)) //
174                 .doOnError(throwable -> onHttpError(traceTag, throwable));
175     }
176
177     private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
178         logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
179     }
180
181     private static Object createTraceTag() {
182         return sequenceNumber.incrementAndGet();
183     }
184
185     private void onHttpError(Object traceTag, Throwable t) {
186         if (t instanceof WebClientResponseException) {
187             WebClientResponseException exception = (WebClientResponseException) t;
188             logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
189                     exception.getResponseBodyAsString());
190         } else {
191             logger.debug("{} HTTP error", traceTag, t);
192         }
193     }
194
195     private Mono<String> toBody(ResponseEntity<String> entity) {
196         if (entity.getBody() == null) {
197             return Mono.just("");
198         } else {
199             return Mono.just(entity.getBody());
200         }
201     }
202
203     private TcpClient createTcpClientSecure(SslContext sslContext) {
204         return TcpClient.create(ConnectionProvider.newConnection()) //
205                 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
206                 .secure(c -> c.sslContext(sslContext)) //
207                 .doOnConnected(connection -> {
208                     connection.addHandlerLast(new ReadTimeoutHandler(30));
209                     connection.addHandlerLast(new WriteTimeoutHandler(30));
210                 });
211     }
212
213     private TcpClient createTcpClientInsecure() {
214         return TcpClient.create(ConnectionProvider.newConnection()) //
215                 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
216                 .doOnConnected(connection -> {
217                     connection.addHandlerLast(new ReadTimeoutHandler(30));
218                     connection.addHandlerLast(new WriteTimeoutHandler(30));
219                 });
220     }
221
222     private WebClient createWebClient(String baseUrl, TcpClient tcpClient) {
223         HttpClient httpClient = HttpClient.from(tcpClient);
224         ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
225         ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
226                 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
227                 .build();
228         return WebClient.builder() //
229                 .clientConnector(connector) //
230                 .baseUrl(baseUrl) //
231                 .exchangeStrategies(exchangeStrategies) //
232                 .build();
233     }
234
235     private Mono<WebClient> getWebClient() {
236         if (this.webClient == null) {
237             try {
238                 if (this.sslContext != null) {
239                     TcpClient tcpClient = createTcpClientSecure(sslContext);
240                     this.webClient = createWebClient(this.baseUrl, tcpClient);
241                 } else {
242                     TcpClient tcpClient = createTcpClientInsecure();
243                     this.webClient = createWebClient(this.baseUrl, tcpClient);
244                 }
245             } catch (Exception e) {
246                 logger.error("Could not create WebClient {}", e.getMessage());
247                 return Mono.error(e);
248             }
249         }
250         return Mono.just(this.webClient);
251     }
252
253 }