25fb67fb76b3693358718c846694ffcf876749b7
[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 reactor.core.publisher.Mono;
40
41 @Component
42 @RequiredArgsConstructor
43 public class AcA1PmsClient {
44
45     private final A1PmsParameters a1PmsParameters;
46
47     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
48
49     /**
50      * Get webclient for A1PMS.
51      *
52      * @return webClient
53      */
54     private WebClient getPmsClient() {
55         return WebClient.builder().baseUrl(a1PmsParameters.getBaseUrl())
56                        .defaultHeaders(httpHeaders -> httpHeaders.addAll(createHeaders())).build();
57     }
58
59     /**
60      * Get A1PMS health status.
61      *
62      * @return whether A1PMS is healthy
63      */
64     public boolean isPmsHealthy() {
65         return Objects.equals(Boolean.TRUE,
66                 getPmsClient().method(HttpMethod.GET).uri(a1PmsParameters.getEndpoints().getHealth())
67                         .exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode().is2xxSuccessful()))
68                         .block());
69     }
70
71
72     /**
73      * Create service in A1PMS.
74      * @param policyServiceEntities List of service entities
75      * @throws A1PolicyServiceException Exception on creating service
76      */
77     public void createService(List<A1PolicyServiceEntity> policyServiceEntities) throws A1PolicyServiceException {
78         policyServiceEntities.forEach(
79                 a1PolicyServiceEntity -> getPmsClient().method(HttpMethod.PUT)
80                                            .uri(a1PmsParameters.getEndpoints().getServices())
81                                            .bodyValue(a1PolicyServiceEntity).retrieve()
82                                            .onStatus(HttpStatus::isError,
83                                                    clientResponse -> Mono.error(new A1PolicyServiceException(
84                                                                    clientResponse.statusCode().value(),
85                                                                    "Error in creating policy service")))
86                                            .onStatus(Predicate.isEqual(HttpStatus.OK),
87                                                    clientResponse -> {
88                                                        LOGGER.warn("Client {} already exists and the configuration "
89                                                                            + "is updated",
90                                                                a1PolicyServiceEntity.getClientId());
91                                                        return Mono.empty();
92                                                    })
93                                            .toBodilessEntity()
94                                            .block());
95     }
96
97     /**
98      * Delete service in A1PMS.
99      * @param policyServiceEntities List of service entities
100      * @throws A1PolicyServiceException Exception on deleting service
101      */
102     public void deleteService(List<A1PolicyServiceEntity> policyServiceEntities) throws A1PolicyServiceException {
103         policyServiceEntities.forEach(
104                 a1PolicyServiceEntity -> getPmsClient().method(HttpMethod.DELETE)
105                                              .uri(a1PmsParameters.getEndpoints().getService(),
106                                                      a1PolicyServiceEntity.getClientId())
107                                              .bodyValue(a1PolicyServiceEntity).retrieve()
108                                              .onStatus(HttpStatus::isError,
109                                                      clientResponse -> Mono.error(
110                                                              new A1PolicyServiceException(
111                                                                      clientResponse.statusCode().value(),
112                                                                      "Error in deleting policy service")))
113                                              .toBodilessEntity()
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 }