Log full URL for REST calls
[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 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actorserviceprovider.impl;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.concurrent.CompletableFuture;
26 import java.util.concurrent.Executor;
27 import java.util.concurrent.Future;
28 import java.util.function.Function;
29 import javax.ws.rs.client.InvocationCallback;
30 import javax.ws.rs.core.Response;
31 import lombok.Getter;
32 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
33 import org.onap.policy.common.endpoints.http.client.HttpClient;
34 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
35 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
38 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
39 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
40 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
41 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
42 import org.onap.policy.controlloop.policy.PolicyResult;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Operator that uses HTTP. The operator's parameters must be an {@link HttpParams}.
48  *
49  * @param <T> response type
50  */
51 @Getter
52 public abstract class HttpOperation<T> extends OperationPartial {
53     private static final Logger logger = LoggerFactory.getLogger(HttpOperation.class);
54
55     /**
56      * Configuration for this operation.
57      */
58     private final HttpConfig config;
59
60     /**
61      * Response class.
62      */
63     private final Class<T> responseClass;
64
65
66     /**
67      * Constructs the object.
68      *
69      * @param params operation parameters
70      * @param config configuration for this operation
71      * @param clazz response class
72      */
73     public HttpOperation(ControlLoopOperationParams params, HttpConfig config, Class<T> clazz) {
74         super(params, config);
75         this.config = config;
76         this.responseClass = clazz;
77     }
78
79     public HttpClient getClient() {
80         return config.getClient();
81     }
82
83     /**
84      * Gets the path to be used when performing the request; this is typically appended to
85      * the base URL. This method simply invokes {@link #getPath()}.
86      *
87      * @return the path URI suffix
88      */
89     public String getPath() {
90         return config.getPath();
91     }
92
93     public long getTimeoutMs() {
94         return config.getTimeoutMs();
95     }
96
97     /**
98      * If no timeout is specified, then it returns the operator's configured timeout.
99      */
100     @Override
101     protected long getTimeoutMs(Integer timeoutSec) {
102         return (timeoutSec == null || timeoutSec == 0 ? getTimeoutMs() : super.getTimeoutMs(timeoutSec));
103     }
104
105     /**
106      * Makes the request headers. This simply returns an empty map.
107      *
108      * @return request headers, a non-null, modifiable map
109      */
110     protected Map<String, Object> makeHeaders() {
111         return new HashMap<>();
112     }
113
114     /**
115      * Makes the URL to which the HTTP request should be posted. This is primarily used
116      * for logging purposes. This particular method returns the base URL appended with the
117      * return value from {@link #getPath()}.
118      *
119      * @return the URL to which from which to get
120      */
121     public String getUrl() {
122         return (getClient().getBaseUrl() + getPath());
123     }
124
125     /**
126      * Arranges to handle a response.
127      *
128      * @param outcome outcome to be populate
129      * @param url URL to which to request was sent
130      * @param requester function to initiate the request and invoke the given callback
131      *        when it completes
132      * @return a future for the response
133      */
134     protected CompletableFuture<OperationOutcome> handleResponse(OperationOutcome outcome, String url,
135                     Function<InvocationCallback<Response>, Future<Response>> requester) {
136
137         final PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
138         final CompletableFuture<Response> future = new CompletableFuture<>();
139         final Executor executor = params.getExecutor();
140
141         // arrange for the callback to complete "future"
142         InvocationCallback<Response> callback = new InvocationCallback<>() {
143             @Override
144             public void completed(Response response) {
145                 future.complete(response);
146             }
147
148             @Override
149             public void failed(Throwable throwable) {
150                 logger.warn("{}.{}: response failure for {}", params.getActor(), params.getOperation(),
151                                 params.getRequestId());
152                 future.completeExceptionally(throwable);
153             }
154         };
155
156         // start the request and arrange to cancel it if the controller is canceled
157         controller.add(requester.apply(callback));
158
159         // once "future" completes, process the response, and then complete the controller
160         future.thenComposeAsync(response -> processResponse(outcome, url, response), executor)
161                         .whenCompleteAsync(controller.delayedComplete(), executor);
162
163         return controller;
164     }
165
166     /**
167      * Processes a response. This method decodes the response, sets the outcome based on
168      * the response, and then returns a completed future.
169      *
170      * @param outcome outcome to be populate
171      * @param url URL to which to request was sent
172      * @param response raw response to process
173      * @return a future to cancel or await the outcome
174      */
175     protected CompletableFuture<OperationOutcome> processResponse(OperationOutcome outcome, String url,
176                     Response rawResponse) {
177
178         logger.info("{}.{}: response received for {}", params.getActor(), params.getOperation(), params.getRequestId());
179
180         String strResponse = HttpClient.getBody(rawResponse, String.class);
181
182         logMessage(EventType.IN, CommInfrastructure.REST, url, strResponse);
183
184         T response;
185         if (responseClass == String.class) {
186             response = responseClass.cast(strResponse);
187         } else {
188             try {
189                 response = makeCoder().decode(strResponse, responseClass);
190             } catch (CoderException e) {
191                 logger.warn("{}.{} cannot decode response for {}", params.getActor(), params.getOperation(),
192                                 params.getRequestId(), e);
193                 throw new IllegalArgumentException("cannot decode response");
194             }
195         }
196
197         if (!isSuccess(rawResponse, response)) {
198             logger.info("{}.{} request failed with http error code {} for {}", params.getActor(), params.getOperation(),
199                             rawResponse.getStatus(), params.getRequestId());
200             return CompletableFuture.completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
201         }
202
203         logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(), params.getRequestId());
204         setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response);
205         return postProcessResponse(outcome, url, rawResponse, response);
206     }
207
208     /**
209      * Sets an operation's outcome and default message based on the result.
210      *
211      * @param outcome operation to be updated
212      * @param result result of the operation
213      * @param rawResponse raw response
214      * @param response decoded response
215      * @return the updated operation
216      */
217     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
218                     T response) {
219
220         return setOutcome(outcome, result);
221     }
222
223     /**
224      * Processes a successful response. This method simply returns the outcome wrapped in
225      * a completed future.
226      *
227      * @param outcome outcome to be populate
228      * @param url URL to which to request was sent
229      * @param rawResponse raw response
230      * @param response decoded response
231      * @return a future to cancel or await the outcome
232      */
233     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
234                     Response rawResponse, T response) {
235
236         return CompletableFuture.completedFuture(outcome);
237     }
238
239     /**
240      * Determines if the response indicates success. This method simply checks the HTTP
241      * status code.
242      *
243      * @param rawResponse raw response
244      * @param response decoded response
245      * @return {@code true} if the response indicates success, {@code false} otherwise
246      */
247     protected boolean isSuccess(Response rawResponse, T response) {
248         return (rawResponse.getStatus() == 200);
249     }
250
251     @Override
252     public <Q> String logMessage(EventType direction, CommInfrastructure infra, String sink, Q request) {
253         String json = super.logMessage(direction, infra, sink, request);
254         NetLoggerUtil.log(direction, infra, sink, json);
255         return json;
256     }
257 }