[BUG] Remove slow validation check during module search (CPS-2190 #2)
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / client / DmiRestClient.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2023 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.impl.client;
23
24 import com.fasterxml.jackson.databind.JsonNode;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.util.Locale;
28 import lombok.RequiredArgsConstructor;
29 import lombok.extern.slf4j.Slf4j;
30 import org.onap.cps.ncmp.api.impl.config.DmiWebClientConfiguration.DmiProperties;
31 import org.onap.cps.ncmp.api.impl.exception.HttpClientRequestException;
32 import org.onap.cps.ncmp.api.impl.operations.OperationType;
33 import org.springframework.http.HttpHeaders;
34 import org.springframework.http.ResponseEntity;
35 import org.springframework.stereotype.Component;
36 import org.springframework.web.client.HttpStatusCodeException;
37 import org.springframework.web.reactive.function.BodyInserters;
38 import org.springframework.web.reactive.function.client.WebClient;
39
40 @Component
41 @RequiredArgsConstructor
42 @Slf4j
43 public class DmiRestClient {
44     private static final String HEALTH_CHECK_URL_EXTENSION = "/actuator/health";
45     private static final String NOT_SPECIFIED = "";
46     private static final String NO_AUTHORIZATION = null;
47     private final WebClient webClient;
48     private final DmiProperties dmiProperties;
49
50     /**
51      * Sends POST operation to DMI with json body containing module references.
52      *
53      * @param dmiResourceUrl          dmi resource url
54      * @param requestBodyAsJsonString json data body
55      * @param operationType           the type of operation being executed (for error reporting only)
56      * @param authorization           contents of Authorization header, or null if not present
57      * @return response entity of type String
58      */
59     public ResponseEntity<Object> postOperationWithJsonData(final String dmiResourceUrl,
60                                                             final String requestBodyAsJsonString,
61                                                             final OperationType operationType,
62                                                             final String authorization) {
63         try {
64             return webClient.post().uri(new URI(dmiResourceUrl))
65                     .headers(httpHeaders -> configureHttpHeaders(httpHeaders, authorization))
66                     .body(BodyInserters.fromValue(requestBodyAsJsonString))
67                     .retrieve()
68                     .toEntity(Object.class)
69                     .block();
70         } catch (final HttpStatusCodeException httpStatusCodeException) {
71             final String exceptionMessage = "Unable to " + operationType.toString() + " resource data.";
72             throw new HttpClientRequestException(exceptionMessage, httpStatusCodeException.getResponseBodyAsString(),
73                     httpStatusCodeException.getStatusCode().value());
74         } catch (final URISyntaxException ex) {
75             throw new RuntimeException(ex);
76         }
77     }
78
79     /**
80      * Get DMI plugin health status.
81      *
82      * @param       dmiPluginBaseUrl the base URL of the dmi-plugin
83      * @return      plugin health status ("UP" is all OK, "" (not-specified) in case of any exception)
84      */
85     public String getDmiHealthStatus(final String dmiPluginBaseUrl) {
86         try {
87             final JsonNode responseHealthStatus = webClient.get()
88                     .uri(new URI(dmiPluginBaseUrl + HEALTH_CHECK_URL_EXTENSION))
89                     .headers(httpHeaders -> configureHttpHeaders(httpHeaders, NO_AUTHORIZATION))
90                     .retrieve()
91                     .bodyToMono(JsonNode.class).block();
92             return responseHealthStatus == null ? NOT_SPECIFIED :
93                     responseHealthStatus.get("status").asText();
94         } catch (final Exception e) {
95             log.warn("Failed to retrieve health status from {}. Error Message: {}", dmiPluginBaseUrl, e.getMessage());
96             return NOT_SPECIFIED;
97         }
98     }
99
100     private HttpHeaders configureHttpHeaders(final HttpHeaders httpHeaders, final String authorization) {
101         if (dmiProperties.isDmiBasicAuthEnabled()) {
102             httpHeaders.setBasicAuth(dmiProperties.getAuthUsername(), dmiProperties.getAuthPassword());
103         } else if (authorization != null && authorization.toLowerCase(Locale.getDefault()).startsWith("bearer ")) {
104             httpHeaders.add(HttpHeaders.AUTHORIZATION, authorization);
105         }
106         return httpHeaders;
107     }
108 }