Modify Actors to use properties when provided
[policy/models.git] / models-interactions / model-actors / actor.so / src / main / java / org / onap / policy / controlloop / actor / so / SoOperation.java
index 2a00edd..8f0dda3 100644 (file)
@@ -22,43 +22,33 @@ package org.onap.policy.controlloop.actor.so;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import com.google.gson.TypeAdapter;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonToken;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
 import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
-import java.time.format.DateTimeParseException;
 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.ModelVer;
 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.OperationProperties;
 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;
@@ -68,15 +58,13 @@ 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 SoCoder();
 
     public static final String PAYLOAD_KEY_VF_COUNT = "vfCount";
@@ -88,8 +76,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;
@@ -97,22 +83,18 @@ 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.
      *
      * @param params operation parameters
      * @param config configuration for this operation
+     * @param propertyNames names of properties required by this operation
      */
-    public SoOperation(ControlLoopOperationParams params, HttpConfig config) {
-        super(params, config, SoResponse.class);
-        this.config = (SoConfig) config;
+    public SoOperation(ControlLoopOperationParams params, HttpPollingConfig config, List<String> propertyNames) {
+        super(params, config, SoResponse.class, propertyNames);
+
+        setUsePolling();
 
         verifyNotNull("Target information", params.getTarget());
 
@@ -124,11 +106,9 @@ 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);
     }
 
@@ -193,35 +173,34 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
     }
 
     protected int getVfCount() {
+        if (containsProperty(OperationProperties.DATA_VF_COUNT)) {
+            return getProperty(OperationProperties.DATA_VF_COUNT);
+        }
+
         return params.getContext().getProperty(vfCountKey);
     }
 
     protected void setVfCount(int vfCount) {
+        if (containsProperty(OperationProperties.DATA_VF_COUNT)) {
+            setProperty(OperationProperties.DATA_VF_COUNT, vfCount);
+            return;
+        }
+
         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)) {
                 extractSubRequestId(response);
-                successfulCompletion();
-                return CompletableFuture
-                                .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
+                return Status.SUCCESS;
             }
 
             if (FAILED.equalsIgnoreCase(requestState)) {
                 extractSubRequestId(response);
-                return CompletableFuture
-                                .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
+                return Status.FAILURE;
             }
         }
 
@@ -232,17 +211,12 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
             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);
-        }
+        return Status.STILL_WAITING;
+    }
 
-        // sleep and then perform a "get" operation
-        Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome);
-        return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
+    @Override
+    protected String getPollingPath() {
+        return super.getPollingPath() + getSubRequestId();
     }
 
     @Override
@@ -260,30 +234,6 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
         return true;
     }
 
-    /**
-     * Invoked when a request completes successfully.
-     */
-    protected void successfulCompletion() {
-        // do nothing
-    }
-
-    /**
-     * Issues a "get" request to see if the original request is complete yet.
-     *
-     * @param outcome outcome to be populated with the response
-     * @return a future that can be used to cancel the "get" request or await its response
-     */
-    private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome) {
-        String path = getPathGet() + getSubRequestId();
-        String url = getClient().getBaseUrl() + path;
-
-        logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
-
-        logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
-
-        return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
-    }
-
     /**
      * Gets the request state of a response.
      *
@@ -323,7 +273,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;
     }
 
@@ -429,113 +382,86 @@ public abstract class SoOperation extends HttpOperation<SoResponse> {
         return headers;
     }
 
-    /*
-     * These methods extract data from the Custom Query and throw an
-     * IllegalArgumentException if the desired data item is not found.
+    /**
+     * Gets an item from a property. If the property is not found, then it invokes the
+     * given function to retrieve it from the custom query data. If that fails as well,
+     * then an exception is thrown.
+     *
+     * @param propName property name
+     * @param getter method to extract the value from the custom query data
+     * @param errmsg error message to include in any exception
+     * @return the retrieved item
      */
-
-    protected GenericVnf getVnfItem(AaiCqResponse aaiCqResponse, SoModelInfo soModelInfo) {
-        GenericVnf vnf = aaiCqResponse.getGenericVnfByVfModuleModelInvariantId(soModelInfo.getModelInvariantId());
-        if (vnf == null) {
-            throw new IllegalArgumentException("missing generic VNF");
+    protected <T> T getItem(String propName, Function<AaiCqResponse, T> getter, String errmsg) {
+        if (containsProperty(propName)) {
+            return getProperty(propName);
         }
 
-        return vnf;
-    }
-
-    protected ServiceInstance getServiceInstance(AaiCqResponse aaiCqResponse) {
-        ServiceInstance vnfService = aaiCqResponse.getServiceInstance();
-        if (vnfService == null) {
-            throw new IllegalArgumentException("missing VNF Service Item");
+        final AaiCqResponse aaiCqResponse = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
+        T item = getter.apply(aaiCqResponse);
+        if (item == null) {
+            throw new IllegalArgumentException(errmsg);
         }
 
-        return vnfService;
+        return item;
     }
 
-    protected Tenant getDefaultTenant(AaiCqResponse aaiCqResponse) {
-        Tenant tenant = aaiCqResponse.getDefaultTenant();
-        if (tenant == null) {
-            throw new IllegalArgumentException("missing Tenant Item");
-        }
+    /*
+     * These methods extract data from the Custom Query and throw an
+     * IllegalArgumentException if the desired data item is not found.
+     */
 
-        return tenant;
+    protected GenericVnf getVnfItem(SoModelInfo soModelInfo) {
+        // @formatter:off
+        return getItem(OperationProperties.AAI_VNF,
+            cq -> cq.getGenericVnfByVfModuleModelInvariantId(soModelInfo.getModelInvariantId()),
+            "missing generic VNF");
+        // @formatter:on
     }
 
-    protected CloudRegion getDefaultCloudRegion(AaiCqResponse aaiCqResponse) {
-        CloudRegion cloudRegion = aaiCqResponse.getDefaultCloudRegion();
-        if (cloudRegion == null) {
-            throw new IllegalArgumentException("missing Cloud Region");
-        }
-
-        return cloudRegion;
+    protected ServiceInstance getServiceInstance() {
+        return getItem(OperationProperties.AAI_SERVICE, AaiCqResponse::getServiceInstance, "missing VNF Service Item");
     }
 
-    // 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);
+    protected Tenant getDefaultTenant() {
+        // @formatter:off
+        return getItem(OperationProperties.AAI_DEFAULT_TENANT,
+            AaiCqResponse::getDefaultTenant,
+            "missing Default Tenant Item");
+        // @formatter:on
     }
 
-    public int getMaxGets() {
-        return config.getMaxGets();
+    protected CloudRegion getDefaultCloudRegion() {
+        // @formatter:off
+        return getItem(OperationProperties.AAI_DEFAULT_CLOUD_REGION,
+            AaiCqResponse::getDefaultCloudRegion,
+            "missing Default Cloud Region");
+        // @formatter:on
     }
 
-    public String getPathGet() {
-        return config.getPathGet();
+    protected ModelVer getVnfModel(GenericVnf vnfItem) {
+        // @formatter:off
+        return getItem(OperationProperties.AAI_VNF_MODEL,
+            cq -> cq.getModelVerByVersionId(vnfItem.getModelVersionId()),
+            "missing generic VNF Model");
+        // @formatter:on
     }
 
-    public int getWaitSecGet() {
-        return config.getWaitSecGet();
+    protected ModelVer getServiceModel(ServiceInstance vnfServiceItem) {
+        // @formatter:off
+        return getItem(OperationProperties.AAI_SERVICE_MODEL,
+            cq -> cq.getModelVerByVersionId(vnfServiceItem.getModelVersionId()),
+            "missing Service Model");
+        // @formatter:on
     }
 
+    // these may be overridden by junit tests
+
     @Override
-    protected Coder makeCoder() {
+    protected Coder getCoder() {
         return coder;
     }
 
-    /*
-     * TODO: combine this adapter with existing LocalDateTimeTypeAdapter and eliminate the
-     * following two classes.
-     */
-
-    /**
-     * GSON Type Adapter for "LocalDateTime" fields, that uses the standard
-     * RFC_1123_DATE_TIME formatter.
-     */
-    private static class SoLocalDateTimeTypeAdapter extends TypeAdapter<LocalDateTime> {
-        private static final DateTimeFormatter FORMATTER = DateTimeFormatter.RFC_1123_DATE_TIME;
-
-        @Override
-        public LocalDateTime read(JsonReader in) throws IOException {
-            try {
-                if (in.peek() == JsonToken.NULL) {
-                    in.nextNull();
-                    return null;
-                } else {
-                    return LocalDateTime.parse(in.nextString(), FORMATTER);
-                }
-
-            } catch (DateTimeParseException e) {
-                throw new JsonParseException("invalid date", e);
-            }
-        }
-
-        @Override
-        public void write(JsonWriter out, LocalDateTime value) throws IOException {
-            if (value == null) {
-                out.nullValue();
-            } else {
-                String text = value.format(FORMATTER);
-                out.value(text);
-            }
-        }
-    }
-
     private static class SoCoder extends StandardCoder {
 
         /**