Added support for https
[portal/nonrtric-controlpanel.git] / webapp-backend / src / main / java / org / oransc / portal / nonrtric / controlpanel / util / 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.portal.nonrtric.controlpanel.util;
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.web.reactive.function.client.WebClient;
40 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
41 import org.springframework.web.reactive.function.client.WebClientResponseException;
42
43 import reactor.core.publisher.Mono;
44 import reactor.netty.http.client.HttpClient;
45 import reactor.netty.tcp.TcpClient;
46
47 /**
48  * Generic reactive REST client.
49  */
50 public class AsyncRestClient {
51     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
52     private WebClient webClient = null;
53     private final String baseUrl;
54
55     public AsyncRestClient(String baseUrl) {
56         this.baseUrl = baseUrl;
57     }
58
59     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
60         logger.debug("PUT uri = '{}{}''", baseUrl, uri);
61         return getWebClient() //
62             .flatMap(client -> {
63                 RequestHeadersSpec<?> request = client.put() //
64                     .uri(uri) //
65                     .contentType(MediaType.APPLICATION_JSON) //
66                     .bodyValue(body);
67                 return retrieve(request);
68             });
69     }
70
71     public Mono<ResponseEntity<String>> putForEntity(String uri) {
72         logger.debug("PUT uri = '{}{}''", baseUrl, uri);
73         return getWebClient() //
74             .flatMap(client -> {
75                 RequestHeadersSpec<?> request = client.put() //
76                     .uri(uri);
77                 return retrieve(request);
78             });
79     }
80
81     public Mono<String> put(String uri, String body) {
82         return putForEntity(uri, body) //
83             .flatMap(this::toBody);
84     }
85
86     public Mono<ResponseEntity<String>> getForEntity(String uri) {
87         logger.debug("GET uri = '{}{}''", baseUrl, uri);
88         return getWebClient() //
89             .flatMap(client -> {
90                 RequestHeadersSpec<?> request = client.get().uri(uri);
91                 return retrieve(request);
92             });
93     }
94
95     public Mono<String> get(String uri) {
96         return getForEntity(uri) //
97             .flatMap(this::toBody);
98     }
99
100     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
101         logger.debug("DELETE uri = '{}{}''", baseUrl, uri);
102         return getWebClient() //
103             .flatMap(client -> {
104                 RequestHeadersSpec<?> request = client.delete().uri(uri);
105                 return retrieve(request);
106             });
107     }
108
109     public Mono<String> delete(String uri) {
110         return deleteForEntity(uri) //
111             .flatMap(this::toBody);
112     }
113
114     private Mono<ResponseEntity<String>> retrieve(RequestHeadersSpec<?> request) {
115         return request.retrieve() //
116             .toEntity(String.class) //
117             .doOnError(this::onHttpError);
118     }
119
120     private void onHttpError(Throwable t) {
121         if (t instanceof WebClientResponseException) {
122             WebClientResponseException exception = (WebClientResponseException) t;
123             logger.debug("HTTP error status = '{}', body '{}'", exception.getStatusCode(),
124                 exception.getResponseBodyAsString());
125         } else {
126             logger.debug("HTTP error: {}", t.getMessage());
127         }
128     }
129
130     private Mono<String> toBody(ResponseEntity<String> entity) {
131         if (entity.getBody() == null) {
132             return Mono.just("");
133         } else {
134             return Mono.just(entity.getBody());
135         }
136     }
137
138     private static SslContext createSslContext() throws SSLException {
139         return SslContextBuilder.forClient() //
140             .trustManager(InsecureTrustManagerFactory.INSTANCE) //
141             .build();
142     }
143
144     private static WebClient createWebClient(String baseUrl, SslContext sslContext) {
145         TcpClient tcpClient = TcpClient.create() //
146             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
147             .secure(c -> c.sslContext(sslContext)) //
148             .doOnConnected(connection -> {
149                 connection.addHandler(new ReadTimeoutHandler(10));
150                 connection.addHandler(new WriteTimeoutHandler(30));
151             });
152         HttpClient httpClient = HttpClient.from(tcpClient);
153         ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
154
155         return WebClient.builder() //
156             .clientConnector(connector) //
157             .baseUrl(baseUrl) //
158             .build();
159     }
160
161     private Mono<WebClient> getWebClient() {
162         if (this.webClient == null) {
163             try {
164                 SslContext sslContext = createSslContext();
165                 this.webClient = createWebClient(this.baseUrl, sslContext);
166             } catch (SSLException e) {
167                 logger.error("Could not create WebClient {}", e.getMessage());
168                 return Mono.error(e);
169             }
170         }
171         return Mono.just(this.webClient);
172     }
173
174 }