c4afdb2f165dc7b57fb49f91c98ff8af01d3fcd5
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2022 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.ExchangeFilterFunction;
39 import org.springframework.web.reactive.function.client.ExchangeStrategies;
40 import org.springframework.web.reactive.function.client.WebClient;
41 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
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     private final SecurityContext securityContext;
59
60     public AsyncRestClient(String baseUrl, @Nullable SslContext sslContext, @Nullable HttpProxyConfig httpProxyConfig,
61             SecurityContext securityContext) {
62         this.baseUrl = baseUrl;
63         this.sslContext = sslContext;
64         this.httpProxyConfig = httpProxyConfig;
65         this.securityContext = securityContext;
66     }
67
68     public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String 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(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         RequestHeadersSpec<?> request = getWebClient() //
86                 .post() //
87                 .uri(uri) //
88                 .headers(headers -> headers.setBasicAuth(username, password)) //
89                 .contentType(MediaType.APPLICATION_JSON) //
90                 .bodyValue(body);
91         return retrieve(request) //
92                 .map(this::toBody);
93     }
94
95     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
96         RequestHeadersSpec<?> request = getWebClient() //
97                 .put() //
98                 .uri(uri) //
99                 .contentType(MediaType.APPLICATION_JSON) //
100                 .bodyValue(body);
101         return retrieve(request);
102     }
103
104     public Mono<ResponseEntity<String>> putForEntity(String uri) {
105         RequestHeadersSpec<?> request = getWebClient() //
106                 .put() //
107                 .uri(uri);
108         return retrieve(request);
109     }
110
111     public Mono<String> put(String uri, String body) {
112         return putForEntity(uri, body) //
113                 .map(this::toBody);
114     }
115
116     public Mono<ResponseEntity<String>> getForEntity(String uri) {
117         RequestHeadersSpec<?> request = getWebClient().get().uri(uri);
118         return retrieve(request);
119     }
120
121     public Mono<String> get(String uri) {
122         return getForEntity(uri) //
123                 .map(this::toBody);
124     }
125
126     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
127         RequestHeadersSpec<?> request = getWebClient().delete().uri(uri);
128         return retrieve(request);
129     }
130
131     public Mono<String> delete(String uri) {
132         return deleteForEntity(uri) //
133                 .map(this::toBody);
134     }
135
136     private Mono<ResponseEntity<String>> retrieve(RequestHeadersSpec<?> request) {
137         if (securityContext.isConfigured()) {
138             request.headers(h -> h.setBearerAuth(securityContext.getBearerAuthToken()));
139         }
140         return request.retrieve() //
141                 .toEntity(String.class);
142     }
143
144     private static Object createTraceTag() {
145         return sequenceNumber.incrementAndGet();
146     }
147
148     private String toBody(ResponseEntity<String> entity) {
149         if (entity.getBody() == null) {
150             return "";
151         } else {
152             return entity.getBody();
153         }
154     }
155
156     private boolean isHttpProxyConfigured() {
157         return httpProxyConfig != null && httpProxyConfig.getHttpProxyPort() > 0
158                 && !httpProxyConfig.getHttpProxyHost().isEmpty();
159     }
160
161     private HttpClient buildHttpClient() {
162         HttpClient httpClient = HttpClient.create() //
163                 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
164                 .doOnConnected(connection -> {
165                     connection.addHandlerLast(new ReadTimeoutHandler(30));
166                     connection.addHandlerLast(new WriteTimeoutHandler(30));
167                 });
168
169         if (this.sslContext != null) {
170             httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
171         }
172
173         if (isHttpProxyConfigured()) {
174             httpClient = httpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP)
175                     .host(httpProxyConfig.getHttpProxyHost()).port(httpProxyConfig.getHttpProxyPort()));
176         }
177         return httpClient;
178     }
179
180     public WebClient buildWebClient(String baseUrl) {
181         Object traceTag = createTraceTag();
182
183         final HttpClient httpClient = buildHttpClient();
184         ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
185                 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
186                 .build();
187
188         ExchangeFilterFunction reqLogger = ExchangeFilterFunction.ofRequestProcessor(req -> {
189             logger.debug("{} {} uri = '{}''", traceTag, req.method(), req.url());
190             return Mono.just(req);
191         });
192
193         ExchangeFilterFunction respLogger = ExchangeFilterFunction.ofResponseProcessor(resp -> {
194             logger.debug("{} resp: {}", traceTag, resp.statusCode());
195             return Mono.just(resp);
196         });
197
198         return WebClient.builder() //
199                 .clientConnector(new ReactorClientHttpConnector(httpClient)) //
200                 .baseUrl(baseUrl) //
201                 .exchangeStrategies(exchangeStrategies) //
202                 .filter(reqLogger) //
203                 .filter(respLogger) //
204                 .build();
205     }
206
207     private WebClient getWebClient() {
208         if (this.webClient == null) {
209             this.webClient = buildWebClient(baseUrl);
210         }
211         return this.webClient;
212     }
213 }