2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 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.controlloop.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.controlloop.participant.http.main.exception.HttpWebClientException;
30 import org.onap.policy.clamp.controlloop.participant.http.main.models.ConfigRequest;
31 import org.onap.policy.clamp.controlloop.participant.http.main.models.ConfigurationEntity;
32 import org.onap.policy.clamp.controlloop.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.web.reactive.function.BodyInserters;
39 import org.springframework.web.reactive.function.client.WebClient;
40 import org.springframework.web.util.UriComponentsBuilder;
41 import reactor.core.publisher.Mono;
43 public class ClHttpClient implements Runnable {
45 private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
47 private final ConfigRequest configRequest;
49 private Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap;
54 public ClHttpClient(ConfigRequest configRequest, Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap) {
55 this.configRequest = configRequest;
56 this.responseMap = responseMap;
60 * Runnable to execute http requests.
65 var webClient = WebClient.builder()
66 .baseUrl(configRequest.getBaseUrl())
67 .defaultHeaders(httpHeaders -> httpHeaders.addAll(createHeaders(configRequest)))
70 for (ConfigurationEntity configurationEntity : configRequest.getConfigurationEntities()) {
71 LOGGER.info("Executing http requests for the config entity {}",
72 configurationEntity.getConfigurationEntityId());
74 executeRequest(webClient, configurationEntity);
78 private void executeRequest(WebClient client, ConfigurationEntity configurationEntity) {
80 // Iterate the sequence of http requests
81 for (RestParams request: configurationEntity.getRestSequence()) {
82 String response = null;
84 var httpMethod = Objects.requireNonNull(HttpMethod.resolve(request.getHttpMethod()));
85 var uri = createUriString(request);
86 LOGGER.info("Executing HTTP request: {} for the Rest request id: {}", httpMethod,
87 request.getRestRequestId());
89 response = client.method(httpMethod)
91 .body(request.getBody() == null ? BodyInserters.empty()
92 : BodyInserters.fromValue(request.getBody()))
93 .exchangeToMono(clientResponse ->
94 clientResponse.statusCode().value() == request.getExpectedResponse()
95 ? clientResponse.bodyToMono(String.class)
96 : Mono.error(new HttpWebClientException(clientResponse.statusCode().value(),
97 clientResponse.bodyToMono(String.class).toString())))
98 .block(Duration.ofMillis(configRequest.getUninitializedToPassiveTimeout() * 1000L));
100 LOGGER.info("HTTP response for the {} request : {}", httpMethod, response);
101 responseMap.put(request.getRestRequestId(), new ImmutablePair<>(request.getExpectedResponse(),
104 } catch (HttpWebClientException ex) {
105 LOGGER.error("Error occurred on the HTTP request ", ex);
106 responseMap.put(request.getRestRequestId(), new ImmutablePair<>(ex.getStatusCode().value(),
107 ex.getResponseBodyAsString()));
112 private HttpHeaders createHeaders(ConfigRequest request) {
113 var headers = new HttpHeaders();
114 for (Map.Entry<String, String> entry: request.getHttpHeaders().entrySet()) {
115 headers.add(entry.getKey(), entry.getValue());
120 private String createUriString(RestParams restParams) {
121 var uriComponentsBuilder = UriComponentsBuilder.fromUriString(restParams.getPath());
122 // Add path params if present
123 if (restParams.getPathParams() != null) {
124 uriComponentsBuilder.uriVariables(restParams.getPathParams());
126 // Add query params if present
127 if (restParams.getQueryParams() != null) {
128 for (Map.Entry<String, String> entry : restParams.getQueryParams().entrySet()) {
129 uriComponentsBuilder.queryParam(entry.getKey(), entry.getValue());
132 return uriComponentsBuilder.build().toUriString();