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.lang.Nullable;
51 import org.springframework.util.ResourceUtils;
52 import org.springframework.web.reactive.function.client.ExchangeStrategies;
53 import org.springframework.web.reactive.function.client.WebClient;
54 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
55 import org.springframework.web.reactive.function.client.WebClientResponseException;
57 import reactor.core.publisher.Mono;
58 import reactor.netty.http.client.HttpClient;
59 import reactor.netty.resources.ConnectionProvider;
60 import reactor.netty.tcp.TcpClient;
63 * Generic reactive REST client.
65 public class AsyncRestClient {
68 @Value.Style(redactedMask = "####")
69 public interface WebClientConfig {
70 public boolean isTrustStoreUsed();
73 public String trustStorePassword();
75 public String trustStore();
78 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
79 private WebClient webClient = null;
80 private final String baseUrl;
81 private static final AtomicInteger sequenceNumber = new AtomicInteger();
82 private final WebClientConfig clientConfig;
83 static KeyStore clientTrustStore = null;
85 public AsyncRestClient(String baseUrl) {
87 ImmutableWebClientConfig.builder().isTrustStoreUsed(false).trustStore("").trustStorePassword("").build());
90 public AsyncRestClient(String baseUrl, WebClientConfig config) {
91 this.baseUrl = baseUrl;
92 this.clientConfig = config;
95 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
96 Object traceTag = createTraceTag();
97 logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
98 logger.trace("{} POST body: {}", traceTag, body);
99 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
100 return getWebClient() //
102 RequestHeadersSpec<?> request = client.post() //
104 .contentType(MediaType.APPLICATION_JSON) //
105 .body(bodyProducer, String.class);
106 return retrieve(traceTag, request);
110 public Mono<String> post(String uri, @Nullable String body) {
111 return postForEntity(uri, body) //
112 .flatMap(this::toBody);
115 public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
116 Object traceTag = createTraceTag();
117 logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
118 logger.trace("{} POST body: {}", traceTag, body);
119 return getWebClient() //
121 RequestHeadersSpec<?> request = client.post() //
123 .headers(headers -> headers.setBasicAuth(username, password)) //
124 .contentType(MediaType.APPLICATION_JSON) //
126 return retrieve(traceTag, request) //
127 .flatMap(this::toBody);
131 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
132 Object traceTag = createTraceTag();
133 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
134 logger.trace("{} PUT body: {}", traceTag, body);
135 return getWebClient() //
137 RequestHeadersSpec<?> request = client.put() //
139 .contentType(MediaType.APPLICATION_JSON) //
141 return retrieve(traceTag, request);
145 public Mono<ResponseEntity<String>> putForEntity(String uri) {
146 Object traceTag = createTraceTag();
147 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
148 logger.trace("{} PUT body: <empty>", traceTag);
149 return getWebClient() //
151 RequestHeadersSpec<?> request = client.put() //
153 return retrieve(traceTag, request);
157 public Mono<String> put(String uri, String body) {
158 return putForEntity(uri, body) //
159 .flatMap(this::toBody);
162 public Mono<ResponseEntity<String>> getForEntity(String uri) {
163 Object traceTag = createTraceTag();
164 logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
165 return getWebClient() //
167 RequestHeadersSpec<?> request = client.get().uri(uri);
168 return retrieve(traceTag, request);
172 public Mono<String> get(String uri) {
173 return getForEntity(uri) //
174 .flatMap(this::toBody);
177 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
178 Object traceTag = createTraceTag();
179 logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
180 return getWebClient() //
182 RequestHeadersSpec<?> request = client.delete().uri(uri);
183 return retrieve(traceTag, request);
187 public Mono<String> delete(String uri) {
188 return deleteForEntity(uri) //
189 .flatMap(this::toBody);
192 private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
193 final Class<String> clazz = String.class;
194 return request.retrieve() //
196 .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody())) //
197 .doOnError(throwable -> onHttpError(traceTag, throwable));
200 private static Object createTraceTag() {
201 return sequenceNumber.incrementAndGet();
204 private void onHttpError(Object traceTag, Throwable t) {
205 if (t instanceof WebClientResponseException) {
206 WebClientResponseException exception = (WebClientResponseException) t;
207 logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
208 exception.getResponseBodyAsString());
210 logger.debug("{} HTTP error: {}", traceTag, t.getMessage());
214 private Mono<String> toBody(ResponseEntity<String> entity) {
215 if (entity.getBody() == null) {
216 return Mono.just("");
218 return Mono.just(entity.getBody());
222 private boolean isCertificateEntry(KeyStore trustStore, String alias) {
224 return trustStore.isCertificateEntry(alias);
225 } catch (KeyStoreException e) {
226 logger.error("Error reading truststore {}", e.getMessage());
231 private Certificate getCertificate(KeyStore trustStore, String alias) {
233 return trustStore.getCertificate(alias);
234 } catch (KeyStoreException e) {
235 logger.error("Error reading truststore {}", e.getMessage());
240 private static synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
241 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
242 if (clientTrustStore == null) {
243 KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
244 store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
245 clientTrustStore = store;
247 return clientTrustStore;
250 private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass)
251 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
253 final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
254 List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
255 .filter(alias -> isCertificateEntry(trustStore, alias)) //
256 .map(alias -> getCertificate(trustStore, alias)) //
257 .collect(Collectors.toList());
258 final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
260 return SslContextBuilder.forClient() //
261 .trustManager(certificates) //
265 private SslContext createSslContext()
266 throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
267 if (this.clientConfig.isTrustStoreUsed()) {
268 return createSslContextRejectingUntrustedPeers(this.clientConfig.trustStore(),
269 this.clientConfig.trustStorePassword());
272 return SslContextBuilder.forClient() //
273 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
278 private WebClient createWebClient(String baseUrl, SslContext sslContext) {
279 ConnectionProvider connectionProvider = ConnectionProvider.newConnection();
280 TcpClient tcpClient = TcpClient.create(connectionProvider) //
281 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
282 .secure(c -> c.sslContext(sslContext)) //
284 .doOnConnected(connection -> {
285 connection.addHandlerLast(new ReadTimeoutHandler(30));
286 connection.addHandlerLast(new WriteTimeoutHandler(30));
288 HttpClient httpClient = HttpClient.from(tcpClient);
289 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
291 ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
292 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
295 return WebClient.builder() //
296 .clientConnector(connector) //
298 .exchangeStrategies(exchangeStrategies) //
302 private Mono<WebClient> getWebClient() {
303 if (this.webClient == null) {
305 SslContext sslContext = createSslContext();
306 this.webClient = createWebClient(this.baseUrl, sslContext);
307 } catch (Exception e) {
308 logger.error("Could not create WebClient {}", e.getMessage());
309 return Mono.error(e);
312 return Mono.just(this.webClient);