Validate supported types 66/86166/3 3.0.2-ONAP
authorJim Hahn <jrh3@att.com>
Tue, 23 Apr 2019 17:27:55 +0000 (13:27 -0400)
committerJim Hahn <jrh3@att.com>
Wed, 24 Apr 2019 17:07:50 +0000 (13:07 -0400)
When a group is created, PAP should verify that the "supported types"
exist in the DB.
Address potential sonar issue.
Address potential sonar issue in similar block of code.

Change-Id: Ib830550bc37d4ebe42c8782f3f874e463f3f51c2
Issue-ID: POLICY-1688
Signed-off-by: Jim Hahn <jrh3@att.com>
main/src/main/java/org/onap/policy/pap/main/rest/depundep/PdpGroupDeployProvider.java
main/src/main/java/org/onap/policy/pap/main/rest/depundep/ProviderBase.java
main/src/main/java/org/onap/policy/pap/main/rest/depundep/SessionData.java
main/src/test/java/org/onap/policy/pap/main/rest/depundep/ProviderSuper.java
main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java
main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java
main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java
main/src/test/resources/e2e/monitoring.policy-type.yaml
main/src/test/resources/simpleDeploy/daoPolicyType.json [new file with mode: 0644]

index ee66b35..fa72105 100644 (file)
@@ -251,6 +251,7 @@ public class PdpGroupDeployProvider extends ProviderBase {
 
         BeanValidationResult result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
 
+        result.addResult(validateSupportedTypes(data, subgrp));
         result.addResult(validatePolicies(data, subgrp));
 
         return result;
@@ -345,32 +346,46 @@ public class PdpGroupDeployProvider extends ProviderBase {
     }
 
     /**
-     * Performs additional validations of the policies within a subgroup.
+     * Performs additional validations of the supported policy types within a subgroup.
      *
      * @param data session data
      * @param subgrp the subgroup to be validated
      * @param result the validation result
      * @throws PfModelException if an error occurred
      */
-    private ValidationResult validatePolicies(SessionData data, PdpSubGroup subgrp) throws PfModelException {
+    private ValidationResult validateSupportedTypes(SessionData data, PdpSubGroup subgrp) throws PfModelException {
         BeanValidationResult result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
 
-        for (ToscaPolicyIdentifier ident : subgrp.getPolicies()) {
-            try {
-                ToscaPolicy policy = data.getPolicy(new ToscaPolicyIdentifierOptVersion(ident));
+        for (ToscaPolicyTypeIdentifier type : subgrp.getSupportedPolicyTypes()) {
+            if (data.getPolicyType(type) == null) {
+                result.addResult(new ObjectValidationResult("policy type", type, ValidationStatus.INVALID,
+                                "unknown policy type"));
+            }
+        }
 
-                if (!subgrp.getSupportedPolicyTypes().contains(policy.getTypeIdentifier())) {
-                    result.addResult(new ObjectValidationResult("policy", ident, ValidationStatus.INVALID,
-                                    "not a supported policy for the subgroup"));
-                }
+        return result;
+    }
 
-            } catch (PfModelException e) {
-                if (e.getErrorResponse().getResponseCode() != Status.NOT_FOUND) {
-                    throw e;
-                }
+    /**
+     * Performs additional validations of the policies within a subgroup.
+     *
+     * @param data session data
+     * @param subgrp the subgroup to be validated
+     * @param result the validation result
+     * @throws PfModelException if an error occurred
+     */
+    private ValidationResult validatePolicies(SessionData data, PdpSubGroup subgrp) throws PfModelException {
+        BeanValidationResult result = new BeanValidationResult(subgrp.getPdpType(), subgrp);
 
+        for (ToscaPolicyIdentifier ident : subgrp.getPolicies()) {
+            ToscaPolicy policy = data.getPolicy(new ToscaPolicyIdentifierOptVersion(ident));
+            if (policy == null) {
                 result.addResult(new ObjectValidationResult("policy", ident, ValidationStatus.INVALID,
                                 "unknown policy"));
+
+            } else if (!subgrp.getSupportedPolicyTypes().contains(policy.getTypeIdentifier())) {
+                result.addResult(new ObjectValidationResult("policy", ident, ValidationStatus.INVALID,
+                                "not a supported policy for the subgroup"));
             }
         }
 
index a66b03d..d3f0d13 100644 (file)
@@ -248,7 +248,13 @@ public abstract class ProviderBase {
      */
     private ToscaPolicy getPolicy(SessionData data, ToscaPolicyIdentifierOptVersion ident) {
         try {
-            return data.getPolicy(ident);
+            ToscaPolicy policy = data.getPolicy(ident);
+            if (policy == null) {
+                throw new PfModelRuntimeException(Status.NOT_FOUND,
+                                "cannot find policy: " + ident.getName() + " " + ident.getVersion());
+            }
+
+            return policy;
 
         } catch (PfModelException e) {
             throw new PfModelRuntimeException(e.getErrorResponse().getResponseCode(),
index 98a5e67..a76d6e1 100644 (file)
@@ -27,7 +27,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
-import javax.ws.rs.core.Response.Status;
 import org.apache.commons.lang3.tuple.Pair;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.pdp.concepts.PdpGroup;
@@ -40,6 +39,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter.ToscaPolicyFilterBuilder;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
 
 /**
@@ -79,6 +79,11 @@ public class SessionData {
      */
     private final Map<ToscaPolicyIdentifierOptVersion, ToscaPolicy> policyCache = new HashMap<>();
 
+    /**
+     * Maps a policy type's identifier to the policy.
+     */
+    private final Map<ToscaPolicyTypeIdentifier, ToscaPolicyType> typeCache = new HashMap<>();
+
 
     /**
      * Constructs the object.
@@ -89,6 +94,31 @@ public class SessionData {
         this.dao = dao;
     }
 
+    /**
+     * Gets the policy type, referenced by an identifier. Loads it from the cache, if possible.
+     * Otherwise, gets it from the DB.
+     *
+     * @param desiredType policy type identifier
+     * @return the specified policy type
+     * @throws PfModelException if an error occurred
+     */
+    public ToscaPolicyType getPolicyType(ToscaPolicyTypeIdentifier desiredType) throws PfModelException {
+
+        ToscaPolicyType type = typeCache.get(desiredType);
+        if (type == null) {
+
+            List<ToscaPolicyType> lst = dao.getPolicyTypeList(desiredType.getName(), desiredType.getVersion());
+            if (lst.isEmpty()) {
+                return null;
+            }
+
+            type = lst.get(0);
+            typeCache.put(desiredType, type);
+        }
+
+        return type;
+    }
+
     /**
      * Gets the policy, referenced by an identifier. Loads it from the cache, if possible.
      * Otherwise, gets it from the DB.
@@ -106,8 +136,7 @@ public class SessionData {
 
             List<ToscaPolicy> lst = dao.getFilteredPolicyList(filterBuilder.build());
             if (lst.isEmpty()) {
-                throw new PfModelException(Status.NOT_FOUND,
-                                "cannot find policy: " + desiredPolicy.getName() + " " + desiredPolicy.getVersion());
+                return null;
             }
 
             policy = lst.get(0);
index 256d3af..2fca684 100644 (file)
@@ -48,6 +48,7 @@ import org.onap.policy.models.pdp.concepts.PdpStateChange;
 import org.onap.policy.models.pdp.concepts.PdpUpdate;
 import org.onap.policy.models.provider.PolicyModelsProvider;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
 import org.onap.policy.pap.main.PapConstants;
 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
@@ -233,6 +234,16 @@ public class ProviderSuper {
         return loadFile(fileName, ToscaPolicy.class);
     }
 
+    /**
+     * Loads a policy type.
+     *
+     * @param fileName name of the file from which to load
+     * @return a policy type
+     */
+    protected ToscaPolicyType loadPolicyType(String fileName) {
+        return loadFile(fileName, ToscaPolicyType.class);
+    }
+
     /**
      * Loads an object from a JSON file.
      *
index 406345c..8166417 100644 (file)
@@ -83,6 +83,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
         super.setUp();
 
         when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json"));
+        when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json")));
 
         prov = new PdpGroupDeployProvider();
     }
@@ -356,14 +357,36 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
         assertGroupUpdateOnly(group);
     }
 
+    @Test
+    public void testAddSubGroup_ValidationPolicyTypeNotFound() throws Exception {
+        PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
+        PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
+        when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+        when(dao.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList());
+
+        assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy type");
+    }
+
+    @Test
+    public void testAddSubGroup_ValidationPolicyTypeDaoEx() throws Exception {
+        PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
+        PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
+        when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+        PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION);
+        when(dao.getPolicyTypeList(any(), any())).thenThrow(exc);
+
+        assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isSameAs(exc);
+    }
+
     @Test
     public void testAddSubGroup_ValidationPolicyNotFound() throws Exception {
         PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
         PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
         when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
 
-        PfModelException exc = new PfModelException(Status.NOT_FOUND, EXPECTED_EXCEPTION);
-        when(dao.getFilteredPolicyList(any())).thenThrow(exc);
+        when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList());
 
         assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy");
     }
index e8ddd82..55c6f3d 100644 (file)
@@ -150,6 +150,17 @@ public class TestProviderBase extends ProviderSuper {
                         .hasCause(exc);
     }
 
+    @Test
+    public void testGetPolicy_NotFound() throws Exception {
+        when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList());
+
+        assertThatThrownBy(() -> prov.process(loadRequest(), this::handle)).isInstanceOf(PfModelRuntimeException.class)
+                        .hasMessage("cannot find policy: policyA 1.2.3").matches(thr -> {
+                            PfModelRuntimeException exc = (PfModelRuntimeException) thr;
+                            return (exc.getErrorResponse().getResponseCode() == Status.NOT_FOUND);
+                        });
+    }
+
     @Test
     public void testGetGroup() throws Exception {
         when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json"))
index 17acd5a..f586d16 100644 (file)
@@ -51,6 +51,7 @@ import org.onap.policy.models.pdp.concepts.PdpUpdate;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
 
 public class TestSessionData extends ProviderSuper {
@@ -90,6 +91,32 @@ public class TestSessionData extends ProviderSuper {
         session = new SessionData(dao);
     }
 
+    @Test
+    public void testGetPolicyType() throws Exception {
+        ToscaPolicyType policy1 = makePolicyType(POLICY_TYPE, POLICY_TYPE_VERSION);
+        when(dao.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenReturn(Arrays.asList(policy1));
+
+        assertSame(policy1, session.getPolicyType(type));
+
+        // retrieve a second time - should use cache
+        assertSame(policy1, session.getPolicyType(type));
+    }
+
+    @Test
+    public void testGetPolicyType_NotFound() throws Exception {
+        when(dao.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList());
+
+        assertNull(session.getPolicyType(type));
+    }
+
+    @Test
+    public void testGetPolicyType_DaoEx() throws Exception {
+        PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, EXPECTED_EXCEPTION);
+        when(dao.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenThrow(ex);
+
+        assertThatThrownBy(() -> session.getPolicyType(type)).isSameAs(ex);
+    }
+
     @Test
     public void testGetPolicy_NullVersion() throws Exception {
         ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION);
@@ -148,12 +175,12 @@ public class TestSessionData extends ProviderSuper {
     public void testGetPolicy_NotFound() throws Exception {
         when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList());
 
-        assertThatThrownBy(() -> session.getPolicy(ident)).hasMessage("cannot find policy: myPolicy 1.2.3");
+        assertNull(session.getPolicy(ident));
     }
 
     @Test
     public void testGetPolicy_DaoEx() throws Exception {
-        PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, "expected exception");
+        PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, EXPECTED_EXCEPTION);
         when(dao.getFilteredPolicyList(any())).thenThrow(ex);
 
         assertThatThrownBy(() -> session.getPolicy(ident)).isSameAs(ex);
@@ -270,6 +297,15 @@ public class TestSessionData extends ProviderSuper {
         assertEquals(Arrays.asList(change1, change2, change3).toString(), lst.toString());
     }
 
+    private ToscaPolicyType makePolicyType(String name, String version) {
+        ToscaPolicyType type = new ToscaPolicyType();
+
+        type.setName(name);
+        type.setVersion(version);
+
+        return type;
+    }
+
     private ToscaPolicy makePolicy(String name, String version) {
         ToscaPolicy policy = new ToscaPolicy();
 
index 98b6452..28e5d6e 100644 (file)
@@ -6,7 +6,7 @@ policy_types:
         description: a base policy type for all policies that governs monitoring provisioning
         version: 1.0.0
   -
-    onap.policy.monitoring.cdap.tca.hi.lo.app:
+    onap.policies.monitoring.cdap.tca.hi.lo.app:
         derived_from: onap.policies.Monitoring
         version: 1.0.0
         properties:
diff --git a/main/src/test/resources/simpleDeploy/daoPolicyType.json b/main/src/test/resources/simpleDeploy/daoPolicyType.json
new file mode 100644 (file)
index 0000000..e71bf98
--- /dev/null
@@ -0,0 +1,4 @@
+{
+    "name": "typeA",
+    "version": "100.2.3"
+}