563daecd9df932a140028479d650d62371f5beca
[policy/clamp.git] /
1 /*-
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
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.Map;
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.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;
42
43 public class AcHttpClient implements Runnable {
44
45     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
46
47     private final ConfigRequest configRequest;
48
49     private Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap;
50
51     /**
52      * Constructor.
53      */
54     public AcHttpClient(ConfigRequest configRequest, Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap) {
55         this.configRequest = configRequest;
56         this.responseMap = responseMap;
57     }
58
59     /**
60      * Runnable to execute http requests.
61      */
62     @Override
63     public void run() {
64
65         var webClient = WebClient.builder()
66             .baseUrl(configRequest.getBaseUrl())
67             .defaultHeaders(httpHeaders -> httpHeaders.addAll(createHeaders(configRequest)))
68             .build();
69
70         for (ConfigurationEntity configurationEntity : configRequest.getConfigurationEntities()) {
71             LOGGER.info("Executing http requests for the config entity {}",
72                 configurationEntity.getConfigurationEntityId());
73
74             executeRequest(webClient, configurationEntity);
75         }
76     }
77
78     private void executeRequest(WebClient client, ConfigurationEntity configurationEntity)  {
79
80         // Iterate the sequence of http requests
81         for (RestParams request: configurationEntity.getRestSequence()) {
82             String response = null;
83             try {
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());
88
89                 response = client.method(httpMethod)
90                     .uri(uri)
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));
99
100                 LOGGER.info("HTTP response for the {} request : {}", httpMethod, response);
101                 responseMap.put(request.getRestRequestId(), new ImmutablePair<>(request.getExpectedResponse(),
102                     response));
103
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()));
108             }
109         }
110     }
111
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());
116         }
117         return headers;
118     }
119
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());
125         }
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());
130             }
131         }
132         return uriComponentsBuilder.build().toUriString();
133     }
134
135 }