2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controlloop.actorserviceprovider.impl;
23 import java.util.HashMap;
25 import java.util.concurrent.CompletableFuture;
26 import java.util.concurrent.Executor;
27 import java.util.concurrent.Future;
28 import java.util.concurrent.TimeUnit;
29 import java.util.function.Function;
30 import javax.ws.rs.client.InvocationCallback;
31 import javax.ws.rs.core.Response;
33 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
34 import org.onap.policy.common.endpoints.http.client.HttpClient;
35 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
36 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
37 import org.onap.policy.common.utils.coder.CoderException;
38 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
39 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
40 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
41 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
42 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
43 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
44 import org.onap.policy.controlloop.policy.PolicyResult;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * Operator that uses HTTP. The operator's parameters must be an {@link HttpParams}.
51 * @param <T> response type
54 public abstract class HttpOperation<T> extends OperationPartial {
55 private static final Logger logger = LoggerFactory.getLogger(HttpOperation.class);
61 SUCCESS, FAILURE, STILL_WAITING
65 * Configuration for this operation.
67 private final HttpConfig config;
72 private final Class<T> responseClass;
75 * {@code True} to use polling, {@code false} otherwise.
78 private boolean usePolling;
81 * Number of polls issued so far, on the current operation attempt.
84 private int pollCount;
88 * Constructs the object.
90 * @param params operation parameters
91 * @param config configuration for this operation
92 * @param clazz response class
94 public HttpOperation(ControlLoopOperationParams params, HttpConfig config, Class<T> clazz) {
95 super(params, config);
97 this.responseClass = clazz;
101 * Indicates that polling should be used.
103 protected void setUsePolling() {
104 if (!(config instanceof HttpPollingConfig)) {
105 throw new IllegalStateException("cannot poll without polling parameters");
111 public HttpClient getClient() {
112 return config.getClient();
116 * Gets the path to be used when performing the request; this is typically appended to
117 * the base URL. This method simply invokes {@link #getPath()}.
119 * @return the path URI suffix
121 public String getPath() {
122 return config.getPath();
125 public long getTimeoutMs() {
126 return config.getTimeoutMs();
130 * If no timeout is specified, then it returns the operator's configured timeout.
133 protected long getTimeoutMs(Integer timeoutSec) {
134 return (timeoutSec == null || timeoutSec == 0 ? getTimeoutMs() : super.getTimeoutMs(timeoutSec));
138 * Makes the request headers. This simply returns an empty map.
140 * @return request headers, a non-null, modifiable map
142 protected Map<String, Object> makeHeaders() {
143 return new HashMap<>();
147 * Makes the URL to which the HTTP request should be posted. This is primarily used
148 * for logging purposes. This particular method returns the base URL appended with the
149 * return value from {@link #getPath()}.
151 * @return the URL to which from which to get
153 public String getUrl() {
154 return (getClient().getBaseUrl() + getPath());
158 * Resets the polling count
161 * Note: This should be invoked at the start of each operation (i.e., in
162 * {@link #startOperationAsync(int, OperationOutcome)}.
164 protected void resetPollCount() {
169 * Arranges to handle a response.
171 * @param outcome outcome to be populate
172 * @param url URL to which to request was sent
173 * @param requester function to initiate the request and invoke the given callback
175 * @return a future for the response
177 protected CompletableFuture<OperationOutcome> handleResponse(OperationOutcome outcome, String url,
178 Function<InvocationCallback<Response>, Future<Response>> requester) {
180 final PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
181 final CompletableFuture<Response> future = new CompletableFuture<>();
182 final Executor executor = params.getExecutor();
184 // arrange for the callback to complete "future"
185 InvocationCallback<Response> callback = new InvocationCallback<>() {
187 public void completed(Response response) {
188 future.complete(response);
192 public void failed(Throwable throwable) {
193 logger.warn("{}.{}: response failure for {}", params.getActor(), params.getOperation(),
194 params.getRequestId());
195 future.completeExceptionally(throwable);
199 // start the request and arrange to cancel it if the controller is canceled
200 controller.add(requester.apply(callback));
202 // once "future" completes, process the response, and then complete the controller
203 future.thenComposeAsync(response -> processResponse(outcome, url, response), executor)
204 .whenCompleteAsync(controller.delayedComplete(), executor);
210 * Processes a response. This method decodes the response, sets the outcome based on
211 * the response, and then returns a completed future.
213 * @param outcome outcome to be populate
214 * @param url URL to which to request was sent
215 * @param response raw response to process
216 * @return a future to cancel or await the outcome
218 protected CompletableFuture<OperationOutcome> processResponse(OperationOutcome outcome, String url,
219 Response rawResponse) {
221 logger.info("{}.{}: response received for {}", params.getActor(), params.getOperation(), params.getRequestId());
223 String strResponse = rawResponse.readEntity(String.class);
225 logMessage(EventType.IN, CommInfrastructure.REST, url, strResponse);
228 if (responseClass == String.class) {
229 response = responseClass.cast(strResponse);
232 response = getCoder().decode(strResponse, responseClass);
233 } catch (CoderException e) {
234 logger.warn("{}.{} cannot decode response for {}", params.getActor(), params.getOperation(),
235 params.getRequestId(), e);
236 throw new IllegalArgumentException("cannot decode response");
240 if (!isSuccess(rawResponse, response)) {
241 logger.info("{}.{} request failed with http error code {} for {}", params.getActor(), params.getOperation(),
242 rawResponse.getStatus(), params.getRequestId());
243 return CompletableFuture.completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
246 logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(), params.getRequestId());
247 setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response);
248 return postProcessResponse(outcome, url, rawResponse, response);
252 * Sets an operation's outcome and default message based on the result.
254 * @param outcome operation to be updated
255 * @param result result of the operation
256 * @param rawResponse raw response
257 * @param response decoded response
258 * @return the updated operation
260 public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
263 outcome.setResponse(response);
264 return setOutcome(outcome, result);
268 * Processes a successful response. This method simply returns the outcome wrapped in
269 * a completed future.
271 * @param outcome outcome to be populate
272 * @param url URL to which to request was sent
273 * @param rawResponse raw response
274 * @param response decoded response
275 * @return a future to cancel or await the outcome
277 protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
278 Response rawResponse, T response) {
281 // doesn't use polling - just return the completed future
282 return CompletableFuture.completedFuture(outcome);
285 HttpPollingConfig cfg = (HttpPollingConfig) config;
287 switch (detmStatus(rawResponse, response)) {
289 logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(),
290 params.getRequestId());
291 return CompletableFuture
292 .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
295 logger.info("{}.{} request failed for {}", params.getActor(), params.getOperation(),
296 params.getRequestId());
297 return CompletableFuture
298 .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
302 logger.info("{}.{} request incomplete for {}", params.getActor(), params.getOperation(),
303 params.getRequestId());
309 // see if the limit for the number of polls has been reached
310 if (pollCount++ >= cfg.getMaxPolls()) {
311 logger.warn("{}: execeeded 'poll' limit {} for {}", getFullName(), cfg.getMaxPolls(),
312 params.getRequestId());
313 setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
314 return CompletableFuture.completedFuture(outcome);
317 // sleep and then poll
318 Function<Void, CompletableFuture<OperationOutcome>> doPoll = unused -> issuePoll(outcome);
319 return sleep(getPollWaitMs(), TimeUnit.MILLISECONDS).thenComposeAsync(doPoll);
323 * Polls to see if the original request is complete. This method polls using an HTTP
324 * "get" request whose URL is constructed by appending the extracted "poll ID" to the
325 * poll path from the configuration data.
327 * @param outcome outcome to be populated with the response
328 * @return a future that can be used to cancel the poll or await its response
330 protected CompletableFuture<OperationOutcome> issuePoll(OperationOutcome outcome) {
331 String path = getPollingPath();
332 String url = getClient().getBaseUrl() + path;
334 logger.debug("{}: 'poll' count {} for {}", getFullName(), pollCount, params.getRequestId());
336 logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
338 return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
342 * Determines the status of the response. This particular method simply throws an
345 * @param rawResponse raw response
346 * @param response decoded response
347 * @return the status of the response
349 protected Status detmStatus(Response rawResponse, T response) {
350 throw new UnsupportedOperationException("cannot determine response status");
354 * Gets the URL to use when polling. Typically, this is some unique ID appended to the
355 * polling path found within the configuration data. This particular method simply
356 * returns the polling path from the configuration data.
358 * @return the URL to use when polling
360 protected String getPollingPath() {
361 return ((HttpPollingConfig) config).getPollPath();
365 * Determines if the response indicates success. This method simply checks the HTTP
368 * @param rawResponse raw response
369 * @param response decoded response
370 * @return {@code true} if the response indicates success, {@code false} otherwise
372 protected boolean isSuccess(Response rawResponse, T response) {
373 return (rawResponse.getStatus() == 200);
377 public <Q> String logMessage(EventType direction, CommInfrastructure infra, String sink, Q request) {
378 String json = super.logMessage(direction, infra, sink, request);
379 NetLoggerUtil.log(direction, infra, sink, json);
383 // these may be overridden by junit tests
385 protected long getPollWaitMs() {
386 HttpPollingConfig cfg = (HttpPollingConfig) config;
388 return TimeUnit.MILLISECONDS.convert(cfg.getPollWaitSec(), TimeUnit.SECONDS);