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.lang.invoke.MethodHandles;
32 import javax.net.ssl.SSLException;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.http.MediaType;
37 import org.springframework.http.ResponseEntity;
38 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
39 import org.springframework.lang.Nullable;
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.tcp.TcpClient;
49 * Generic reactive REST client.
51 public class AsyncRestClient {
52 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
53 private WebClient webClient = null;
54 private final String baseUrl;
56 public AsyncRestClient(String baseUrl) {
57 this.baseUrl = baseUrl;
60 public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
61 logger.debug("POST uri = '{}{}''", baseUrl, uri);
62 Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
63 return getWebClient() //
65 RequestHeadersSpec<?> request = client.post() //
67 .contentType(MediaType.APPLICATION_JSON) //
68 .body(bodyProducer, String.class);
69 return retrieve(request);
73 public Mono<String> post(String uri, @Nullable String body) {
74 return postForEntity(uri, body) //
75 .flatMap(this::toBody);
78 public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
79 logger.debug("POST (auth) uri = '{}{}''", baseUrl, uri);
80 return getWebClient() //
82 RequestHeadersSpec<?> request = client.post() //
84 .headers(headers -> headers.setBasicAuth(username, password)) //
85 .contentType(MediaType.APPLICATION_JSON) //
87 return retrieve(request) //
88 .flatMap(this::toBody);
92 public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
93 logger.debug("PUT uri = '{}{}''", baseUrl, uri);
94 return getWebClient() //
96 RequestHeadersSpec<?> request = client.put() //
98 .contentType(MediaType.APPLICATION_JSON) //
100 return retrieve(request);
104 public Mono<ResponseEntity<String>> putForEntity(String uri) {
105 logger.debug("PUT uri = '{}{}''", baseUrl, uri);
106 return getWebClient() //
108 RequestHeadersSpec<?> request = client.put() //
110 return retrieve(request);
114 public Mono<String> put(String uri, String body) {
115 return putForEntity(uri, body) //
116 .flatMap(this::toBody);
119 public Mono<ResponseEntity<String>> getForEntity(String uri) {
120 logger.debug("GET uri = '{}{}''", baseUrl, uri);
121 return getWebClient() //
123 RequestHeadersSpec<?> request = client.get().uri(uri);
124 return retrieve(request);
128 public Mono<String> get(String uri) {
129 return getForEntity(uri) //
130 .flatMap(this::toBody);
133 public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
134 logger.debug("DELETE uri = '{}{}''", baseUrl, uri);
135 return getWebClient() //
137 RequestHeadersSpec<?> request = client.delete().uri(uri);
138 return retrieve(request);
142 public Mono<String> delete(String uri) {
143 return deleteForEntity(uri) //
144 .flatMap(this::toBody);
147 private Mono<ResponseEntity<String>> retrieve(RequestHeadersSpec<?> request) {
148 return request.retrieve() //
149 .toEntity(String.class) //
150 .doOnError(this::onHttpError);
153 private void onHttpError(Throwable t) {
154 if (t instanceof WebClientResponseException) {
155 WebClientResponseException exception = (WebClientResponseException) t;
156 logger.debug("HTTP error status = '{}', body '{}'", exception.getStatusCode(),
157 exception.getResponseBodyAsString());
159 logger.debug("HTTP error: {}", t.getMessage());
163 private Mono<String> toBody(ResponseEntity<String> entity) {
164 if (entity.getBody() == null) {
165 return Mono.just("");
167 return Mono.just(entity.getBody());
171 private static SslContext createSslContext() throws SSLException {
172 return SslContextBuilder.forClient() //
173 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
177 private static WebClient createWebClient(String baseUrl, SslContext sslContext) {
178 TcpClient tcpClient = TcpClient.create() //
179 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
180 .secure(c -> c.sslContext(sslContext)) //
181 .doOnConnected(connection -> {
182 connection.addHandler(new ReadTimeoutHandler(10));
183 connection.addHandler(new WriteTimeoutHandler(30));
185 HttpClient httpClient = HttpClient.from(tcpClient);
186 ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
188 return WebClient.builder() //
189 .clientConnector(connector) //
194 private Mono<WebClient> getWebClient() {
195 if (this.webClient == null) {
197 SslContext sslContext = createSslContext();
198 this.webClient = createWebClient(this.baseUrl, sslContext);
199 } catch (SSLException e) {
200 logger.error("Could not create WebClient {}", e.getMessage());
201 return Mono.error(e);
204 return Mono.just(this.webClient);