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.policyagent.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.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.oransc.policyagent.configuration.ImmutableWebClientConfig;
45 import org.oransc.policyagent.configuration.WebClientConfig;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.http.MediaType;
49 import org.springframework.http.ResponseEntity;
50 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
51 import org.springframework.lang.Nullable;
52 import org.springframework.util.ResourceUtils;
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.tcp.TcpClient;
62 * Generic reactive REST client.
64 public class AsyncRestClient {
65 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
66 private WebClient webClient = null;
67 private final String baseUrl;
68 private static final AtomicInteger sequenceNumber = new AtomicInteger();
69 private final WebClientConfig clientConfig;
70 static KeyStore clientTrustStore = null;
72 public AsyncRestClient(String baseUrl) {
74 ImmutableWebClientConfig.builder().isTrustStoreUsed(false).trustStore("").trustStorePassword("").build());
77 public AsyncRestClient(String baseUrl, WebClientConfig config) {
78 this.baseUrl = baseUrl;
79 this.clientConfig = config;
82 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
83 Object traceTag = createTraceTag();
84 logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
85 logger.trace("{} POST body: {}", traceTag, body);
86 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
87 return getWebClient() //
89 RequestHeadersSpec<?> request = client.post() //
91 .contentType(MediaType.APPLICATION_JSON) //
92 .body(bodyProducer, String.class);
93 return retrieve(traceTag, request);
97 public Mono<String> post(String uri, @Nullable String body) {
98 return postForEntity(uri, body) //
99 .flatMap(this::toBody);
102 public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
103 Object traceTag = createTraceTag();
104 logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
105 logger.trace("{} POST body: {}", traceTag, body);
106 return getWebClient() //
108 RequestHeadersSpec<?> request = client.post() //
110 .headers(headers -> headers.setBasicAuth(username, password)) //
111 .contentType(MediaType.APPLICATION_JSON) //
113 return retrieve(traceTag, request) //
114 .flatMap(this::toBody);
118 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
119 Object traceTag = createTraceTag();
120 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
121 logger.trace("{} PUT body: {}", traceTag, body);
122 return getWebClient() //
124 RequestHeadersSpec<?> request = client.put() //
126 .contentType(MediaType.APPLICATION_JSON) //
128 return retrieve(traceTag, request);
132 public Mono<ResponseEntity<String>> putForEntity(String uri) {
133 Object traceTag = createTraceTag();
134 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
135 logger.trace("{} PUT body: <empty>", traceTag);
136 return getWebClient() //
138 RequestHeadersSpec<?> request = client.put() //
140 return retrieve(traceTag, request);
144 public Mono<String> put(String uri, String body) {
145 return putForEntity(uri, body) //
146 .flatMap(this::toBody);
149 public Mono<ResponseEntity<String>> getForEntity(String uri) {
150 Object traceTag = createTraceTag();
151 logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
152 return getWebClient() //
154 RequestHeadersSpec<?> request = client.get().uri(uri);
155 return retrieve(traceTag, request);
159 public Mono<String> get(String uri) {
160 return getForEntity(uri) //
161 .flatMap(this::toBody);
164 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
165 Object traceTag = createTraceTag();
166 logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
167 return getWebClient() //
169 RequestHeadersSpec<?> request = client.delete().uri(uri);
170 return retrieve(traceTag, request);
174 public Mono<String> delete(String uri) {
175 return deleteForEntity(uri) //
176 .flatMap(this::toBody);
179 private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
180 return request.retrieve() //
181 .toEntity(String.class) //
182 .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody()))
183 .doOnError(throwable -> onHttpError(traceTag, throwable));
186 private static Object createTraceTag() {
187 return sequenceNumber.incrementAndGet();
190 private void onHttpError(Object traceTag, Throwable t) {
191 if (t instanceof WebClientResponseException) {
192 WebClientResponseException exception = (WebClientResponseException) t;
193 logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
194 exception.getResponseBodyAsString());
196 logger.debug("{} HTTP error: {}", traceTag, t.getMessage());
200 private Mono<String> toBody(ResponseEntity<String> entity) {
201 if (entity.getBody() == null) {
202 return Mono.just("");
204 return Mono.just(entity.getBody());
208 private boolean isCertificateEntry(KeyStore trustStore, String alias) {
210 return trustStore.isCertificateEntry(alias);
211 } catch (KeyStoreException e) {
212 logger.error("Error reading truststore {}", e.getMessage());
217 private Certificate getCertificate(KeyStore trustStore, String alias) {
219 return trustStore.getCertificate(alias);
220 } catch (KeyStoreException e) {
221 logger.error("Error reading truststore {}", e.getMessage());
226 private static synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
227 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
228 if (clientTrustStore == null) {
229 KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
230 store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
231 clientTrustStore = store;
233 return clientTrustStore;
236 private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass)
237 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
239 final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
240 List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
241 .filter(alias -> isCertificateEntry(trustStore, alias)) //
242 .map(alias -> getCertificate(trustStore, alias)) //
243 .collect(Collectors.toList());
244 final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
246 return SslContextBuilder.forClient() //
247 .trustManager(certificates) //
251 private SslContext createSslContext()
252 throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
253 if (this.clientConfig.isTrustStoreUsed()) {
254 return createSslContextRejectingUntrustedPeers(this.clientConfig.trustStore(),
255 this.clientConfig.trustStorePassword());
258 return SslContextBuilder.forClient() //
259 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
264 private WebClient createWebClient(String baseUrl, SslContext sslContext) {
265 TcpClient tcpClient = TcpClient.create() //
266 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
267 .secure(c -> c.sslContext(sslContext)) //
268 .doOnConnected(connection -> {
269 connection.addHandlerLast(new ReadTimeoutHandler(30));
270 connection.addHandlerLast(new WriteTimeoutHandler(30));
272 HttpClient httpClient = HttpClient.from(tcpClient);
273 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
275 return WebClient.builder() //
276 .clientConnector(connector) //
281 private Mono<WebClient> getWebClient() {
282 if (this.webClient == null) {
284 SslContext sslContext = createSslContext();
285 this.webClient = createWebClient(this.baseUrl, sslContext);
286 } catch (Exception e) {
287 logger.error("Could not create WebClient {}", e.getMessage());
288 return Mono.error(e);
291 return Mono.just(this.webClient);