2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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.oransc.portal.nonrtric.controlpanel.util;
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.lang.invoke.MethodHandles;
26 import java.security.KeyStore;
27 import java.security.KeyStoreException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.cert.Certificate;
30 import java.security.cert.CertificateException;
31 import java.security.cert.X509Certificate;
32 import java.util.Collections;
33 import java.util.List;
34 import java.util.concurrent.atomic.AtomicInteger;
35 import java.util.stream.Collectors;
36 import org.immutables.value.Value;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.http.MediaType;
40 import org.springframework.http.ResponseEntity;
41 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
42 import org.springframework.util.ResourceUtils;
43 import org.springframework.web.reactive.function.client.ExchangeStrategies;
44 import org.springframework.web.reactive.function.client.WebClient;
45 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
46 import org.springframework.web.reactive.function.client.WebClientResponseException;
47 import io.netty.channel.ChannelOption;
48 import io.netty.handler.ssl.SslContext;
49 import io.netty.handler.ssl.SslContextBuilder;
50 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
51 import io.netty.handler.timeout.ReadTimeoutHandler;
52 import io.netty.handler.timeout.WriteTimeoutHandler;
53 import reactor.core.publisher.Mono;
54 import reactor.netty.http.client.HttpClient;
55 import reactor.netty.resources.ConnectionProvider;
56 import reactor.netty.tcp.TcpClient;
59 * Generic reactive REST client.
61 public class AsyncRestClient {
64 @Value.Style(redactedMask = "####")
65 public interface WebClientConfig {
66 public boolean isTrustStoreUsed();
69 public String trustStorePassword();
71 public String trustStore();
74 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
75 private WebClient webClient = null;
76 private final String baseUrl;
77 private static final AtomicInteger sequenceNumber = new AtomicInteger();
78 private final WebClientConfig clientConfig;
79 static KeyStore clientTrustStore = null;
81 public AsyncRestClient(String baseUrl) {
83 ImmutableWebClientConfig.builder().isTrustStoreUsed(false).trustStore("").trustStorePassword("").build());
86 public AsyncRestClient(String baseUrl, WebClientConfig config) {
87 this.baseUrl = baseUrl;
88 this.clientConfig = config;
91 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
92 Object traceTag = createTraceTag();
93 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
94 logger.trace("{} PUT body: {}", traceTag, body);
95 return getWebClient() //
97 RequestHeadersSpec<?> request = client.put() //
99 .contentType(MediaType.APPLICATION_JSON) //
101 return retrieve(traceTag, request);
105 public Mono<ResponseEntity<String>> putForEntity(String uri) {
106 Object traceTag = createTraceTag();
107 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
108 logger.trace("{} PUT body: <empty>", traceTag);
109 return getWebClient() //
111 RequestHeadersSpec<?> request = client.put() //
113 return retrieve(traceTag, request);
117 public Mono<String> put(String uri, String body) {
118 return putForEntity(uri, body) //
119 .flatMap(this::toBody);
122 public Mono<ResponseEntity<String>> getForEntity(String uri) {
123 Object traceTag = createTraceTag();
124 logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
125 return getWebClient() //
127 RequestHeadersSpec<?> request = client.get().uri(uri);
128 return retrieve(traceTag, request);
132 public Mono<String> get(String uri) {
133 return getForEntity(uri) //
134 .flatMap(this::toBody);
137 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
138 Object traceTag = createTraceTag();
139 logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
140 return getWebClient() //
142 RequestHeadersSpec<?> request = client.delete().uri(uri);
143 return retrieve(traceTag, request);
147 public Mono<String> delete(String uri) {
148 return deleteForEntity(uri) //
149 .flatMap(this::toBody);
152 private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
153 final Class<String> clazz = String.class;
154 return request.retrieve() //
156 .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody())) //
157 .doOnError(throwable -> onHttpError(traceTag, throwable));
160 private static Object createTraceTag() {
161 return sequenceNumber.incrementAndGet();
164 private void onHttpError(Object traceTag, Throwable t) {
165 if (t instanceof WebClientResponseException) {
166 WebClientResponseException exception = (WebClientResponseException) t;
167 logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
168 exception.getResponseBodyAsString());
170 logger.debug("{} HTTP error: {}", traceTag, t.getMessage());
174 private Mono<String> toBody(ResponseEntity<String> entity) {
175 if (entity.getBody() == null) {
176 return Mono.just("");
178 return Mono.just(entity.getBody());
182 private boolean isCertificateEntry(KeyStore trustStore, String alias) {
184 return trustStore.isCertificateEntry(alias);
185 } catch (KeyStoreException e) {
186 logger.error("Error reading truststore {}", e.getMessage());
191 private Certificate getCertificate(KeyStore trustStore, String alias) {
193 return trustStore.getCertificate(alias);
194 } catch (KeyStoreException e) {
195 logger.error("Error reading truststore {}", e.getMessage());
200 private static synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
201 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
202 if (clientTrustStore == null) {
203 KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
204 store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
205 clientTrustStore = store;
207 return clientTrustStore;
210 private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass)
211 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
213 final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
214 List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
215 .filter(alias -> isCertificateEntry(trustStore, alias)) //
216 .map(alias -> getCertificate(trustStore, alias)) //
217 .collect(Collectors.toList());
218 final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
220 return SslContextBuilder.forClient() //
221 .trustManager(certificates) //
225 private SslContext createSslContext()
226 throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
227 if (this.clientConfig.isTrustStoreUsed()) {
228 return createSslContextRejectingUntrustedPeers(this.clientConfig.trustStore(),
229 this.clientConfig.trustStorePassword());
232 return SslContextBuilder.forClient() //
233 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
238 private WebClient createWebClient(String baseUrl, SslContext sslContext) {
239 ConnectionProvider connectionProvider = ConnectionProvider.newConnection();
240 TcpClient tcpClient = TcpClient.create(connectionProvider) //
241 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
242 .secure(c -> c.sslContext(sslContext)) //
244 .doOnConnected(connection -> {
245 connection.addHandlerLast(new ReadTimeoutHandler(30));
246 connection.addHandlerLast(new WriteTimeoutHandler(30));
248 HttpClient httpClient = HttpClient.from(tcpClient);
249 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
251 ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
252 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
255 return WebClient.builder() //
256 .clientConnector(connector) //
258 .exchangeStrategies(exchangeStrategies) //
262 private Mono<WebClient> getWebClient() {
263 if (this.webClient == null) {
265 SslContext sslContext = createSslContext();
266 this.webClient = createWebClient(this.baseUrl, sslContext);
267 } catch (Exception e) {
268 logger.error("Could not create WebClient {}", e.getMessage());
269 return Mono.error(e);
272 return Mono.just(this.webClient);