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;
71 public AsyncRestClient(String baseUrl) {
73 ImmutableWebClientConfig.builder().isTrustStoreUsed(false).trustStore("").trustStorePassword("").build());
76 public AsyncRestClient(String baseUrl, WebClientConfig config) {
77 this.baseUrl = baseUrl;
78 this.clientConfig = config;
81 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
82 Object traceTag = createTraceTag();
83 logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
84 logger.trace("{} POST body: {}", traceTag, body);
85 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
86 return getWebClient() //
88 RequestHeadersSpec<?> request = client.post() //
90 .contentType(MediaType.APPLICATION_JSON) //
91 .body(bodyProducer, String.class);
92 return retrieve(traceTag, request);
96 public Mono<String> post(String uri, @Nullable String body) {
97 return postForEntity(uri, body) //
98 .flatMap(this::toBody);
101 public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
102 Object traceTag = createTraceTag();
103 logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
104 logger.trace("{} POST body: {}", traceTag, body);
105 return getWebClient() //
107 RequestHeadersSpec<?> request = client.post() //
109 .headers(headers -> headers.setBasicAuth(username, password)) //
110 .contentType(MediaType.APPLICATION_JSON) //
112 return retrieve(traceTag, request) //
113 .flatMap(this::toBody);
117 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
118 Object traceTag = createTraceTag();
119 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
120 logger.trace("{} PUT body: {}", traceTag, body);
121 return getWebClient() //
123 RequestHeadersSpec<?> request = client.put() //
125 .contentType(MediaType.APPLICATION_JSON) //
127 return retrieve(traceTag, request);
131 public Mono<ResponseEntity<String>> putForEntity(String uri) {
132 Object traceTag = createTraceTag();
133 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
134 logger.trace("{} PUT body: <empty>", traceTag);
135 return getWebClient() //
137 RequestHeadersSpec<?> request = client.put() //
139 return retrieve(traceTag, request);
143 public Mono<String> put(String uri, String body) {
144 return putForEntity(uri, body) //
145 .flatMap(this::toBody);
148 public Mono<ResponseEntity<String>> getForEntity(String uri) {
149 Object traceTag = createTraceTag();
150 logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
151 return getWebClient() //
153 RequestHeadersSpec<?> request = client.get().uri(uri);
154 return retrieve(traceTag, request);
158 public Mono<String> get(String uri) {
159 return getForEntity(uri) //
160 .flatMap(this::toBody);
163 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
164 Object traceTag = createTraceTag();
165 logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
166 return getWebClient() //
168 RequestHeadersSpec<?> request = client.delete().uri(uri);
169 return retrieve(traceTag, request);
173 public Mono<String> delete(String uri) {
174 return deleteForEntity(uri) //
175 .flatMap(this::toBody);
178 private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
179 return request.retrieve() //
180 .toEntity(String.class) //
181 .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody()))
182 .doOnError(throwable -> onHttpError(traceTag, throwable));
185 private static Object createTraceTag() {
186 return sequenceNumber.incrementAndGet();
189 private void onHttpError(Object traceTag, Throwable t) {
190 if (t instanceof WebClientResponseException) {
191 WebClientResponseException exception = (WebClientResponseException) t;
192 logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
193 exception.getResponseBodyAsString());
195 logger.debug("{} HTTP error: {}", traceTag, t.getMessage());
199 private Mono<String> toBody(ResponseEntity<String> entity) {
200 if (entity.getBody() == null) {
201 return Mono.just("");
203 return Mono.just(entity.getBody());
207 private boolean isCertificateEntry(KeyStore trustStore, String alias) {
209 return trustStore.isCertificateEntry(alias);
210 } catch (KeyStoreException e) {
211 logger.error("Error reading truststore {}", e.getMessage());
216 private Certificate getCertificate(KeyStore trustStore, String alias) {
218 return trustStore.getCertificate(alias);
219 } catch (KeyStoreException e) {
220 logger.error("Error reading truststore {}", e.getMessage());
225 SslContext createSslContextSecure(String trustStorePath, String trustStorePass)
226 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
228 final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
229 trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
231 List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
232 .filter(alias -> isCertificateEntry(trustStore, alias)) //
233 .map(alias -> getCertificate(trustStore, alias)) //
234 .collect(Collectors.toList());
235 final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
237 return SslContextBuilder.forClient() //
238 .trustManager(certificates) //
242 private SslContext createSslContext()
243 throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
244 if (this.clientConfig.isTrustStoreUsed()) {
245 return createSslContextSecure(this.clientConfig.trustStore(), this.clientConfig.trustStorePassword());
247 return SslContextBuilder.forClient() //
248 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
253 private WebClient createWebClient(String baseUrl, SslContext sslContext) {
254 TcpClient tcpClient = TcpClient.create() //
255 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
256 .secure(c -> c.sslContext(sslContext)) //
257 .doOnConnected(connection -> {
258 connection.addHandlerLast(new ReadTimeoutHandler(30));
259 connection.addHandlerLast(new WriteTimeoutHandler(30));
261 HttpClient httpClient = HttpClient.from(tcpClient);
262 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
264 return WebClient.builder() //
265 .clientConnector(connector) //
270 private Mono<WebClient> getWebClient() {
271 if (this.webClient == null) {
273 SslContext sslContext = createSslContext();
274 this.webClient = createWebClient(this.baseUrl, sslContext);
275 } catch (Exception e) {
276 logger.error("Could not create WebClient {}", e.getMessage());
277 return Mono.error(e);
280 return Mono.just(this.webClient);