2 * ========================LICENSE_START=================================
5 * Copyright (C) 2021 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.oran.dmaapadapter.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.oran.dmaapadapter.configuration.WebClientConfig.HttpProxyConfig;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.http.MediaType;
35 import org.springframework.http.ResponseEntity;
36 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
37 import org.springframework.lang.Nullable;
38 import org.springframework.web.reactive.function.client.ExchangeStrategies;
39 import org.springframework.web.reactive.function.client.WebClient;
40 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
41 import org.springframework.web.reactive.function.client.WebClientResponseException;
43 import reactor.core.publisher.Mono;
44 import reactor.netty.http.client.HttpClient;
45 import reactor.netty.transport.ProxyProvider;
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;
57 private final HttpProxyConfig httpProxyConfig;
59 public AsyncRestClient(String baseUrl, @Nullable SslContext sslContext, @Nullable HttpProxyConfig httpProxyConfig) {
60 this.baseUrl = baseUrl;
61 this.sslContext = sslContext;
62 this.httpProxyConfig = httpProxyConfig;
65 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body,
66 @Nullable MediaType contentType) {
67 Object traceTag = createTraceTag();
68 logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
69 logger.trace("{} POST body: {}", traceTag, body);
70 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
72 RequestHeadersSpec<?> request = getWebClient() //
75 .contentType(contentType) //
76 .body(bodyProducer, String.class);
77 return retrieve(traceTag, request);
80 public Mono<String> post(String uri, @Nullable String body, @Nullable MediaType contentType) {
81 return postForEntity(uri, body, contentType) //
85 public Mono<String> postWithAuthHeader(String uri, String body, String username, String password,
86 MediaType mediaType) {
87 Object traceTag = createTraceTag();
88 logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
89 logger.trace("{} POST body: {}", traceTag, body);
91 RequestHeadersSpec<?> request = getWebClient() //
94 .headers(headers -> headers.setBasicAuth(username, password)) //
95 .contentType(mediaType) //
97 return retrieve(traceTag, request) //
101 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
102 Object traceTag = createTraceTag();
103 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
104 logger.trace("{} PUT body: {}", traceTag, body);
106 RequestHeadersSpec<?> request = getWebClient() //
109 .contentType(MediaType.APPLICATION_JSON) //
111 return retrieve(traceTag, request);
114 public Mono<ResponseEntity<String>> putForEntity(String uri) {
115 Object traceTag = createTraceTag();
116 logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
117 logger.trace("{} PUT body: <empty>", traceTag);
118 RequestHeadersSpec<?> request = getWebClient() //
121 return retrieve(traceTag, request);
124 public Mono<String> put(String uri, String body) {
125 return putForEntity(uri, body) //
129 public Mono<ResponseEntity<String>> getForEntity(String uri) {
130 Object traceTag = createTraceTag();
131 logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
132 RequestHeadersSpec<?> request = getWebClient().get().uri(uri);
133 return retrieve(traceTag, request);
136 public Mono<String> get(String uri) {
137 return getForEntity(uri) //
141 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
142 Object traceTag = createTraceTag();
143 logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
144 RequestHeadersSpec<?> request = getWebClient().delete().uri(uri);
145 return retrieve(traceTag, request);
148 public Mono<String> delete(String uri) {
149 return deleteForEntity(uri) //
153 private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
154 final Class<String> clazz = String.class;
155 return request.retrieve() //
157 .doOnNext(entity -> logReceivedData(traceTag, entity)) //
158 .doOnError(throwable -> onHttpError(traceTag, throwable));
161 private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
162 logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
165 private static Object createTraceTag() {
166 return sequenceNumber.incrementAndGet();
169 private void onHttpError(Object traceTag, Throwable t) {
170 if (t instanceof WebClientResponseException) {
171 WebClientResponseException exception = (WebClientResponseException) t;
172 logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
173 exception.getResponseBodyAsString());
175 logger.debug("{} HTTP error {}", traceTag, t.getMessage());
179 private String toBody(ResponseEntity<String> entity) {
180 if (entity.getBody() == null) {
183 return entity.getBody();
187 private boolean isHttpProxyConfigured() {
188 return httpProxyConfig != null && httpProxyConfig.httpProxyPort() > 0
189 && !httpProxyConfig.httpProxyHost().isEmpty();
192 private HttpClient buildHttpClient() {
193 HttpClient httpClient = HttpClient.create() //
194 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
195 .doOnConnected(connection -> {
196 connection.addHandlerLast(new ReadTimeoutHandler(30));
197 connection.addHandlerLast(new WriteTimeoutHandler(30));
200 if (this.sslContext != null) {
201 httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
204 if (isHttpProxyConfigured()) {
205 httpClient = httpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP)
206 .host(httpProxyConfig.httpProxyHost()).port(httpProxyConfig.httpProxyPort()));
211 private WebClient buildWebClient(String baseUrl) {
212 final HttpClient httpClient = buildHttpClient();
213 ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
214 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
216 return WebClient.builder() //
217 .clientConnector(new ReactorClientHttpConnector(httpClient)) //
219 .exchangeStrategies(exchangeStrategies) //
223 private WebClient getWebClient() {
224 if (this.webClient == null) {
225 this.webClient = buildWebClient(baseUrl);
227 return this.webClient;