131551e5b9be949c3b414e7b057d486bca87768b
[dcaegen2/services.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * BBS-RELOCATION-CPE-AUTHENTICATION-HANDLER
4  * ================================================================================
5  * Copyright (C) 2019 NOKIA Intellectual Property. 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
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.onap.bbs.event.processor.utilities;
22
23 import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;
24
25 import com.google.gson.Gson;
26 import com.google.gson.JsonSyntaxException;
27
28 import io.netty.handler.ssl.SslContext;
29
30 import javax.annotation.PostConstruct;
31 import javax.annotation.PreDestroy;
32 import javax.net.ssl.SSLException;
33
34 import org.onap.bbs.event.processor.config.AaiClientConfiguration;
35 import org.onap.bbs.event.processor.config.ApplicationConfiguration;
36 import org.onap.bbs.event.processor.config.ConfigurationChangeObserver;
37 import org.onap.bbs.event.processor.exceptions.AaiTaskException;
38 import org.onap.bbs.event.processor.model.PnfAaiObject;
39 import org.onap.bbs.event.processor.model.ServiceInstanceAaiObject;
40 import org.onap.dcaegen2.services.sdk.rest.services.ssl.SslFactory;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.http.HttpStatus;
45 import org.springframework.http.client.reactive.ClientHttpConnector;
46 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
47 import org.springframework.stereotype.Component;
48 import org.springframework.web.reactive.function.client.ClientResponse;
49 import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
50 import org.springframework.web.reactive.function.client.WebClient;
51
52 import reactor.core.publisher.Mono;
53 import reactor.netty.http.client.HttpClient;
54
55 @Component
56 public class AaiReactiveClient implements ConfigurationChangeObserver {
57
58     private static final Logger LOGGER = LoggerFactory.getLogger(AaiReactiveClient.class);
59
60     private final Gson gson;
61     private WebClient webClient;
62     private SslFactory sslFactory;
63     private final ApplicationConfiguration configuration;
64     private AaiClientConfiguration aaiClientConfiguration;
65
66     @Autowired
67     AaiReactiveClient(ApplicationConfiguration configuration, Gson gson) throws SSLException {
68         this.configuration = configuration;
69         this.gson = gson;
70         this.sslFactory = new SslFactory();
71
72         aaiClientConfiguration = configuration.getAaiClientConfiguration();
73         setupWebClient();
74     }
75
76     @PostConstruct
77     public void registerForConfigChanges() {
78         configuration.register(this);
79     }
80
81     @PreDestroy
82     public void unRegisterForConfigChanges() {
83         configuration.unRegister(this);
84     }
85
86     @Override
87     public void updateConfiguration(ApplicationConfiguration configuration) {
88         AaiClientConfiguration newConfiguration = configuration.getAaiClientConfiguration();
89         if (aaiClientConfiguration.equals(newConfiguration)) {
90             LOGGER.debug("No Configuration changes necessary for AAI Reactive client");
91         } else {
92             LOGGER.debug("AAI Reactive client must be re-configured");
93             aaiClientConfiguration = newConfiguration;
94             try {
95                 setupWebClient();
96             } catch (SSLException e) {
97                 LOGGER.error("AAI Reactive client error while re-configuring WebClient");
98             }
99         }
100     }
101
102     private synchronized void setupWebClient() throws SSLException {
103         SslContext sslContext = createSslContext();
104
105         ClientHttpConnector reactorClientHttpConnector = new ReactorClientHttpConnector(
106                 HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)));
107
108         this.webClient = WebClient.builder()
109                 .baseUrl(aaiClientConfiguration.aaiProtocol() + "://" + aaiClientConfiguration.aaiHost()
110                         + ":" + aaiClientConfiguration.aaiPort())
111                 .clientConnector(reactorClientHttpConnector)
112                 .defaultHeaders(httpHeaders -> httpHeaders.setAll(aaiClientConfiguration.aaiHeaders()))
113                 .filter(basicAuthentication(aaiClientConfiguration.aaiUserName(),
114                         aaiClientConfiguration.aaiUserPassword()))
115                 .filter(logRequest())
116                 .filter(logResponse())
117                 .build();
118     }
119
120     public Mono<PnfAaiObject> getPnfObjectDataFor(String url) {
121
122         return performReactiveHttpGet(url, PnfAaiObject.class);
123     }
124
125     public Mono<ServiceInstanceAaiObject> getServiceInstanceObjectDataFor(String url) {
126
127         return performReactiveHttpGet(url, ServiceInstanceAaiObject.class);
128     }
129
130     private synchronized <T> Mono<T> performReactiveHttpGet(String url, Class<T> responseType) {
131         LOGGER.debug("Will issue Reactive GET request to URL ({}) for object ({})", url, responseType.getName());
132         return webClient
133                 .get()
134                 .uri(url)
135                 .retrieve()
136                 .onStatus(HttpStatus::is4xxClientError,
137                     response -> Mono.error(createExceptionObject(url, response)))
138                 .onStatus(HttpStatus::is5xxServerError,
139                     response -> Mono.error(createExceptionObject(url, response)))
140                 .bodyToMono(String.class)
141                 .flatMap(body -> extractMono(body, responseType));
142     }
143
144     private AaiTaskException createExceptionObject(String url, ClientResponse response) {
145         return new AaiTaskException(String.format("A&AI Request for (%s) failed with HTTP status code %d", url,
146                 response.statusCode().value()));
147     }
148
149     private <T> Mono<T> extractMono(String body, Class<T> responseType) {
150         LOGGER.debug("Response body \n{}", body);
151         try {
152             return Mono.just(parseFromJsonReply(body, responseType));
153         } catch (JsonSyntaxException | IllegalStateException e) {
154             return Mono.error(e);
155         }
156     }
157
158     private <T> T parseFromJsonReply(String body, Class<T> responseType) {
159         return gson.fromJson(body, responseType);
160     }
161
162     private static ExchangeFilterFunction logRequest() {
163         return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
164             LOGGER.debug("Request: {} {}", clientRequest.method(), clientRequest.url());
165             clientRequest.headers()
166                     .forEach((name, values) -> values.forEach(value -> LOGGER.debug("{}={}", name, value)));
167             return Mono.just(clientRequest);
168         });
169     }
170
171     private static ExchangeFilterFunction logResponse() {
172         return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
173             LOGGER.debug("Response status {}", clientResponse.statusCode());
174             return Mono.just(clientResponse);
175         });
176     }
177
178     private SslContext createSslContext() throws SSLException {
179         if (aaiClientConfiguration.enableAaiCertAuth()) {
180             return sslFactory.createSecureContext(
181                     aaiClientConfiguration.keyStorePath(),
182                     aaiClientConfiguration.keyStorePasswordPath(),
183                     aaiClientConfiguration.trustStorePath(),
184                     aaiClientConfiguration.trustStorePasswordPath()
185             );
186         }
187         return sslFactory.createInsecureContext();
188     }
189 }