2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2019-2022 Nordix Foundation. All rights reserved.
6 * ======================================================================
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.onap.ccsdk.oran.a1policymanagementservice.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.onap.ccsdk.oran.a1policymanagementservice.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.ExchangeFilterFunction;
39 import org.springframework.web.reactive.function.client.ExchangeStrategies;
40 import org.springframework.web.reactive.function.client.WebClient;
41 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
42 import org.springframework.web.reactive.function.client.WebClientResponseException;
44 import reactor.core.publisher.Mono;
45 import reactor.netty.http.client.HttpClient;
46 import reactor.netty.transport.ProxyProvider;
49 * Generic reactive REST client.
51 public class AsyncRestClient {
53 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
54 private WebClient webClient = null;
55 private final String baseUrl;
56 private static final AtomicInteger sequenceNumber = new AtomicInteger();
57 private final SslContext sslContext;
58 private final HttpProxyConfig httpProxyConfig;
59 private final SecurityContext securityContext;
61 public AsyncRestClient(String baseUrl, @Nullable SslContext sslContext, @Nullable HttpProxyConfig httpProxyConfig,
62 SecurityContext securityContext) {
63 this.baseUrl = baseUrl;
64 this.sslContext = sslContext;
65 this.httpProxyConfig = httpProxyConfig;
66 this.securityContext = securityContext;
69 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
70 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
72 RequestHeadersSpec<?> request = getWebClient() //
75 .contentType(MediaType.APPLICATION_JSON) //
76 .body(bodyProducer, String.class);
77 return retrieve(request);
80 public Mono<String> post(String uri, @Nullable String body) {
81 return postForEntity(uri, body) //
85 public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
86 RequestHeadersSpec<?> request = getWebClient() //
89 .headers(headers -> headers.setBasicAuth(username, password)) //
90 .contentType(MediaType.APPLICATION_JSON) //
92 return retrieve(request) //
96 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
97 RequestHeadersSpec<?> request = getWebClient() //
100 .contentType(MediaType.APPLICATION_JSON) //
102 return retrieve(request);
105 public Mono<ResponseEntity<String>> putForEntity(String uri) {
106 RequestHeadersSpec<?> request = getWebClient() //
109 return retrieve(request);
112 public Mono<String> put(String uri, String body) {
113 return putForEntity(uri, body) //
117 public Mono<ResponseEntity<String>> getForEntity(String uri) {
118 RequestHeadersSpec<?> request = getWebClient().get().uri(uri);
119 return retrieve(request);
122 public Mono<String> get(String uri) {
123 return getForEntity(uri) //
127 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
128 RequestHeadersSpec<?> request = getWebClient().delete().uri(uri);
129 return retrieve(request);
132 public Mono<String> delete(String uri) {
133 return deleteForEntity(uri) //
137 private Mono<ResponseEntity<String>> retrieve(RequestHeadersSpec<?> request) {
138 if (securityContext.isConfigured()) {
139 request.headers(h -> h.setBearerAuth(securityContext.getBearerAuthToken()));
141 return request.retrieve() //
142 .toEntity(String.class) //
143 .doOnError(this::onError);
147 private void onError(Throwable t) {
148 if (t instanceof WebClientResponseException) {
149 WebClientResponseException e = (WebClientResponseException) t;
150 logger.debug("Response error: {}", e.getResponseBodyAsString());
154 private static Object createTraceTag() {
155 return sequenceNumber.incrementAndGet();
158 private String toBody(ResponseEntity<String> entity) {
159 if (entity.getBody() == null) {
162 return entity.getBody();
166 private boolean isHttpProxyConfigured() {
167 return httpProxyConfig != null && httpProxyConfig.getHttpProxyPort() > 0
168 && !httpProxyConfig.getHttpProxyHost().isEmpty();
171 private HttpClient buildHttpClient() {
172 HttpClient httpClient = HttpClient.create() //
173 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
174 .doOnConnected(connection -> {
175 connection.addHandlerLast(new ReadTimeoutHandler(30));
176 connection.addHandlerLast(new WriteTimeoutHandler(30));
179 if (this.sslContext != null) {
180 httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
183 if (isHttpProxyConfigured()) {
184 httpClient = httpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP)
185 .host(httpProxyConfig.getHttpProxyHost()).port(httpProxyConfig.getHttpProxyPort()));
190 public WebClient buildWebClient(String baseUrl) {
191 Object traceTag = createTraceTag();
193 final HttpClient httpClient = buildHttpClient();
194 ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
195 .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
198 ExchangeFilterFunction reqLogger = ExchangeFilterFunction.ofRequestProcessor(req -> {
199 logger.debug("{} {} uri = '{}''", traceTag, req.method(), req.url());
200 return Mono.just(req);
203 ExchangeFilterFunction respLogger = ExchangeFilterFunction.ofResponseProcessor(resp -> {
204 logger.debug("{} resp: {}", traceTag, resp.statusCode());
205 return Mono.just(resp);
208 return WebClient.builder() //
209 .clientConnector(new ReactorClientHttpConnector(httpClient)) //
211 .exchangeStrategies(exchangeStrategies) //
212 .filter(reqLogger) //
213 .filter(respLogger) //
217 private WebClient getWebClient() {
218 if (this.webClient == null) {
219 this.webClient = buildWebClient(baseUrl);
221 return this.webClient;