66ca1b31a7fa7ab79920f0160bbbc895408538ad
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021,2023 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.http.main.webclient;
22
23 import java.lang.invoke.MethodHandles;
24 import java.time.Duration;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Objects;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.apache.commons.lang3.tuple.Pair;
30 import org.onap.policy.clamp.acm.participant.http.main.exception.HttpWebClientException;
31 import org.onap.policy.clamp.acm.participant.http.main.models.ConfigRequest;
32 import org.onap.policy.clamp.acm.participant.http.main.models.ConfigurationEntity;
33 import org.onap.policy.clamp.acm.participant.http.main.models.RestParams;
34 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.http.HttpHeaders;
38 import org.springframework.http.HttpMethod;
39 import org.springframework.stereotype.Component;
40 import org.springframework.web.reactive.function.BodyInserters;
41 import org.springframework.web.reactive.function.client.WebClient;
42 import org.springframework.web.reactive.function.client.WebClientRequestException;
43 import org.springframework.web.util.UriComponentsBuilder;
44 import reactor.core.publisher.Mono;
45
46 @Component
47 public class AcHttpClient {
48
49     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
50
51     /**
52      * Runnable to execute http requests.
53      */
54     public Map<ToscaConceptIdentifier, Pair<Integer, String>> run(ConfigRequest configRequest) {
55
56         var webClient = WebClient.builder().baseUrl(configRequest.getBaseUrl())
57                 .defaultHeaders(httpHeaders -> httpHeaders.addAll(createHeaders(configRequest))).build();
58
59         Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap = new HashMap<>();
60         for (var configurationEntity : configRequest.getConfigurationEntities()) {
61             LOGGER.info("Executing http requests for the config entity {}",
62                     configurationEntity.getConfigurationEntityId());
63
64             responseMap.putAll(executeRequest(webClient, configRequest, configurationEntity));
65         }
66         return responseMap;
67     }
68
69     private Map<ToscaConceptIdentifier, Pair<Integer, String>> executeRequest(WebClient client,
70             ConfigRequest configRequest, ConfigurationEntity configurationEntity) {
71
72         Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap = new HashMap<>();
73         // Iterate the sequence of http requests
74         for (var request : configurationEntity.getRestSequence()) {
75             try {
76                 var httpMethod = Objects.requireNonNull(HttpMethod.resolve(request.getHttpMethod()));
77                 var uri = createUriString(request);
78                 LOGGER.info("Executing HTTP request: {} for the Rest request id: {}", httpMethod,
79                         request.getRestRequestId());
80
81                 var response = client.method(httpMethod).uri(uri)
82                         .body(request.getBody() == null ? BodyInserters.empty()
83                                 : BodyInserters.fromValue(request.getBody()))
84                         .exchangeToMono(
85                                 clientResponse -> clientResponse.statusCode().value() == request.getExpectedResponse()
86                                         ? clientResponse.bodyToMono(String.class)
87                                         : Mono.error(new HttpWebClientException(clientResponse.statusCode().value(),
88                                                 clientResponse.bodyToMono(String.class).toString())))
89                         .block(Duration.ofMillis(configRequest.getUninitializedToPassiveTimeout() * 1000L));
90
91                 LOGGER.info("HTTP response for the {} request : {}", httpMethod, response);
92                 responseMap.put(request.getRestRequestId(),
93                         new ImmutablePair<>(request.getExpectedResponse(), response));
94
95             } catch (HttpWebClientException ex) {
96                 LOGGER.error("Error occurred on the HTTP response ", ex);
97                 responseMap.put(request.getRestRequestId(),
98                         new ImmutablePair<>(ex.getStatusCode().value(), ex.getResponseBodyAsString()));
99             } catch (WebClientRequestException | IllegalStateException ex) {
100                 LOGGER.error("Error occurred on the HTTP request ", ex);
101                 responseMap.put(request.getRestRequestId(), new ImmutablePair<>(404, ex.getMessage()));
102             }
103         }
104         return responseMap;
105     }
106
107     private HttpHeaders createHeaders(ConfigRequest request) {
108         var headers = new HttpHeaders();
109         for (var entry : request.getHttpHeaders().entrySet()) {
110             headers.add(entry.getKey(), entry.getValue());
111         }
112         return headers;
113     }
114
115     private String createUriString(RestParams restParams) {
116         var uriComponentsBuilder = UriComponentsBuilder.fromUriString(restParams.getPath());
117         // Add path params if present
118         if (restParams.getPathParams() != null) {
119             uriComponentsBuilder.uriVariables(restParams.getPathParams());
120         }
121         // Add query params if present
122         if (restParams.getQueryParams() != null) {
123             for (var entry : restParams.getQueryParams().entrySet()) {
124                 uriComponentsBuilder.queryParam(entry.getKey(), entry.getValue());
125             }
126         }
127         return uriComponentsBuilder.build().toUriString();
128     }
129
130 }