4099caa7683ca368cf44013cbf1b11c0786225b2
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.acm.participant.a1pms.webclient;
22
23 import java.lang.invoke.MethodHandles;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Objects;
27 import java.util.function.Predicate;
28 import lombok.RequiredArgsConstructor;
29 import org.onap.policy.clamp.acm.participant.a1pms.exception.A1PolicyServiceException;
30 import org.onap.policy.clamp.acm.participant.a1pms.models.A1PolicyServiceEntity;
31 import org.onap.policy.clamp.acm.participant.a1pms.parameters.A1PmsParameters;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.http.HttpHeaders;
35 import org.springframework.http.HttpMethod;
36 import org.springframework.http.HttpStatus;
37 import org.springframework.stereotype.Component;
38 import org.springframework.web.reactive.function.client.WebClient;
39 import org.springframework.web.reactive.function.client.WebClientResponseException;
40 import reactor.core.publisher.Mono;
41
42 @Component
43 @RequiredArgsConstructor
44 public class AcA1PmsClient {
45
46     private final A1PmsParameters a1PmsParameters;
47
48     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
49
50     /**
51      * Get webclient for A1PMS.
52      *
53      * @return webClient
54      */
55     private WebClient getPmsClient() {
56         return WebClient.builder().baseUrl(a1PmsParameters.getBaseUrl())
57                        .defaultHeaders(httpHeaders -> httpHeaders.addAll(createHeaders())).build();
58     }
59
60     /**
61      * Get A1PMS health status.
62      *
63      * @return whether A1PMS is healthy
64      */
65     public boolean isPmsHealthy() {
66         return Objects.equals(Boolean.TRUE,
67                 getPmsClient().method(HttpMethod.GET).uri(a1PmsParameters.getEndpoints().getHealth())
68                         .exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode().is2xxSuccessful()))
69                         .block());
70     }
71
72
73     /**
74      * Create service in A1PMS.
75      * @param policyServiceEntities List of service entities
76      * @throws A1PolicyServiceException Exception on creating service
77      */
78     public void createService(List<A1PolicyServiceEntity> policyServiceEntities) throws A1PolicyServiceException {
79         policyServiceEntities.forEach(
80                 a1PolicyServiceEntity -> getPmsClient().method(HttpMethod.PUT)
81                                            .uri(a1PmsParameters.getEndpoints().getServices())
82                                            .bodyValue(a1PolicyServiceEntity).retrieve()
83                                            .onStatus(Predicate.isEqual(HttpStatus.OK),
84                                                    clientResponse -> {
85                                                        LOGGER.warn("Client {} already exists and the configuration "
86                                                                            + "is updated",
87                                                                a1PolicyServiceEntity.getClientId());
88                                                        return Mono.empty();
89                                                    })
90                                            .toBodilessEntity()
91                                            .onErrorResume(WebClientResponseException.class,
92                                                    clientResponse -> Mono.error(new A1PolicyServiceException(
93                                                                clientResponse.getStatusCode().value(),
94                                                                "Error in creating policy service")))
95                                            .block());
96     }
97
98     /**
99      * Delete service in A1PMS.
100      * @param policyServiceEntities List of service entities
101      * @throws A1PolicyServiceException Exception on deleting service
102      */
103     public void deleteService(List<A1PolicyServiceEntity> policyServiceEntities) throws A1PolicyServiceException {
104         policyServiceEntities.forEach(
105                 a1PolicyServiceEntity -> getPmsClient().method(HttpMethod.DELETE)
106                                              .uri(a1PmsParameters.getEndpoints().getService(),
107                                                      a1PolicyServiceEntity.getClientId())
108                                              .bodyValue(a1PolicyServiceEntity).retrieve()
109                                              .toBodilessEntity()
110                                             .onErrorResume(WebClientResponseException.class,
111                                                     clientResponse -> Mono.error(new A1PolicyServiceException(
112                                                             clientResponse.getStatusCode().value(),
113                                                             "Error in deleting policy service")))
114                                              .block());
115     }
116
117     /**
118      * Prepare the Http headers to call A1PMS.
119      *
120      * @return httpHeaders
121      */
122     private HttpHeaders createHeaders() {
123         var headers = new HttpHeaders();
124         for (Map.Entry<String, String> entry : a1PmsParameters.getHeaders().entrySet()) {
125             headers.add(entry.getKey(), entry.getValue());
126         }
127         return headers;
128     }
129 }