Merge "Added support for https"
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / clients / AsyncRestClient.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.oransc.policyagent.clients;
22
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;
29
30 import java.lang.invoke.MethodHandles;
31
32 import javax.net.ssl.SSLException;
33
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;
43
44 import reactor.core.publisher.Mono;
45 import reactor.netty.http.client.HttpClient;
46 import reactor.netty.tcp.TcpClient;
47
48 /**
49  * Generic reactive REST client.
50  */
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;
55
56     public AsyncRestClient(String baseUrl) {
57         this.baseUrl = baseUrl;
58     }
59
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() //
64             .flatMap(client -> {
65                 RequestHeadersSpec<?> request = client.post() //
66                     .uri(uri) //
67                     .contentType(MediaType.APPLICATION_JSON) //
68                     .body(bodyProducer, String.class);
69                 return retrieve(request);
70             });
71     }
72
73     public Mono<String> post(String uri, @Nullable String body) {
74         return postForEntity(uri, body) //
75             .flatMap(this::toBody);
76     }
77
78     public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
79         logger.debug("POST (auth) uri = '{}{}''", baseUrl, uri);
80         return getWebClient() //
81             .flatMap(client -> {
82                 RequestHeadersSpec<?> request = client.post() //
83                     .uri(uri) //
84                     .headers(headers -> headers.setBasicAuth(username, password)) //
85                     .contentType(MediaType.APPLICATION_JSON) //
86                     .bodyValue(body);
87                 return retrieve(request) //
88                     .flatMap(this::toBody);
89             });
90     }
91
92     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
93         logger.debug("PUT uri = '{}{}''", baseUrl, uri);
94         return getWebClient() //
95             .flatMap(client -> {
96                 RequestHeadersSpec<?> request = client.put() //
97                     .uri(uri) //
98                     .contentType(MediaType.APPLICATION_JSON) //
99                     .bodyValue(body);
100                 return retrieve(request);
101             });
102     }
103
104     public Mono<ResponseEntity<String>> putForEntity(String uri) {
105         logger.debug("PUT uri = '{}{}''", baseUrl, uri);
106         return getWebClient() //
107             .flatMap(client -> {
108                 RequestHeadersSpec<?> request = client.put() //
109                     .uri(uri);
110                 return retrieve(request);
111             });
112     }
113
114     public Mono<String> put(String uri, String body) {
115         return putForEntity(uri, body) //
116             .flatMap(this::toBody);
117     }
118
119     public Mono<ResponseEntity<String>> getForEntity(String uri) {
120         logger.debug("GET uri = '{}{}''", baseUrl, uri);
121         return getWebClient() //
122             .flatMap(client -> {
123                 RequestHeadersSpec<?> request = client.get().uri(uri);
124                 return retrieve(request);
125             });
126     }
127
128     public Mono<String> get(String uri) {
129         return getForEntity(uri) //
130             .flatMap(this::toBody);
131     }
132
133     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
134         logger.debug("DELETE uri = '{}{}''", baseUrl, uri);
135         return getWebClient() //
136             .flatMap(client -> {
137                 RequestHeadersSpec<?> request = client.delete().uri(uri);
138                 return retrieve(request);
139             });
140     }
141
142     public Mono<String> delete(String uri) {
143         return deleteForEntity(uri) //
144             .flatMap(this::toBody);
145     }
146
147     private Mono<ResponseEntity<String>> retrieve(RequestHeadersSpec<?> request) {
148         return request.retrieve() //
149             .toEntity(String.class) //
150             .doOnError(this::onHttpError);
151     }
152
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());
158         } else {
159             logger.debug("HTTP error: {}", t.getMessage());
160         }
161     }
162
163     private Mono<String> toBody(ResponseEntity<String> entity) {
164         if (entity.getBody() == null) {
165             return Mono.just("");
166         } else {
167             return Mono.just(entity.getBody());
168         }
169     }
170
171     private static SslContext createSslContext() throws SSLException {
172         return SslContextBuilder.forClient() //
173             .trustManager(InsecureTrustManagerFactory.INSTANCE) //
174             .build();
175     }
176
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));
184             });
185         HttpClient httpClient = HttpClient.from(tcpClient);
186         ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
187
188         return WebClient.builder() //
189             .clientConnector(connector) //
190             .baseUrl(baseUrl) //
191             .build();
192     }
193
194     private Mono<WebClient> getWebClient() {
195         if (this.webClient == null) {
196             try {
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);
202             }
203         }
204         return Mono.just(this.webClient);
205     }
206
207 }