Java 17 Upgrade
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / main / java / org / onap / policy / controlloop / actorserviceprovider / impl / HttpOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2023 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controlloop.actorserviceprovider.impl;
23
24 import jakarta.ws.rs.client.InvocationCallback;
25 import jakarta.ws.rs.core.Response;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.concurrent.CompletableFuture;
30 import java.util.concurrent.Future;
31 import java.util.concurrent.TimeUnit;
32 import java.util.function.Function;
33 import lombok.Getter;
34 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
35 import org.onap.policy.common.endpoints.http.client.HttpClient;
36 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
37 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
38 import org.onap.policy.common.utils.coder.CoderException;
39 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
40 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
41 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
42 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
43 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
44 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
45 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * Operator that uses HTTP. The operator's parameters must be an {@link HttpParams}.
51  *
52  * @param <T> response type
53  */
54 @Getter
55 public abstract class HttpOperation<T> extends OperationPartial {
56     private static final Logger logger = LoggerFactory.getLogger(HttpOperation.class);
57
58     /**
59      * Response status.
60      */
61     public enum Status {
62         SUCCESS, FAILURE, STILL_WAITING
63     }
64
65     /**
66      * Configuration for this operation.
67      */
68     private final HttpConfig config;
69
70     /**
71      * Response class.
72      */
73     private final Class<T> responseClass;
74
75     /**
76      * {@code True} to use polling, {@code false} otherwise.
77      */
78     @Getter
79     private boolean usePolling;
80
81     /**
82      * Number of polls issued so far, on the current operation attempt.
83      */
84     @Getter
85     private int pollCount;
86
87
88     /**
89      * Constructs the object.
90      *
91      * @param params operation parameters
92      * @param config configuration for this operation
93      * @param clazz response class
94      * @param propertyNames names of properties required by this operation
95      */
96     protected HttpOperation(ControlLoopOperationParams params, HttpConfig config, Class<T> clazz,
97                     List<String> propertyNames) {
98         super(params, config, propertyNames);
99         this.config = config;
100         this.responseClass = clazz;
101     }
102
103     /**
104      * Indicates that polling should be used.
105      */
106     protected void setUsePolling() {
107         if (!(config instanceof HttpPollingConfig)) {
108             throw new IllegalStateException("cannot poll without polling parameters");
109         }
110
111         usePolling = true;
112     }
113
114     public HttpClient getClient() {
115         return config.getClient();
116     }
117
118     /**
119      * Gets the path to be used when performing the request; this is typically appended to
120      * the base URL. This method simply invokes {@link #getPath()}.
121      *
122      * @return the path URI suffix
123      */
124     public String getPath() {
125         return config.getPath();
126     }
127
128     public long getTimeoutMs() {
129         return config.getTimeoutMs();
130     }
131
132     /**
133      * If no timeout is specified, then it returns the operator's configured timeout.
134      */
135     @Override
136     protected long getTimeoutMs(Integer timeoutSec) {
137         return (timeoutSec == null || timeoutSec == 0 ? getTimeoutMs() : super.getTimeoutMs(timeoutSec));
138     }
139
140     /**
141      * Makes the request headers. This simply returns an empty map.
142      *
143      * @return request headers, a non-null, modifiable map
144      */
145     protected Map<String, Object> makeHeaders() {
146         return new HashMap<>();
147     }
148
149     /**
150      * Makes the URL to which the HTTP request should be posted. This is primarily used
151      * for logging purposes. This particular method returns the base URL appended with the
152      * return value from {@link #getPath()}.
153      *
154      * @return the URL to which from which to get
155      */
156     public String getUrl() {
157         return (getClient().getBaseUrl() + getPath());
158     }
159
160     /**
161      * Resets the polling count
162      *
163      * <p/>
164      * Note: This should be invoked at the start of each operation (i.e., in
165      * {@link #startOperationAsync(int, OperationOutcome)}.
166      */
167     protected void resetPollCount() {
168         pollCount = 0;
169     }
170
171     /**
172      * Arranges to handle a response.
173      *
174      * @param outcome outcome to be populate
175      * @param url URL to which to request was sent
176      * @param requester function to initiate the request and invoke the given callback
177      *        when it completes
178      * @return a future for the response
179      */
180     protected CompletableFuture<OperationOutcome> handleResponse(OperationOutcome outcome, String url,
181                     Function<InvocationCallback<Response>, Future<Response>> requester) {
182
183         final PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
184         final CompletableFuture<Response> future = new CompletableFuture<>();
185         final var executor = params.getExecutor();
186
187         // arrange for the callback to complete "future"
188         InvocationCallback<Response> callback = new InvocationCallback<>() {
189             @Override
190             public void completed(Response response) {
191                 future.complete(response);
192             }
193
194             @Override
195             public void failed(Throwable throwable) {
196                 logger.warn("{}.{}: response failure for {}", params.getActor(), params.getOperation(),
197                                 params.getRequestId());
198                 future.completeExceptionally(throwable);
199             }
200         };
201
202         // start the request and arrange to cancel it if the controller is canceled
203         controller.add(requester.apply(callback));
204
205         // once "future" completes, process the response, and then complete the controller
206         future.thenComposeAsync(response -> processResponse(outcome, url, response), executor)
207                         .whenCompleteAsync(controller.delayedComplete(), executor);
208
209         return controller;
210     }
211
212     /**
213      * Processes a response. This method decodes the response, sets the outcome based on
214      * the response, and then returns a completed future.
215      *
216      * @param outcome outcome to be populate
217      * @param url URL to which to request was sent
218      * @param rawResponse raw response to process
219      * @return a future to cancel or await the outcome
220      */
221     protected CompletableFuture<OperationOutcome> processResponse(OperationOutcome outcome, String url,
222                     Response rawResponse) {
223
224         logger.info("{}.{}: response received for {}", params.getActor(), params.getOperation(), params.getRequestId());
225
226         String strResponse = rawResponse.readEntity(String.class);
227
228         logMessage(EventType.IN, CommInfrastructure.REST, url, strResponse);
229
230         T response;
231         if (responseClass == String.class) {
232             response = responseClass.cast(strResponse);
233         } else {
234             try {
235                 response = getCoder().decode(strResponse, responseClass);
236             } catch (CoderException e) {
237                 logger.warn("{}.{} cannot decode response for {}", params.getActor(), params.getOperation(),
238                                 params.getRequestId(), e);
239                 throw new IllegalArgumentException("cannot decode response");
240             }
241         }
242
243         if (!isSuccess(rawResponse, response)) {
244             logger.info("{}.{} request failed with http error code {} for {}", params.getActor(), params.getOperation(),
245                             rawResponse.getStatus(), params.getRequestId());
246             return CompletableFuture.completedFuture(
247                     setOutcome(outcome, OperationResult.FAILURE, rawResponse, response));
248         }
249
250         logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(), params.getRequestId());
251         setOutcome(outcome, OperationResult.SUCCESS, rawResponse, response);
252         return postProcessResponse(outcome, url, rawResponse, response);
253     }
254
255     /**
256      * Sets an operation's outcome and default message based on the result.
257      *
258      * @param outcome operation to be updated
259      * @param result result of the operation
260      * @param rawResponse raw response
261      * @param response decoded response
262      * @return the updated operation
263      */
264     public OperationOutcome setOutcome(OperationOutcome outcome, OperationResult result, Response rawResponse,
265                     T response) {
266
267         outcome.setResponse(response);
268         return setOutcome(outcome, result);
269     }
270
271     /**
272      * Processes a successful response. This method simply returns the outcome wrapped in
273      * a completed future.
274      *
275      * @param outcome outcome to be populate
276      * @param url URL to which to request was sent
277      * @param rawResponse raw response
278      * @param response decoded response
279      * @return a future to cancel or await the outcome
280      */
281     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
282                     Response rawResponse, T response) {
283
284         if (!usePolling) {
285             // doesn't use polling - just return the completed future
286             return CompletableFuture.completedFuture(outcome);
287         }
288
289         HttpPollingConfig cfg = (HttpPollingConfig) config;
290
291         switch (detmStatus(rawResponse, response)) {
292             case SUCCESS -> {
293                 logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(),
294                     params.getRequestId());
295                 return CompletableFuture
296                     .completedFuture(setOutcome(outcome, OperationResult.SUCCESS, rawResponse, response));
297             }
298             case FAILURE -> {
299                 logger.info("{}.{} request failed for {}", params.getActor(), params.getOperation(),
300                     params.getRequestId());
301                 return CompletableFuture
302                     .completedFuture(setOutcome(outcome, OperationResult.FAILURE, rawResponse, response));
303             }
304             default -> logger.info("{}.{} request incomplete for {}", params.getActor(), params.getOperation(),
305                 params.getRequestId());
306         }
307
308         // still incomplete
309
310         // see if the limit for the number of polls has been reached
311         if (pollCount++ >= cfg.getMaxPolls()) {
312             logger.warn("{}: exceeded 'poll' limit {} for {}", getFullName(), cfg.getMaxPolls(),
313                             params.getRequestId());
314             setOutcome(outcome, OperationResult.FAILURE_TIMEOUT);
315             return CompletableFuture.completedFuture(outcome);
316         }
317
318         // sleep and then poll
319         Function<Void, CompletableFuture<OperationOutcome>> doPoll = unused -> issuePoll(outcome);
320         return sleep(getPollWaitMs(), TimeUnit.MILLISECONDS).thenComposeAsync(doPoll);
321     }
322
323     /**
324      * Polls to see if the original request is complete. This method polls using an HTTP
325      * "get" request whose URL is constructed by appending the extracted "poll ID" to the
326      * poll path from the configuration data.
327      *
328      * @param outcome outcome to be populated with the response
329      * @return a future that can be used to cancel the poll or await its response
330      */
331     protected CompletableFuture<OperationOutcome> issuePoll(OperationOutcome outcome) {
332         String path = getPollingPath();
333         String url = getClient().getBaseUrl() + path;
334
335         logger.debug("{}: 'poll' count {} for {}", getFullName(), pollCount, params.getRequestId());
336
337         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
338
339         return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
340     }
341
342     /**
343      * Determines the status of the response. This particular method simply throws an
344      * exception.
345      *
346      * @param rawResponse raw response
347      * @param response decoded response
348      * @return the status of the response
349      */
350     protected Status detmStatus(Response rawResponse, T response) {
351         throw new UnsupportedOperationException("cannot determine response status");
352     }
353
354     /**
355      * Gets the URL to use when polling. Typically, this is some unique ID appended to the
356      * polling path found within the configuration data. This particular method simply
357      * returns the polling path from the configuration data.
358      *
359      * @return the URL to use when polling
360      */
361     protected String getPollingPath() {
362         return ((HttpPollingConfig) config).getPollPath();
363     }
364
365     /**
366      * Determines if the response indicates success. This method simply checks the HTTP
367      * status code.
368      *
369      * @param rawResponse raw response
370      * @param response decoded response
371      * @return {@code true} if the response indicates success, {@code false} otherwise
372      */
373     protected boolean isSuccess(Response rawResponse, T response) {
374         return (rawResponse.getStatus() == 200);
375     }
376
377     @Override
378     public <Q> String logMessage(EventType direction, CommInfrastructure infra, String sink, Q request) {
379         String json = super.logMessage(direction, infra, sink, request);
380         NetLoggerUtil.log(direction, infra, sink, json);
381         return json;
382     }
383
384     // these may be overridden by junit tests
385
386     protected long getPollWaitMs() {
387         HttpPollingConfig cfg = (HttpPollingConfig) config;
388
389         return TimeUnit.MILLISECONDS.convert(cfg.getPollWaitSec(), TimeUnit.SECONDS);
390     }
391 }