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
 
  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.onap.bbs.event.processor.utilities;
 
  23 import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;
 
  25 import com.google.gson.Gson;
 
  26 import com.google.gson.JsonSyntaxException;
 
  28 import io.netty.handler.ssl.SslContext;
 
  30 import javax.annotation.PostConstruct;
 
  31 import javax.annotation.PreDestroy;
 
  32 import javax.net.ssl.SSLException;
 
  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;
 
  52 import reactor.core.publisher.Mono;
 
  53 import reactor.netty.http.client.HttpClient;
 
  56 public class AaiReactiveClient implements ConfigurationChangeObserver {
 
  58     private static final Logger LOGGER = LoggerFactory.getLogger(AaiReactiveClient.class);
 
  60     private final Gson gson;
 
  61     private WebClient webClient;
 
  62     private SslFactory sslFactory;
 
  63     private final ApplicationConfiguration configuration;
 
  64     private AaiClientConfiguration aaiClientConfiguration;
 
  67     AaiReactiveClient(ApplicationConfiguration configuration, Gson gson) throws SSLException {
 
  68         this.configuration = configuration;
 
  70         this.sslFactory = new SslFactory();
 
  72         aaiClientConfiguration = configuration.getAaiClientConfiguration();
 
  77     public void registerForConfigChanges() {
 
  78         configuration.register(this);
 
  82     public void unRegisterForConfigChanges() {
 
  83         configuration.unRegister(this);
 
  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");
 
  92             LOGGER.debug("AAI Reactive client must be re-configured");
 
  93             aaiClientConfiguration = newConfiguration;
 
  96             } catch (SSLException e) {
 
  97                 LOGGER.error("AAI Reactive client error while re-configuring WebClient");
 
 102     private synchronized void setupWebClient() throws SSLException {
 
 103         SslContext sslContext = createSslContext();
 
 105         ClientHttpConnector reactorClientHttpConnector = new ReactorClientHttpConnector(
 
 106                 HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)));
 
 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())
 
 120     public Mono<PnfAaiObject> getPnfObjectDataFor(String url) {
 
 122         return performReactiveHttpGet(url, PnfAaiObject.class);
 
 125     public Mono<ServiceInstanceAaiObject> getServiceInstanceObjectDataFor(String url) {
 
 127         return performReactiveHttpGet(url, ServiceInstanceAaiObject.class);
 
 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());
 
 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));
 
 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()));
 
 149     private <T> Mono<T> extractMono(String body, Class<T> responseType) {
 
 150         LOGGER.debug("Response body \n{}", body);
 
 152             return Mono.just(parseFromJsonReply(body, responseType));
 
 153         } catch (JsonSyntaxException | IllegalStateException e) {
 
 154             return Mono.error(e);
 
 158     private <T> T parseFromJsonReply(String body, Class<T> responseType) {
 
 159         return gson.fromJson(body, responseType);
 
 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);
 
 171     private static ExchangeFilterFunction logResponse() {
 
 172         return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
 
 173             LOGGER.debug("Response status {}", clientResponse.statusCode());
 
 174             return Mono.just(clientResponse);
 
 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()
 
 187         return sslFactory.createInsecureContext();