aboutsummaryrefslogtreecommitdiffstats
path: root/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/AsyncRestClient.java
blob: c3be9b4de6e160a00e3ed0242124e3addeac0d3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/*-
 * ========================LICENSE_START=================================
 * ONAP : ccsdk oran
 * ======================================================================
 * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
 * ======================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================LICENSE_END===================================
 */

package org.onap.ccsdk.oran.a1policymanagementservice.clients;

import io.netty.channel.ChannelOption;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

import java.lang.invoke.MethodHandles;
import java.util.concurrent.atomic.AtomicInteger;

import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig.HttpProxyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.lang.Nullable;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
import org.springframework.web.reactive.function.client.WebClientResponseException;

import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

/**
 * Generic reactive REST client.
 */
public class AsyncRestClient {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    private WebClient webClient = null;
    private final String baseUrl;
    private static final AtomicInteger sequenceNumber = new AtomicInteger();
    private final SslContext sslContext;
    private final HttpProxyConfig httpProxyConfig;

    public AsyncRestClient(String baseUrl, @Nullable SslContext sslContext, @Nullable HttpProxyConfig httpProxyConfig) {
        this.baseUrl = baseUrl;
        this.sslContext = sslContext;
        this.httpProxyConfig = httpProxyConfig;
    }

    public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
        Object traceTag = createTraceTag();
        logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
        logger.trace("{} POST body: {}", traceTag, body);
        Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
        return getWebClient() //
                .flatMap(client -> {
                    RequestHeadersSpec<?> request = client.post() //
                            .uri(uri) //
                            .contentType(MediaType.APPLICATION_JSON) //
                            .body(bodyProducer, String.class);
                    return retrieve(traceTag, request);
                });
    }

    public Mono<String> post(String uri, @Nullable String body) {
        return postForEntity(uri, body) //
                .flatMap(this::toBody);
    }

    public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
        Object traceTag = createTraceTag();
        logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
        logger.trace("{} POST body: {}", traceTag, body);
        return getWebClient() //
                .flatMap(client -> {
                    RequestHeadersSpec<?> request = client.post() //
                            .uri(uri) //
                            .headers(headers -> headers.setBasicAuth(username, password)) //
                            .contentType(MediaType.APPLICATION_JSON) //
                            .bodyValue(body);
                    return retrieve(traceTag, request) //
                            .flatMap(this::toBody);
                });
    }

    public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
        Object traceTag = createTraceTag();
        logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
        logger.trace("{} PUT body: {}", traceTag, body);
        return getWebClient() //
                .flatMap(client -> {
                    RequestHeadersSpec<?> request = client.put() //
                            .uri(uri) //
                            .contentType(MediaType.APPLICATION_JSON) //
                            .bodyValue(body);
                    return retrieve(traceTag, request);
                });
    }

    public Mono<ResponseEntity<String>> putForEntity(String uri) {
        Object traceTag = createTraceTag();
        logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
        logger.trace("{} PUT body: <empty>", traceTag);
        return getWebClient() //
                .flatMap(client -> {
                    RequestHeadersSpec<?> request = client.put() //
                            .uri(uri);
                    return retrieve(traceTag, request);
                });
    }

    public Mono<String> put(String uri, String body) {
        return putForEntity(uri, body) //
                .flatMap(this::toBody);
    }

    public Mono<ResponseEntity<String>> getForEntity(String uri) {
        Object traceTag = createTraceTag();
        logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
        return getWebClient() //
                .flatMap(client -> {
                    RequestHeadersSpec<?> request = client.get().uri(uri);
                    return retrieve(traceTag, request);
                });
    }

    public Mono<String> get(String uri) {
        return getForEntity(uri) //
                .flatMap(this::toBody);
    }

    public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
        Object traceTag = createTraceTag();
        logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
        return getWebClient() //
                .flatMap(client -> {
                    RequestHeadersSpec<?> request = client.delete().uri(uri);
                    return retrieve(traceTag, request);
                });
    }

    public Mono<String> delete(String uri) {
        return deleteForEntity(uri) //
                .flatMap(this::toBody);
    }

    private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
        final Class<String> clazz = String.class;
        return request.retrieve() //
                .toEntity(clazz) //
                .doOnNext(entity -> logReceivedData(traceTag, entity)) //
                .doOnError(throwable -> onHttpError(traceTag, throwable));
    }

    private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
        logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
    }

    private static Object createTraceTag() {
        return sequenceNumber.incrementAndGet();
    }

    private void onHttpError(Object traceTag, Throwable t) {
        if (t instanceof WebClientResponseException) {
            WebClientResponseException exception = (WebClientResponseException) t;
            logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
                    exception.getResponseBodyAsString());
        } else {
            logger.debug("{} HTTP error {}", traceTag, t.getMessage());
        }
    }

    private Mono<String> toBody(ResponseEntity<String> entity) {
        if (entity.getBody() == null) {
            return Mono.just("");
        } else {
            return Mono.just(entity.getBody());
        }
    }

    private boolean isHttpProxyConfigured() {
        return httpProxyConfig != null && httpProxyConfig.httpProxyPort() > 0
                && !httpProxyConfig.httpProxyHost().isEmpty();
    }

    private HttpClient buildHttpClient() {
        HttpClient httpClient = HttpClient.create() //
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
                .doOnConnected(connection -> {
                    connection.addHandlerLast(new ReadTimeoutHandler(30));
                    connection.addHandlerLast(new WriteTimeoutHandler(30));
                });

        if (this.sslContext != null) {
            httpClient = httpClient.secure(ssl -> ssl.sslContext(sslContext));
        }

        if (isHttpProxyConfigured()) {
            httpClient = httpClient.proxy(proxy -> proxy.type(httpProxyConfig.httpProxyType()) //
                    .host(httpProxyConfig.httpProxyHost()) //
                    .port(httpProxyConfig.httpProxyPort()));
        }
        return httpClient;
    }

    private WebClient buildWebClient(String baseUrl) {
        final HttpClient httpClient = buildHttpClient();
        ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
                .build();
        return WebClient.builder() //
                .clientConnector(new ReactorClientHttpConnector(httpClient)) //
                .baseUrl(baseUrl) //
                .exchangeStrategies(exchangeStrategies) //
                .build();
    }

    private Mono<WebClient> getWebClient() {
        if (this.webClient == null) {
            this.webClient = buildWebClient(baseUrl);
        }
        return Mono.just(buildWebClient(baseUrl));
    }

}