2 * ========================LICENSE_START=================================
5 * Copyright (C) 2020 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.enrichment.clients;
23 import io.netty.channel.ChannelOption;
24 import io.netty.handler.ssl.SslContext;
25 import io.netty.handler.timeout.ReadTimeoutHandler;
26 import io.netty.handler.timeout.WriteTimeoutHandler;
28 import java.lang.invoke.MethodHandles;
29 import java.util.concurrent.atomic.AtomicInteger;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.http.MediaType;
34 import org.springframework.http.ResponseEntity;
35 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
36 import org.springframework.lang.Nullable;
37 import org.springframework.web.reactive.function.client.ExchangeStrategies;
38 import org.springframework.web.reactive.function.client.WebClient;
39 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
40 import org.springframework.web.reactive.function.client.WebClientResponseException;
42 import reactor.core.publisher.Mono;
43 import reactor.netty.http.client.HttpClient;
44 import reactor.netty.resources.ConnectionProvider;
45 import reactor.netty.tcp.TcpClient;
48 * Generic reactive REST client.
50 public class AsyncRestClient {
52 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
53 private WebClient webClient = null;
54 private final String baseUrl;
55 private static final AtomicInteger sequenceNumber = new AtomicInteger();
56 private final SslContext sslContext;
59 * Note that only http (not https) will work when this constructor is used.
63 public AsyncRestClient(String baseUrl) {
67 public AsyncRestClient(String baseUrl, SslContext sslContext) {
68 this.baseUrl = baseUrl;
69 this.sslContext = sslContext;
72 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
73 Object traceTag = createTraceTag();
74 logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
75 logger.trace("{} POST body: {}", traceTag, body);
76 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
77 return getWebClient() //
79 RequestHeadersSpec<?> request = client.post() //
81 .contentType(MediaType.APPLICATION_JSON) //
82 .body(bodyProducer, String.class);
83 return retrieve(traceTag, request);
87 public Mono<String> post(String uri, @Nullable String body) {
88 return postForEntity(uri, body) //
89 .flatMap(this::toBody);
92 public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
93 Object traceTag = createTraceTag();
94 logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
95 logger.trace("{} POST body: {}", traceTag, body);
96 return getWebClient() //
98 RequestHeadersSpec<?> request = client.post() //
100 .headers(headers -> headers.setBasicAuth(username, password)) //
101 .contentType(MediaType.APPLICATION_JSON) //
103 return retrieve(traceTag, request) //
104 .flatMap(this::toBody);
108 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
109 Object traceTag = createTraceTag();
110 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
111 logger.trace("{} PUT body: {}", traceTag, body);
112 return getWebClient() //
114 RequestHeadersSpec<?> request = client.put() //
116 .contentType(MediaType.APPLICATION_JSON) //
118 return retrieve(traceTag, request);
122 public Mono<ResponseEntity<String>> putForEntity(String uri) {
123 Object traceTag = createTraceTag();
124 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
125 logger.trace("{} PUT body: <empty>", traceTag);
126 return getWebClient() //
128 RequestHeadersSpec<?> request = client.put() //
130 return retrieve(traceTag, request);
134 public Mono<String> put(String uri, String body) {
135 return putForEntity(uri, body) //
136 .flatMap(this::toBody);
139 public Mono<ResponseEntity<String>> getForEntity(String uri) {
140 Object traceTag = createTraceTag();
141 logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
142 return getWebClient() //
144 RequestHeadersSpec<?> request = client.get().uri(uri);
145 return retrieve(traceTag, request);
149 public Mono<String> get(String uri) {
150 return getForEntity(uri) //
151 .flatMap(this::toBody);
154 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
155 Object traceTag = createTraceTag();
156 logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
157 return getWebClient() //
159 RequestHeadersSpec<?> request = client.delete().uri(uri);
160 return retrieve(traceTag, request);
164 public Mono<String> delete(String uri) {
165 return deleteForEntity(uri) //
166 .flatMap(this::toBody);
169 private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
170 final Class<String> clazz = String.class;
171 return request.retrieve() //
173 .doOnNext(entity -> logReceivedData(traceTag, entity)) //
174 .doOnError(throwable -> onHttpError(traceTag, throwable));
177 private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
178 logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
181 private static Object createTraceTag() {
182 return sequenceNumber.incrementAndGet();
185 private void onHttpError(Object traceTag, Throwable t) {
186 if (t instanceof WebClientResponseException) {
187 WebClientResponseException exception = (WebClientResponseException) t;
188 logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
189 exception.getResponseBodyAsString());
191 logger.debug("{} HTTP error", traceTag, t);
195 private Mono<String> toBody(ResponseEntity<String> entity) {
196 if (entity.getBody() == null) {
197 return Mono.just("");
199 return Mono.just(entity.getBody());
203 private TcpClient createTcpClientSecure(SslContext sslContext) {
204 return TcpClient.create(ConnectionProvider.newConnection()) //
205 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
206 .secure(c -> c.sslContext(sslContext)) //
207 .doOnConnected(connection -> {
208 connection.addHandlerLast(new ReadTimeoutHandler(30));
209 connection.addHandlerLast(new WriteTimeoutHandler(30));
213 private TcpClient createTcpClientInsecure() {
214 return TcpClient.create(ConnectionProvider.newConnection()) //
215 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
216 .doOnConnected(connection -> {
217 connection.addHandlerLast(new ReadTimeoutHandler(30));
218 connection.addHandlerLast(new WriteTimeoutHandler(30));
222 private WebClient createWebClient(String baseUrl, TcpClient tcpClient) {
223 HttpClient httpClient = HttpClient.from(tcpClient);
224 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
225 ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
226 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
228 return WebClient.builder() //
229 .clientConnector(connector) //
231 .exchangeStrategies(exchangeStrategies) //
235 private Mono<WebClient> getWebClient() {
236 if (this.webClient == null) {
238 if (this.sslContext != null) {
239 TcpClient tcpClient = createTcpClientSecure(sslContext);
240 this.webClient = createWebClient(this.baseUrl, tcpClient);
242 TcpClient tcpClient = createTcpClientInsecure();
243 this.webClient = createWebClient(this.baseUrl, tcpClient);
245 } catch (Exception e) {
246 logger.error("Could not create WebClient {}", e.getMessage());
247 return Mono.error(e);
250 return Mono.just(this.webClient);