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.function.Function;
 
  29 import javax.ws.rs.client.InvocationCallback;
 
  30 import javax.ws.rs.core.Response;
 
  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.HttpParams;
 
  40 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
 
  41 import org.onap.policy.controlloop.policy.PolicyResult;
 
  42 import org.slf4j.Logger;
 
  43 import org.slf4j.LoggerFactory;
 
  46  * Operator that uses HTTP. The operator's parameters must be an {@link HttpParams}.
 
  48  * @param <T> response type
 
  51 public abstract class HttpOperation<T> extends OperationPartial {
 
  52     private static final Logger logger = LoggerFactory.getLogger(HttpOperation.class);
 
  55      * Operator that created this operation.
 
  57     protected final HttpOperator operator;
 
  62     private final Class<T> responseClass;
 
  66      * Constructs the object.
 
  68      * @param params operation parameters
 
  69      * @param operator operator that created this operation
 
  70      * @param clazz response class
 
  72     public HttpOperation(ControlLoopOperationParams params, HttpOperator operator, Class<T> clazz) {
 
  73         super(params, operator);
 
  74         this.operator = operator;
 
  75         this.responseClass = clazz;
 
  79      * If no timeout is specified, then it returns the operator's configured timeout.
 
  82     protected long getTimeoutMs(Integer timeoutSec) {
 
  83         return (timeoutSec == null || timeoutSec == 0 ? operator.getTimeoutMs() : super.getTimeoutMs(timeoutSec));
 
  87      * Makes the request headers. This simply returns an empty map.
 
  89      * @return request headers, a non-null, modifiable map
 
  91     protected Map<String, Object> makeHeaders() {
 
  92         return new HashMap<>();
 
  96      * Gets the path to be used when performing the request; this is typically appended to
 
  97      * the base URL. This method simply invokes {@link #getPath()}.
 
  99      * @return the path URI suffix
 
 101     public String makePath() {
 
 102         return operator.getPath();
 
 106      * Makes the URL to which the "get" request should be posted. This ir primarily used
 
 107      * for logging purposes. This particular method returns the base URL appended with the
 
 108      * return value from {@link #makePath()}.
 
 110      * @return the URL to which from which to get
 
 112     public String makeUrl() {
 
 113         return (operator.getClient().getBaseUrl() + makePath());
 
 117      * Arranges to handle a response.
 
 119      * @param outcome outcome to be populate
 
 120      * @param url URL to which to request was sent
 
 121      * @param requester function to initiate the request and invoke the given callback
 
 123      * @return a future for the response
 
 125     protected CompletableFuture<OperationOutcome> handleResponse(OperationOutcome outcome, String url,
 
 126                     Function<InvocationCallback<Response>, Future<Response>> requester) {
 
 128         final PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
 
 129         final CompletableFuture<Response> future = new CompletableFuture<>();
 
 130         final Executor executor = params.getExecutor();
 
 132         // arrange for the callback to complete "future"
 
 133         InvocationCallback<Response> callback = new InvocationCallback<>() {
 
 135             public void completed(Response response) {
 
 136                 future.complete(response);
 
 140             public void failed(Throwable throwable) {
 
 141                 logger.warn("{}.{}: response failure for {}", params.getActor(), params.getOperation(),
 
 142                                 params.getRequestId());
 
 143                 future.completeExceptionally(throwable);
 
 147         // start the request and arrange to cancel it if the controller is canceled
 
 148         controller.add(requester.apply(callback));
 
 150         // once "future" completes, process the response, and then complete the controller
 
 151         future.thenComposeAsync(response -> processResponse(outcome, url, response), executor)
 
 152                         .whenCompleteAsync(controller.delayedComplete(), executor);
 
 158      * Processes a response. This method decodes the response, sets the outcome based on
 
 159      * the response, and then returns a completed future.
 
 161      * @param outcome outcome to be populate
 
 162      * @param url URL to which to request was sent
 
 163      * @param response raw response to process
 
 164      * @return a future to cancel or await the outcome
 
 166     protected CompletableFuture<OperationOutcome> processResponse(OperationOutcome outcome, String url,
 
 167                     Response rawResponse) {
 
 169         logger.info("{}.{}: response received for {}", params.getActor(), params.getOperation(), params.getRequestId());
 
 171         String strResponse = HttpClient.getBody(rawResponse, String.class);
 
 173         logMessage(EventType.IN, CommInfrastructure.REST, url, strResponse);
 
 176         if (responseClass == String.class) {
 
 177             response = responseClass.cast(strResponse);
 
 180                 response = makeCoder().decode(strResponse, responseClass);
 
 181             } catch (CoderException e) {
 
 182                 logger.warn("{}.{} cannot decode response for {}", params.getActor(), params.getOperation(),
 
 183                                 params.getRequestId(), e);
 
 184                 throw new IllegalArgumentException("cannot decode response");
 
 188         if (!isSuccess(rawResponse, response)) {
 
 189             logger.info("{}.{} request failed with http error code {} for {}", params.getActor(), params.getOperation(),
 
 190                             rawResponse.getStatus(), params.getRequestId());
 
 191             return CompletableFuture.completedFuture(setOutcome(outcome, PolicyResult.FAILURE, response));
 
 194         logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(), params.getRequestId());
 
 195         setOutcome(outcome, PolicyResult.SUCCESS, response);
 
 196         return postProcessResponse(outcome, url, rawResponse, response);
 
 200      * Sets an operation's outcome and default message based on the result.
 
 202      * @param outcome operation to be updated
 
 203      * @param result result of the operation
 
 204      * @param response response used to populate the outcome
 
 205      * @return the updated operation
 
 207     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, T response) {
 
 208         return setOutcome(outcome, result);
 
 212      * Processes a successful response. This method simply returns the outcome wrapped in
 
 213      * a completed future.
 
 215      * @param outcome outcome to be populate
 
 216      * @param url URL to which to request was sent
 
 217      * @param rawResponse raw response
 
 218      * @param response decoded response
 
 219      * @return a future to cancel or await the outcome
 
 221     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
 
 222                     Response rawResponse, T response) {
 
 224         return CompletableFuture.completedFuture(outcome);
 
 228      * Determines if the response indicates success. This method simply checks the HTTP
 
 231      * @param rawResponse raw response
 
 232      * @param response decoded response
 
 233      * @return {@code true} if the response indicates success, {@code false} otherwise
 
 235     protected boolean isSuccess(Response rawResponse, T response) {
 
 236         return (rawResponse.getStatus() == 200);
 
 240     public <Q> String logMessage(EventType direction, CommInfrastructure infra, String sink, Q request) {
 
 241         String json = super.logMessage(direction, infra, sink, request);
 
 242         NetLoggerUtil.log(direction, infra, sink, json);