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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.clamp.acm.participant.http.main.webclient;
23 import java.lang.invoke.MethodHandles;
24 import java.time.Duration;
26 import java.util.Objects;
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.apache.commons.lang3.tuple.Pair;
29 import org.onap.policy.clamp.acm.participant.http.main.exception.HttpWebClientException;
30 import org.onap.policy.clamp.acm.participant.http.main.models.ConfigRequest;
31 import org.onap.policy.clamp.acm.participant.http.main.models.ConfigurationEntity;
32 import org.onap.policy.clamp.acm.participant.http.main.models.RestParams;
33 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.HttpMethod;
38 import org.springframework.stereotype.Component;
39 import org.springframework.web.reactive.function.BodyInserters;
40 import org.springframework.web.reactive.function.client.WebClient;
41 import org.springframework.web.reactive.function.client.WebClientRequestException;
42 import org.springframework.web.util.UriComponentsBuilder;
43 import reactor.core.publisher.Mono;
46 public class AcHttpClient {
48 private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
51 * Runnable to execute http requests.
53 public void run(ConfigRequest configRequest, Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap) {
55 var webClient = WebClient.builder().baseUrl(configRequest.getBaseUrl())
56 .defaultHeaders(httpHeaders -> httpHeaders.addAll(createHeaders(configRequest))).build();
58 for (var configurationEntity : configRequest.getConfigurationEntities()) {
59 LOGGER.info("Executing http requests for the config entity {}",
60 configurationEntity.getConfigurationEntityId());
62 executeRequest(webClient, configRequest, configurationEntity, responseMap);
66 private void executeRequest(WebClient client, ConfigRequest configRequest, ConfigurationEntity configurationEntity,
67 Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap) {
69 // Iterate the sequence of http requests
70 for (var request : configurationEntity.getRestSequence()) {
72 var httpMethod = Objects.requireNonNull(HttpMethod.resolve(request.getHttpMethod()));
73 var uri = createUriString(request);
74 LOGGER.info("Executing HTTP request: {} for the Rest request id: {}", httpMethod,
75 request.getRestRequestId());
77 var response = client.method(httpMethod).uri(uri)
78 .body(request.getBody() == null ? BodyInserters.empty()
79 : BodyInserters.fromValue(request.getBody()))
81 clientResponse -> clientResponse.statusCode().value() == request.getExpectedResponse()
82 ? clientResponse.bodyToMono(String.class)
83 : Mono.error(new HttpWebClientException(clientResponse.statusCode().value(),
84 clientResponse.bodyToMono(String.class).toString())))
85 .block(Duration.ofMillis(configRequest.getUninitializedToPassiveTimeout() * 1000L));
87 LOGGER.info("HTTP response for the {} request : {}", httpMethod, response);
88 responseMap.put(request.getRestRequestId(),
89 new ImmutablePair<>(request.getExpectedResponse(), response));
91 } catch (HttpWebClientException ex) {
92 LOGGER.error("Error occurred on the HTTP response ", ex);
93 responseMap.put(request.getRestRequestId(),
94 new ImmutablePair<>(ex.getStatusCode().value(), ex.getResponseBodyAsString()));
95 } catch (WebClientRequestException ex) {
96 LOGGER.error("Error occurred on the HTTP request ", ex);
97 responseMap.put(request.getRestRequestId(), new ImmutablePair<>(404, ex.getMessage()));
102 private HttpHeaders createHeaders(ConfigRequest request) {
103 var headers = new HttpHeaders();
104 for (var entry : request.getHttpHeaders().entrySet()) {
105 headers.add(entry.getKey(), entry.getValue());
110 private String createUriString(RestParams restParams) {
111 var uriComponentsBuilder = UriComponentsBuilder.fromUriString(restParams.getPath());
112 // Add path params if present
113 if (restParams.getPathParams() != null) {
114 uriComponentsBuilder.uriVariables(restParams.getPathParams());
116 // Add query params if present
117 if (restParams.getQueryParams() != null) {
118 for (var entry : restParams.getQueryParams().entrySet()) {
119 uriComponentsBuilder.queryParam(entry.getKey(), entry.getValue());
122 return uriComponentsBuilder.build().toUriString();