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 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.lang.invoke.MethodHandles;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.security.NoSuchAlgorithmException;
36 import java.security.cert.Certificate;
37 import java.security.cert.CertificateException;
38 import java.security.cert.X509Certificate;
39 import java.util.Collections;
40 import java.util.List;
41 import java.util.concurrent.atomic.AtomicInteger;
42 import java.util.stream.Collectors;
44 import org.immutables.value.Value;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.http.MediaType;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
50 import org.springframework.util.ResourceUtils;
51 import org.springframework.web.reactive.function.client.ExchangeStrategies;
52 import org.springframework.web.reactive.function.client.WebClient;
53 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
54 import org.springframework.web.reactive.function.client.WebClientResponseException;
56 import reactor.core.publisher.Mono;
57 import reactor.netty.http.client.HttpClient;
58 import reactor.netty.resources.ConnectionProvider;
59 import reactor.netty.tcp.TcpClient;
62 * Generic reactive REST client.
64 public class AsyncRestClient {
67 @Value.Style(redactedMask = "####")
68 public interface WebClientConfig {
69 public boolean isTrustStoreUsed();
72 public String trustStorePassword();
74 public String trustStore();
77 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
78 private WebClient webClient = null;
79 private final String baseUrl;
80 private static final AtomicInteger sequenceNumber = new AtomicInteger();
81 private final WebClientConfig clientConfig;
82 static KeyStore clientTrustStore = null;
84 public AsyncRestClient(String baseUrl) {
86 ImmutableWebClientConfig.builder().isTrustStoreUsed(false).trustStore("").trustStorePassword("").build());
89 public AsyncRestClient(String baseUrl, WebClientConfig config) {
90 this.baseUrl = baseUrl;
91 this.clientConfig = config;
94 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
95 Object traceTag = createTraceTag();
96 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
97 logger.trace("{} PUT body: {}", traceTag, body);
98 return getWebClient() //
100 RequestHeadersSpec<?> request = client.put() //
102 .contentType(MediaType.APPLICATION_JSON) //
104 return retrieve(traceTag, request);
108 public Mono<ResponseEntity<String>> putForEntity(String uri) {
109 Object traceTag = createTraceTag();
110 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
111 logger.trace("{} PUT body: <empty>", traceTag);
112 return getWebClient() //
114 RequestHeadersSpec<?> request = client.put() //
116 return retrieve(traceTag, request);
120 public Mono<String> put(String uri, String body) {
121 return putForEntity(uri, body) //
122 .flatMap(this::toBody);
125 public Mono<ResponseEntity<String>> getForEntity(String uri) {
126 Object traceTag = createTraceTag();
127 logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
128 return getWebClient() //
130 RequestHeadersSpec<?> request = client.get().uri(uri);
131 return retrieve(traceTag, request);
135 public Mono<String> get(String uri) {
136 return getForEntity(uri) //
137 .flatMap(this::toBody);
140 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
141 Object traceTag = createTraceTag();
142 logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
143 return getWebClient() //
145 RequestHeadersSpec<?> request = client.delete().uri(uri);
146 return retrieve(traceTag, request);
150 public Mono<String> delete(String uri) {
151 return deleteForEntity(uri) //
152 .flatMap(this::toBody);
155 private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
156 final Class<String> clazz = String.class;
157 return request.retrieve() //
159 .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody())) //
160 .doOnError(throwable -> onHttpError(traceTag, throwable));
163 private static Object createTraceTag() {
164 return sequenceNumber.incrementAndGet();
167 private void onHttpError(Object traceTag, Throwable t) {
168 if (t instanceof WebClientResponseException) {
169 WebClientResponseException exception = (WebClientResponseException) t;
170 logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
171 exception.getResponseBodyAsString());
173 logger.debug("{} HTTP error: {}", traceTag, t.getMessage());
177 private Mono<String> toBody(ResponseEntity<String> entity) {
178 if (entity.getBody() == null) {
179 return Mono.just("");
181 return Mono.just(entity.getBody());
185 private boolean isCertificateEntry(KeyStore trustStore, String alias) {
187 return trustStore.isCertificateEntry(alias);
188 } catch (KeyStoreException e) {
189 logger.error("Error reading truststore {}", e.getMessage());
194 private Certificate getCertificate(KeyStore trustStore, String alias) {
196 return trustStore.getCertificate(alias);
197 } catch (KeyStoreException e) {
198 logger.error("Error reading truststore {}", e.getMessage());
203 private static synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
204 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
205 if (clientTrustStore == null) {
206 KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
207 store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
208 clientTrustStore = store;
210 return clientTrustStore;
213 private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass)
214 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
216 final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
217 List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
218 .filter(alias -> isCertificateEntry(trustStore, alias)) //
219 .map(alias -> getCertificate(trustStore, alias)) //
220 .collect(Collectors.toList());
221 final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
223 return SslContextBuilder.forClient() //
224 .trustManager(certificates) //
228 private SslContext createSslContext()
229 throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
230 if (this.clientConfig.isTrustStoreUsed()) {
231 return createSslContextRejectingUntrustedPeers(this.clientConfig.trustStore(),
232 this.clientConfig.trustStorePassword());
235 return SslContextBuilder.forClient() //
236 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
241 private WebClient createWebClient(String baseUrl, SslContext sslContext) {
242 ConnectionProvider connectionProvider = ConnectionProvider.newConnection();
243 TcpClient tcpClient = TcpClient.create(connectionProvider) //
244 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
245 .secure(c -> c.sslContext(sslContext)) //
247 .doOnConnected(connection -> {
248 connection.addHandlerLast(new ReadTimeoutHandler(30));
249 connection.addHandlerLast(new WriteTimeoutHandler(30));
251 HttpClient httpClient = HttpClient.from(tcpClient);
252 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
254 ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
255 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
258 return WebClient.builder() //
259 .clientConnector(connector) //
261 .exchangeStrategies(exchangeStrategies) //
265 private Mono<WebClient> getWebClient() {
266 if (this.webClient == null) {
268 SslContext sslContext = createSslContext();
269 this.webClient = createWebClient(this.baseUrl, sslContext);
270 } catch (Exception e) {
271 logger.error("Could not create WebClient {}", e.getMessage());
272 return Mono.error(e);
275 return Mono.just(this.webClient);