2 * ========================LICENSE_START=================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.onap.ccsdk.oran.a1policymanagementservice.clients;
23 import io.netty.channel.ChannelOption;
24 import io.netty.handler.ssl.SslContext;
25 import io.netty.handler.ssl.SslContextBuilder;
26 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
27 import io.netty.handler.timeout.ReadTimeoutHandler;
28 import io.netty.handler.timeout.WriteTimeoutHandler;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.lang.invoke.MethodHandles;
34 import java.security.KeyStore;
35 import java.security.KeyStoreException;
36 import java.security.NoSuchAlgorithmException;
37 import java.security.cert.Certificate;
38 import java.security.cert.CertificateException;
39 import java.security.cert.X509Certificate;
40 import java.util.Collections;
41 import java.util.List;
42 import java.util.concurrent.atomic.AtomicInteger;
43 import java.util.stream.Collectors;
45 import javax.net.ssl.KeyManagerFactory;
47 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.http.MediaType;
51 import org.springframework.http.ResponseEntity;
52 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
53 import org.springframework.lang.Nullable;
54 import org.springframework.util.ResourceUtils;
55 import org.springframework.web.reactive.function.client.ExchangeStrategies;
56 import org.springframework.web.reactive.function.client.WebClient;
57 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
58 import org.springframework.web.reactive.function.client.WebClientResponseException;
60 import reactor.core.publisher.Mono;
61 import reactor.netty.http.client.HttpClient;
62 import reactor.netty.resources.ConnectionProvider;
63 import reactor.netty.tcp.TcpClient;
66 * Generic reactive REST client.
68 public class AsyncRestClient {
69 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
70 private WebClient webClient = null;
71 private final String baseUrl;
72 private static final AtomicInteger sequenceNumber = new AtomicInteger();
73 private final WebClientConfig clientConfig;
74 static KeyStore clientTrustStore = null;
75 private boolean sslEnabled = true;
77 public AsyncRestClient(String baseUrl) {
79 this.sslEnabled = false;
82 public AsyncRestClient(String baseUrl, WebClientConfig config) {
83 this.baseUrl = baseUrl;
84 this.clientConfig = config;
87 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
88 Object traceTag = createTraceTag();
89 logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
90 logger.trace("{} POST body: {}", traceTag, body);
91 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
92 return getWebClient() //
94 RequestHeadersSpec<?> request = client.post() //
96 .contentType(MediaType.APPLICATION_JSON) //
97 .body(bodyProducer, String.class);
98 return retrieve(traceTag, request);
102 public Mono<String> post(String uri, @Nullable String body) {
103 return postForEntity(uri, body) //
104 .flatMap(this::toBody);
107 public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
108 Object traceTag = createTraceTag();
109 logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
110 logger.trace("{} POST body: {}", traceTag, body);
111 return getWebClient() //
113 RequestHeadersSpec<?> request = client.post() //
115 .headers(headers -> headers.setBasicAuth(username, password)) //
116 .contentType(MediaType.APPLICATION_JSON) //
118 return retrieve(traceTag, request) //
119 .flatMap(this::toBody);
123 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
124 Object traceTag = createTraceTag();
125 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
126 logger.trace("{} PUT body: {}", traceTag, body);
127 return getWebClient() //
129 RequestHeadersSpec<?> request = client.put() //
131 .contentType(MediaType.APPLICATION_JSON) //
133 return retrieve(traceTag, request);
137 public Mono<ResponseEntity<String>> putForEntity(String uri) {
138 Object traceTag = createTraceTag();
139 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
140 logger.trace("{} PUT body: <empty>", traceTag);
141 return getWebClient() //
143 RequestHeadersSpec<?> request = client.put() //
145 return retrieve(traceTag, request);
149 public Mono<String> put(String uri, String body) {
150 return putForEntity(uri, body) //
151 .flatMap(this::toBody);
154 public Mono<ResponseEntity<String>> getForEntity(String uri) {
155 Object traceTag = createTraceTag();
156 logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
157 return getWebClient() //
159 RequestHeadersSpec<?> request = client.get().uri(uri);
160 return retrieve(traceTag, request);
164 public Mono<String> get(String uri) {
165 return getForEntity(uri) //
166 .flatMap(this::toBody);
169 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
170 Object traceTag = createTraceTag();
171 logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
172 return getWebClient() //
174 RequestHeadersSpec<?> request = client.delete().uri(uri);
175 return retrieve(traceTag, request);
179 public Mono<String> delete(String uri) {
180 return deleteForEntity(uri) //
181 .flatMap(this::toBody);
184 private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
185 final Class<String> clazz = String.class;
186 return request.retrieve() //
188 .doOnNext(entity -> logReceivedData(traceTag, entity)) //
189 .doOnError(throwable -> onHttpError(traceTag, throwable));
192 private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
193 logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
196 private static Object createTraceTag() {
197 return sequenceNumber.incrementAndGet();
200 private void onHttpError(Object traceTag, Throwable t) {
201 if (t instanceof WebClientResponseException) {
202 WebClientResponseException exception = (WebClientResponseException) t;
203 logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
204 exception.getResponseBodyAsString());
206 logger.debug("{} HTTP error", traceTag, t);
210 private Mono<String> toBody(ResponseEntity<String> entity) {
211 if (entity.getBody() == null) {
212 return Mono.just("");
214 return Mono.just(entity.getBody());
218 private boolean isCertificateEntry(KeyStore trustStore, String alias) {
220 return trustStore.isCertificateEntry(alias);
221 } catch (KeyStoreException e) {
222 logger.error("Error reading truststore {}", e.getMessage());
227 private Certificate getCertificate(KeyStore trustStore, String alias) {
229 return trustStore.getCertificate(alias);
230 } catch (KeyStoreException e) {
231 logger.error("Error reading truststore {}", e.getMessage());
236 private static synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
237 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
238 if (clientTrustStore == null) {
239 KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
240 store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
241 clientTrustStore = store;
243 return clientTrustStore;
246 private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass,
247 KeyManagerFactory keyManager)
248 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
250 final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
251 List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
252 .filter(alias -> isCertificateEntry(trustStore, alias)) //
253 .map(alias -> getCertificate(trustStore, alias)) //
254 .collect(Collectors.toList());
255 final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
257 return SslContextBuilder.forClient() //
258 .keyManager(keyManager) //
259 .trustManager(certificates) //
263 private SslContext createSslContext(KeyManagerFactory keyManager)
264 throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
265 if (this.clientConfig.isTrustStoreUsed()) {
266 return createSslContextRejectingUntrustedPeers(this.clientConfig.trustStore(),
267 this.clientConfig.trustStorePassword(), keyManager);
270 return SslContextBuilder.forClient() //
271 .keyManager(keyManager) //
272 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
277 private TcpClient createTcpClientSecure(SslContext sslContext) {
278 return TcpClient.create(ConnectionProvider.newConnection()) //
279 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
280 .secure(c -> c.sslContext(sslContext)) //
281 .doOnConnected(connection -> {
282 connection.addHandlerLast(new ReadTimeoutHandler(30));
283 connection.addHandlerLast(new WriteTimeoutHandler(30));
287 private TcpClient createTcpClientInsecure() {
288 return TcpClient.create(ConnectionProvider.newConnection()) //
289 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
290 .doOnConnected(connection -> {
291 connection.addHandlerLast(new ReadTimeoutHandler(30));
292 connection.addHandlerLast(new WriteTimeoutHandler(30));
296 private WebClient createWebClient(String baseUrl, TcpClient tcpClient) {
297 HttpClient httpClient = HttpClient.from(tcpClient);
298 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
299 ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
300 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
302 return WebClient.builder() //
303 .clientConnector(connector) //
305 .exchangeStrategies(exchangeStrategies) //
309 private Mono<WebClient> getWebClient() {
310 if (this.webClient == null) {
312 if (this.sslEnabled) {
313 final KeyManagerFactory keyManager =
314 KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
315 final KeyStore keyStore = KeyStore.getInstance(this.clientConfig.keyStoreType());
316 final String keyStoreFile = this.clientConfig.keyStore();
317 final String keyStorePassword = this.clientConfig.keyStorePassword();
318 final String keyPassword = this.clientConfig.keyPassword();
319 try (final InputStream inputStream = new FileInputStream(keyStoreFile)) {
320 keyStore.load(inputStream, keyStorePassword.toCharArray());
322 keyManager.init(keyStore, keyPassword.toCharArray());
323 SslContext sslContext = createSslContext(keyManager);
324 TcpClient tcpClient = createTcpClientSecure(sslContext);
325 this.webClient = createWebClient(this.baseUrl, tcpClient);
327 TcpClient tcpClient = createTcpClientInsecure();
328 this.webClient = createWebClient(this.baseUrl, tcpClient);
330 } catch (Exception e) {
331 logger.error("Could not create WebClient {}", e.getMessage());
332 return Mono.error(e);
335 return Mono.just(this.webClient);