c3be9b4de6e160a00e3ed0242124e3addeac0d3d
[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.onap.ccsdk.oran.a1policymanagementservice.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
46 /**
47  * Generic reactive REST client.
48  */
49 public class AsyncRestClient {
50
51     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
52     private WebClient webClient = null;
53     private final String baseUrl;
54     private static final AtomicInteger sequenceNumber = new AtomicInteger();
55     private final SslContext sslContext;
56     private final HttpProxyConfig httpProxyConfig;
57
58     public AsyncRestClient(String baseUrl, @Nullable SslContext sslContext, @Nullable HttpProxyConfig httpProxyConfig) {
59         this.baseUrl = baseUrl;
60         this.sslContext = sslContext;
61         this.httpProxyConfig = httpProxyConfig;
62     }
63
64     public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
65         Object traceTag = createTraceTag();
66         logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
67         logger.trace("{} POST body: {}", traceTag, body);
68         Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
69         return getWebClient() //
70                 .flatMap(client -> {
71                     RequestHeadersSpec<?> request = client.post() //
72                             .uri(uri) //
73                             .contentType(MediaType.APPLICATION_JSON) //
74                             .body(bodyProducer, String.class);
75                     return retrieve(traceTag, request);
76                 });
77     }
78
79     public Mono<String> post(String uri, @Nullable String body) {
80         return postForEntity(uri, body) //
81                 .flatMap(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         return getWebClient() //
89                 .flatMap(client -> {
90                     RequestHeadersSpec<?> request = client.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                             .flatMap(this::toBody);
97                 });
98     }
99
100     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
101         Object traceTag = createTraceTag();
102         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
103         logger.trace("{} PUT body: {}", traceTag, body);
104         return getWebClient() //
105                 .flatMap(client -> {
106                     RequestHeadersSpec<?> request = client.put() //
107                             .uri(uri) //
108                             .contentType(MediaType.APPLICATION_JSON) //
109                             .bodyValue(body);
110                     return retrieve(traceTag, request);
111                 });
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         return getWebClient() //
119                 .flatMap(client -> {
120                     RequestHeadersSpec<?> request = client.put() //
121                             .uri(uri);
122                     return retrieve(traceTag, request);
123                 });
124     }
125
126     public Mono<String> put(String uri, String body) {
127         return putForEntity(uri, body) //
128                 .flatMap(this::toBody);
129     }
130
131     public Mono<ResponseEntity<String>> getForEntity(String uri) {
132         Object traceTag = createTraceTag();
133         logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
134         return getWebClient() //
135                 .flatMap(client -> {
136                     RequestHeadersSpec<?> request = client.get().uri(uri);
137                     return retrieve(traceTag, request);
138                 });
139     }
140
141     public Mono<String> get(String uri) {
142         return getForEntity(uri) //
143                 .flatMap(this::toBody);
144     }
145
146     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
147         Object traceTag = createTraceTag();
148         logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
149         return getWebClient() //
150                 .flatMap(client -> {
151                     RequestHeadersSpec<?> request = client.delete().uri(uri);
152                     return retrieve(traceTag, request);
153                 });
154     }
155
156     public Mono<String> delete(String uri) {
157         return deleteForEntity(uri) //
158                 .flatMap(this::toBody);
159     }
160
161     private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
162         final Class<String> clazz = String.class;
163         return request.retrieve() //
164                 .toEntity(clazz) //
165                 .doOnNext(entity -> logReceivedData(traceTag, entity)) //
166                 .doOnError(throwable -> onHttpError(traceTag, throwable));
167     }
168
169     private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
170         logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
171     }
172
173     private static Object createTraceTag() {
174         return sequenceNumber.incrementAndGet();
175     }
176
177     private void onHttpError(Object traceTag, Throwable t) {
178         if (t instanceof WebClientResponseException) {
179             WebClientResponseException exception = (WebClientResponseException) t;
180             logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
181                     exception.getResponseBodyAsString());
182         } else {
183             logger.debug("{} HTTP error {}", traceTag, t.getMessage());
184         }
185     }
186
187     private Mono<String> toBody(ResponseEntity<String> entity) {
188         if (entity.getBody() == null) {
189             return Mono.just("");
190         } else {
191             return Mono.just(entity.getBody());
192         }
193     }
194
195     private boolean isHttpProxyConfigured() {
196         return httpProxyConfig != null && httpProxyConfig.httpProxyPort() > 0
197                 && !httpProxyConfig.httpProxyHost().isEmpty();
198     }
199
200     private HttpClient buildHttpClient() {
201         HttpClient httpClient = HttpClient.create() //
202                 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
203                 .doOnConnected(connection -> {
204                     connection.addHandlerLast(new ReadTimeoutHandler(30));
205                     connection.addHandlerLast(new WriteTimeoutHandler(30));
206                 });
207
208         if (this.sslContext != null) {
209             httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
210         }
211
212         if (isHttpProxyConfigured()) {
213             httpClient = httpClient.proxy(proxy -> proxy.type(httpProxyConfig.httpProxyType()) //
214                     .host(httpProxyConfig.httpProxyHost()) //
215                     .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 }