Moving common polling code into HttpOperation
[policy/models.git] / models-interactions / model-actors / actor.so / src / main / java / org / onap / policy / controlloop / actor / so / SoOperation.java
index 1ca6c73..cb9ec9c 100644 (file)
 
 package org.onap.policy.controlloop.actor.so;
 
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import java.time.LocalDateTime;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.function.Function;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import lombok.Getter;
 import org.onap.aai.domain.yang.CloudRegion;
 import org.onap.aai.domain.yang.GenericVnf;
 import org.onap.aai.domain.yang.ServiceInstance;
 import org.onap.aai.domain.yang.Tenant;
 import org.onap.policy.aai.AaiConstants;
 import org.onap.policy.aai.AaiCqResponse;
-import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
-import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
+import org.onap.policy.common.gson.GsonMessageBodyHandler;
 import org.onap.policy.common.utils.coder.Coder;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardCoder;
+import org.onap.policy.common.utils.coder.StandardCoderObject;
 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
-import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
+import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
 import org.onap.policy.controlloop.policy.PolicyResult;
 import org.onap.policy.controlloop.policy.Target;
 import org.onap.policy.so.SoCloudConfiguration;
@@ -55,16 +55,14 @@ import org.onap.policy.so.SoRequestInfo;
 import org.onap.policy.so.SoRequestParameters;
 import org.onap.policy.so.SoRequestStatus;
 import org.onap.policy.so.SoResponse;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.onap.policy.so.util.SoLocalDateTimeTypeAdapter;
 
 /**
- * Superclass for SDNC Operators. Note: subclasses should invoke {@link #resetGetCount()}
+ * Superclass for SDNC Operators. Note: subclasses should invoke {@link #resetPollCount()}
  * each time they issue an HTTP request.
  */
 public abstract class SoOperation extends HttpOperation<SoResponse> {
-    private static final Logger logger = LoggerFactory.getLogger(SoOperation.class);
-    private static final Coder coder = new StandardCoder();
+    private static final Coder coder = new SoCoder();
 
     public static final String PAYLOAD_KEY_VF_COUNT = "vfCount";
     public static final String FAILED = "FAILED";
@@ -75,8 +73,6 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
     public static final String REQ_PARAM_NM = "requestParameters";
     public static final String CONFIG_PARAM_NM = "configurationParameters";
 
-    private final SoConfig config;
-
     // values extracted from the parameter Target
     private final String modelCustomizationId;
     private final String modelInvariantId;
@@ -84,12 +80,6 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
 
     private final String vfCountKey;
 
-    /**
-     * Number of "get" requests issued so far, on the current operation attempt.
-     */
-    @Getter
-    private int getCount;
-
 
     /**
      * Constructs the object.
@@ -97,9 +87,10 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
      * @param params operation parameters
      * @param config configuration for this operation
      */
-    public SoOperation(ControlLoopOperationParams params, HttpConfig config) {
+    public SoOperation(ControlLoopOperationParams params, HttpPollingConfig config) {
         super(params, config, SoResponse.class);
-        this.config = (SoConfig) config;
+
+        setUsePolling();
 
         verifyNotNull("Target information", params.getTarget());
 
@@ -111,11 +102,10 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
                         + modelVersionId + "]";
     }
 
-    /**
-     * Subclasses should invoke this before issuing their first HTTP request.
-     */
-    protected void resetGetCount() {
-        getCount = 0;
+    @Override
+    protected void resetPollCount() {
+        super.resetPollCount();
+        setSubRequestId(null);
     }
 
     /**
@@ -123,9 +113,9 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
      * the VF count from the custom query.
      */
     protected void validateTarget() {
-        verifyNotNull("model-customization-id", modelCustomizationId);
-        verifyNotNull("model-invariant-id", modelInvariantId);
-        verifyNotNull("model-version-id", modelVersionId);
+        verifyNotNull("modelCustomizationId", modelCustomizationId);
+        verifyNotNull("modelInvariantId", modelInvariantId);
+        verifyNotNull("modelVersionId", modelVersionId);
     }
 
     private void verifyNotNull(String type, Object value) {
@@ -186,74 +176,49 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
         params.getContext().setProperty(vfCountKey, vfCount);
     }
 
-    /**
-     * If the response does not indicate that the request has been completed, then sleep a
-     * bit and issue a "get".
-     */
     @Override
-    protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
-                    Response rawResponse, SoResponse response) {
-
-        // see if the request has "completed", whether or not it was successful
+    protected Status detmStatus(Response rawResponse, SoResponse response) {
         if (rawResponse.getStatus() == 200) {
             String requestState = getRequestState(response);
             if (COMPLETE.equalsIgnoreCase(requestState)) {
-                successfulCompletion();
-                return CompletableFuture
-                                .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
+                extractSubRequestId(response);
+                return Status.SUCCESS;
             }
 
             if (FAILED.equalsIgnoreCase(requestState)) {
-                return CompletableFuture
-                                .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
+                extractSubRequestId(response);
+                return Status.FAILURE;
             }
         }
 
         // still incomplete
 
         // need a request ID with which to query
-        if (response == null || response.getRequestReferences() == null
-                        || response.getRequestReferences().getRequestId() == null) {
+        if (getSubRequestId() == null && !extractSubRequestId(response)) {
             throw new IllegalArgumentException("missing request ID in response");
         }
 
-        // see if the limit for the number of "gets" has been reached
-        if (getCount++ >= getMaxGets()) {
-            logger.warn("{}: execeeded 'get' limit {} for {}", getFullName(), getMaxGets(), params.getRequestId());
-            setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
-            outcome.setMessage(SO_RESPONSE_CODE + " " + outcome.getMessage());
-            return CompletableFuture.completedFuture(outcome);
-        }
-
-        // sleep and then perform a "get" operation
-        Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome, response);
-        return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
+        return Status.STILL_WAITING;
     }
 
-    /**
-     * Invoked when a request completes successfully.
-     */
-    protected void successfulCompletion() {
-        // do nothing
+    @Override
+    protected String getPollingPath() {
+        return super.getPollingPath() + getSubRequestId();
     }
 
-    /**
-     * Issues a "get" request to see if the original request is complete yet.
-     *
-     * @param outcome outcome to be populated with the response
-     * @param response previous response
-     * @return a future that can be used to cancel the "get" request or await its response
-     */
-    private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, SoResponse response) {
-        String path = getPathGet() + response.getRequestReferences().getRequestId();
-        String url = getClient().getBaseUrl() + path;
-
-        logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
+    @Override
+    public void generateSubRequestId(int attempt) {
+        setSubRequestId(null);
+    }
 
-        logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
+    private boolean extractSubRequestId(SoResponse response) {
+        if (response == null || response.getRequestReferences() == null
+                        || response.getRequestReferences().getRequestId() == null) {
+            return false;
+        }
 
-        // TODO should this use "path" or the full "url"?
-        return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
+        setSubRequestId(response.getRequestReferences().getRequestId());
+        return true;
     }
 
     /**
@@ -295,7 +260,10 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
         // set default result and message
         setOutcome(outcome, result);
 
-        outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
+        int code = (result == PolicyResult.FAILURE_TIMEOUT ? SO_RESPONSE_CODE : rawResponse.getStatus());
+
+        outcome.setResponse(response);
+        outcome.setMessage(code + " " + outcome.getMessage());
         return outcome;
     }
 
@@ -444,24 +412,35 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
 
     // these may be overridden by junit tests
 
-    /**
-     * Gets the wait time, in milliseconds, between "get" requests.
-     *
-     * @return the wait time, in milliseconds, between "get" requests
-     */
-    public long getWaitMsGet() {
-        return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
+    @Override
+    protected Coder getCoder() {
+        return coder;
     }
 
-    public int getMaxGets() {
-        return config.getMaxGets();
-    }
+    private static class SoCoder extends StandardCoder {
 
-    public String getPathGet() {
-        return config.getPathGet();
-    }
+        /**
+         * Gson object used to encode and decode messages.
+         */
+        private static final Gson SO_GSON;
 
-    public int getWaitSecGet() {
-        return config.getWaitSecGet();
+        /**
+         * Gson object used to encode messages in "pretty" format.
+         */
+        private static final Gson SO_GSON_PRETTY;
+
+        static {
+            GsonBuilder builder = GsonMessageBodyHandler
+                            .configBuilder(new GsonBuilder().registerTypeAdapter(StandardCoderObject.class,
+                                            new StandardTypeAdapter()))
+                            .registerTypeAdapter(LocalDateTime.class, new SoLocalDateTimeTypeAdapter());
+
+            SO_GSON = builder.create();
+            SO_GSON_PRETTY = builder.setPrettyPrinting().create();
+        }
+
+        public SoCoder() {
+            super(SO_GSON, SO_GSON_PRETTY);
+        }
     }
 }