Add Legacy Op Policy Persistence 22/83422/1
authorliamfallon <liam.fallon@est.tech>
Tue, 26 Mar 2019 22:31:43 +0000 (22:31 +0000)
committerliamfallon <liam.fallon@est.tech>
Tue, 26 Mar 2019 22:31:43 +0000 (22:31 +0000)
Legacy operational policies now fully supported for
serialization and persistence from provider through to
database and back. Unit test coverage completed
also

Issue-ID: POLICY-1095
Change-Id: I65755859c94b50edee537d2685f51a7838c6541f
Signed-off-by: liamfallon <liam.fallon@est.tech>
29 files changed:
models-base/src/main/java/org/onap/policy/models/base/PfConceptKey.java
models-base/src/main/java/org/onap/policy/models/base/PfKey.java
models-base/src/main/java/org/onap/policy/models/base/PfKeyUse.java
models-base/src/main/java/org/onap/policy/models/base/PfReferenceKey.java
models-base/src/main/java/org/onap/policy/models/base/PfUtils.java
models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java
models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java
models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java
models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java
models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java
models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseUtils.java
models-examples/src/main/resources/policies/vDNS.policy.monitoring.input.tosca.json
models-examples/src/main/resources/policies/vFirewall.policy.monitoring.input.tosca.json
models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroup.java
models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPdpGroup.java
models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPdpSubGroup.java
models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java
models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java
models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java [new file with mode: 0644]
models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java [new file with mode: 0644]
models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyOperationalPolicy.java
models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java
models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java [new file with mode: 0644]
models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyToscaProvider.java [deleted file]
models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicies.java
models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java
models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java [new file with mode: 0644]
models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProviderTest.java [new file with mode: 0644]
models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/serialization/LegacyOperationalPolicySerializationTest.java

index 9f57585..84239e5 100644 (file)
@@ -176,6 +176,73 @@ public class PfConceptKey extends PfKey {
         return !(compatibility == Compatibility.DIFFERENT || compatibility == Compatibility.MAJOR);
     }
 
+    @Override
+    public boolean isNewerThan(@NonNull final PfKey otherKey) {
+        Assertions.instanceOf(otherKey, PfConceptKey.class);
+
+        final PfConceptKey otherConceptKey = (PfConceptKey) otherKey;
+
+        if (this.equals(otherConceptKey)) {
+            return false;
+        }
+
+        if (!this.getName().equals(otherConceptKey.getName())) {
+            return this.getName().compareTo(otherConceptKey.getName()) > 0;
+        }
+
+        final String[] thisVersionArray = getVersion().split("\\.");
+        final String[] otherVersionArray = otherConceptKey.getVersion().split("\\.");
+
+        // There must always be at least one element in each version
+        if (!thisVersionArray[0].equals(otherVersionArray[0])) {
+            return thisVersionArray[0].compareTo(otherVersionArray[0]) > 0;
+        }
+
+        if (thisVersionArray.length >= 2 && otherVersionArray.length >= 2
+                        && !thisVersionArray[1].equals(otherVersionArray[1])) {
+            return thisVersionArray[1].compareTo(otherVersionArray[1]) > 0;
+        }
+
+        if (thisVersionArray.length >= 3 && otherVersionArray.length >= 3
+                        && !thisVersionArray[2].equals(otherVersionArray[2])) {
+            return thisVersionArray[2].compareTo(otherVersionArray[2]) > 0;
+        }
+
+        return false;
+    }
+
+    @Override
+    public int getMajorVersion() {
+        final String[] versionArray = getVersion().split("\\.");
+
+        // There must always be at least one element in each version
+        return Integer.parseInt(versionArray[0]);
+    }
+
+    @Override
+    public int getMinorVersion() {
+        final String[] versionArray = getVersion().split("\\.");
+
+        if (versionArray.length >= 2) {
+            return Integer.parseInt(versionArray[1]);
+        }
+        else {
+            return 0;
+        }
+    }
+
+    @Override
+    public int getPatchVersion() {
+        final String[] versionArray = getVersion().split("\\.");
+
+        if (versionArray.length >= 3) {
+            return Integer.parseInt(versionArray[2]);
+        }
+        else {
+            return 0;
+        }
+    }
+
     @Override
     public PfValidationResult validate(final PfValidationResult result) {
         final String nameValidationErrorMessage = Assertions.getStringParameterValidationMessage(NAME_TOKEN, name,
index 6e9035e..5407030 100644 (file)
@@ -101,10 +101,39 @@ public abstract class PfKey extends PfConcept {
      */
     public abstract boolean isCompatible(@NonNull PfKey otherKey);
 
+    /**
+     * Check if this key is a newer version than the other key.
+     *
+     * @param otherKey the key to check against
+     * @return true, if this key is newer than the other key
+     */
+    public abstract boolean isNewerThan(@NonNull PfKey otherKey);
+
     /**
      * Check if a key equals its null key.
      *
      * @return true, if the key is a null key
      */
     public abstract boolean isNullKey();
+
+    /**
+     * Get the major version of a key.
+     *
+     * @return the major version of a key
+     */
+    public abstract int getMajorVersion();
+
+    /**
+     * Get the minor version of a key.
+     *
+     * @return the minor version of a key
+     */
+    public abstract int getMinorVersion();
+
+    /**
+     * Get the patch version of a key.
+     *
+     * @return the patch version of a key
+     */
+    public abstract int getPatchVersion();
 }
index 57141c2..836707e 100644 (file)
@@ -110,6 +110,26 @@ public class PfKeyUse extends PfKey {
         return usedKey.isCompatible(otherKey);
     }
 
+    @Override
+    public boolean isNewerThan(@NonNull final PfKey otherKey) {
+        return usedKey.isCompatible(otherKey);
+    }
+
+    @Override
+    public int getMajorVersion() {
+        return usedKey.getMajorVersion();
+    }
+
+    @Override
+    public int getMinorVersion() {
+        return usedKey.getMinorVersion();
+    }
+
+    @Override
+    public int getPatchVersion() {
+        return usedKey.getPatchVersion();
+    }
+
     @Override
     public void clean() {
         usedKey.clean();
index 19e8bee..185ccfa 100644 (file)
@@ -28,6 +28,7 @@ import javax.persistence.Embeddable;
 
 import lombok.Data;
 import lombok.EqualsAndHashCode;
+import lombok.NonNull;
 
 import org.onap.policy.common.utils.validation.Assertions;
 import org.onap.policy.models.base.PfValidationResult.ValidationResult;
@@ -305,7 +306,7 @@ public class PfReferenceKey extends PfKey {
     }
 
     @Override
-    public boolean isCompatible(final PfKey otherKey) {
+    public boolean isCompatible(@NonNull final PfKey otherKey) {
         if (!(otherKey instanceof PfReferenceKey)) {
             return false;
         }
@@ -314,6 +315,31 @@ public class PfReferenceKey extends PfKey {
         return this.getParentConceptKey().isCompatible(otherReferenceKey.getParentConceptKey());
     }
 
+    @Override
+    public int getMajorVersion() {
+        return this.getParentConceptKey().getMajorVersion();
+    }
+
+    @Override
+    public int getMinorVersion() {
+        return this.getParentConceptKey().getMinorVersion();
+    }
+
+    @Override
+    public int getPatchVersion() {
+        return this.getParentConceptKey().getPatchVersion();
+    }
+
+
+    @Override
+    public boolean isNewerThan(@NonNull final PfKey otherKey) {
+        Assertions.instanceOf(otherKey, PfReferenceKey.class);
+
+        final PfReferenceKey otherReferenceKey = (PfReferenceKey) otherKey;
+
+        return this.getParentConceptKey().isNewerThan(otherReferenceKey.getParentConceptKey());
+    }
+
     @Override
     public PfValidationResult validate(final PfValidationResult result) {
         final String parentNameValidationErrorMessage = Assertions.getStringParameterValidationMessage(PARENT_KEY_NAME,
index 8e77d3f..7bdd9a5 100644 (file)
@@ -21,6 +21,7 @@
 
 package org.onap.policy.models.base;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.function.Function;
 import java.util.stream.Collectors;
@@ -72,7 +73,7 @@ public final class PfUtils {
      */
     public static <T> List<T> mapList(List<T> source, Function<T, T> mapFunc) {
         if (source == null) {
-            return null;
+            return new ArrayList<>();
         }
 
         return source.stream().map(mapFunc).collect(Collectors.toList());
index 848889c..a4c5047 100644 (file)
@@ -42,9 +42,10 @@ public class PfKeyTest {
             new PfConceptKey("some bad key id");
             fail("This test should throw an exception");
         } catch (IllegalArgumentException e) {
-            assertEquals("parameter \"id\": value \"some bad key id\", "
+            assertEquals(
+                    "parameter \"id\": value \"some bad key id\", "
                             + "does not match regular expression \"[A-Za-z0-9\\-_\\.]+:[0-9].[0-9].[0-9]\"",
-                            e.getMessage());
+                    e.getMessage());
         }
 
         PfConceptKey someKey0 = new PfConceptKey();
@@ -110,19 +111,19 @@ public class PfKeyTest {
         assertFalse(someKey1.isCompatible(new DummyPfKey()));
 
         assertEquals(PfValidationResult.ValidationResult.VALID,
-                        someKey0.validate(new PfValidationResult()).getValidationResult());
+                someKey0.validate(new PfValidationResult()).getValidationResult());
         assertEquals(PfValidationResult.ValidationResult.VALID,
-                        someKey1.validate(new PfValidationResult()).getValidationResult());
+                someKey1.validate(new PfValidationResult()).getValidationResult());
         assertEquals(PfValidationResult.ValidationResult.VALID,
-                        someKey2.validate(new PfValidationResult()).getValidationResult());
+                someKey2.validate(new PfValidationResult()).getValidationResult());
         assertEquals(PfValidationResult.ValidationResult.VALID,
-                        someKey3.validate(new PfValidationResult()).getValidationResult());
+                someKey3.validate(new PfValidationResult()).getValidationResult());
         assertEquals(PfValidationResult.ValidationResult.VALID,
-                        someKey4.validate(new PfValidationResult()).getValidationResult());
+                someKey4.validate(new PfValidationResult()).getValidationResult());
         assertEquals(PfValidationResult.ValidationResult.VALID,
-                        someKey5.validate(new PfValidationResult()).getValidationResult());
+                someKey5.validate(new PfValidationResult()).getValidationResult());
         assertEquals(PfValidationResult.ValidationResult.VALID,
-                        someKey6.validate(new PfValidationResult()).getValidationResult());
+                someKey6.validate(new PfValidationResult()).getValidationResult());
 
         someKey0.clean();
         assertNotNull(someKey0.toString());
@@ -150,14 +151,14 @@ public class PfKeyTest {
     @Test
     public void testNullArguments() {
         try {
-            new PfConceptKey((String)null);
+            new PfConceptKey((String) null);
             fail("test should throw an exception here");
         } catch (Exception exc) {
             assertEquals("id is marked @NonNull but is null", exc.getMessage());
         }
 
         try {
-            new PfConceptKey((PfConceptKey)null);
+            new PfConceptKey((PfConceptKey) null);
             fail("id is marked @NonNull but is null");
         } catch (Exception exc) {
             assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
@@ -207,9 +208,9 @@ public class PfKeyTest {
             nameField.set(testKey, "TheKey");
             nameField.setAccessible(false);
             assertEquals(
-                "name invalid-parameter name with value Key Name "
-                    + "does not match regular expression [A-Za-z0-9\\-_\\.]+",
-                validationResult.getMessageList().get(0).getMessage());
+                    "name invalid-parameter name with value Key Name "
+                            + "does not match regular expression [A-Za-z0-9\\-_\\.]+",
+                    validationResult.getMessageList().get(0).getMessage());
         } catch (Exception validationException) {
             fail("test should not throw an exception");
         }
@@ -223,11 +224,105 @@ public class PfKeyTest {
             versionField.set(testKey, "0.0.1");
             versionField.setAccessible(false);
             assertEquals(
-                "version invalid-parameter version with value Key Version "
-                    + "does not match regular expression [A-Za-z0-9.]+",
-                validationResult.getMessageList().get(0).getMessage());
+                    "version invalid-parameter version with value Key Version "
+                            + "does not match regular expression [A-Za-z0-9.]+",
+                    validationResult.getMessageList().get(0).getMessage());
         } catch (Exception validationException) {
             fail("test should not throw an exception");
         }
     }
+
+    @Test
+    public void testkeynewerThan() {
+        PfConceptKey key1 = new PfConceptKey("Key1", "1.2.3");
+
+        try {
+            key1.isNewerThan(null);
+            fail("test should throw an exception");
+        } catch (Exception exc) {
+            assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            key1.isNewerThan(new PfReferenceKey());
+            fail("test should throw an exception");
+        } catch (Exception exc) {
+            assertEquals("org.onap.policy.models.base.PfReferenceKey is not "
+                    + "an instance of org.onap.policy.models.base.PfConceptKey", exc.getMessage());
+        }
+
+        assertFalse(key1.isNewerThan(key1));
+
+        PfConceptKey key1a = new PfConceptKey("Key1a", "1.2.3");
+        assertFalse(key1.isNewerThan(key1a));
+
+        PfConceptKey key1b = new PfConceptKey("Key0", "1.2.3");
+        assertTrue(key1.isNewerThan(key1b));
+
+        key1a.setName("Key1");
+        assertFalse(key1.isNewerThan(key1a));
+
+        key1a.setVersion("0.2.3");
+        assertTrue(key1.isNewerThan(key1a));
+        key1a.setVersion("2.2.3");
+        assertFalse(key1.isNewerThan(key1a));
+        key1a.setVersion("1.2.3");
+        assertFalse(key1.isNewerThan(key1a));
+
+        key1a.setVersion("1.1.3");
+        assertTrue(key1.isNewerThan(key1a));
+        key1a.setVersion("1.3.3");
+        assertFalse(key1.isNewerThan(key1a));
+        key1a.setVersion("1.2.3");
+        assertFalse(key1.isNewerThan(key1a));
+
+        key1a.setVersion("1.2.2");
+        assertTrue(key1.isNewerThan(key1a));
+        key1a.setVersion("1.2.4");
+        assertFalse(key1.isNewerThan(key1a));
+        key1a.setVersion("1.2.3");
+        assertFalse(key1.isNewerThan(key1a));
+
+        key1.setVersion("1");
+        assertFalse(key1.isNewerThan(key1a));
+        key1a.setVersion("1");
+        assertFalse(key1.isNewerThan(key1a));
+
+        PfReferenceKey refKey = new PfReferenceKey();
+
+        try {
+            refKey.isNewerThan(null);
+            fail("test should throw an exception");
+        } catch (Exception exc) {
+            assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            refKey.isNewerThan(new PfConceptKey());
+            fail("test should throw an exception");
+        } catch (Exception exc) {
+            assertEquals("org.onap.policy.models.base.PfConceptKey is not "
+                    + "an instance of org.onap.policy.models.base.PfReferenceKey", exc.getMessage());
+        }
+
+        assertFalse(refKey.isNewerThan(refKey));
+    }
+
+    @Test
+    public void testmajorMinorPatch() {
+        PfConceptKey key = new PfConceptKey("Key", "1");
+        assertEquals(1, key.getMajorVersion());
+        assertEquals(0, key.getMinorVersion());
+        assertEquals(0, key.getPatchVersion());
+
+        key = new PfConceptKey("Key", "1.2");
+        assertEquals(1, key.getMajorVersion());
+        assertEquals(2, key.getMinorVersion());
+        assertEquals(0, key.getPatchVersion());
+
+        key = new PfConceptKey("Key", "1.2.3");
+        assertEquals(1, key.getMajorVersion());
+        assertEquals(2, key.getMinorVersion());
+        assertEquals(3, key.getPatchVersion());
+    }
 }
index ccdc72d..72df28f 100644 (file)
@@ -131,5 +131,9 @@ public class PfKeyUseTest {
         } catch (Exception exc) {
             assertEquals("error copying concept key: Some error message", exc.getMessage());
         }
+
+        assertEquals(0, testKeyUse.getMajorVersion());
+        assertEquals(0, testKeyUse.getMinorVersion());
+        assertEquals(0, testKeyUse.getPatchVersion());
     }
 }
index 64d4bc6..edf4466 100644 (file)
@@ -58,6 +58,10 @@ public class PfReferenceKeyTest {
         testReferenceKey.setParentConceptKey(new PfConceptKey("PN", "0.0.1"));
         assertEquals("PN:0.0.1", testReferenceKey.getParentConceptKey().getId());
 
+        assertEquals(0, testReferenceKey.getMajorVersion());
+        assertEquals(0, testReferenceKey.getMinorVersion());
+        assertEquals(1, testReferenceKey.getPatchVersion());
+
         assertEquals(1, testReferenceKey.getKeys().size());
         assertFalse(testReferenceKey.isNullKey());
 
@@ -76,6 +80,13 @@ public class PfReferenceKeyTest {
         testReferenceKey.setLocalName("NLN");
         assertEquals("NLN", testReferenceKey.getLocalName());
 
+        try {
+            testReferenceKey.isCompatible(null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
+        }
+
         assertFalse(testReferenceKey.isCompatible(PfConceptKey.getNullKey()));
         assertFalse(testReferenceKey.isCompatible(PfReferenceKey.getNullKey()));
         assertTrue(testReferenceKey.isCompatible(testReferenceKey));
index bdbab5c..11ddf31 100644 (file)
@@ -1,4 +1,4 @@
-/*
+/*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2019 Nordix Foundation.
  *  Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
@@ -23,7 +23,7 @@ package org.onap.policy.models.base;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 
 import java.util.Arrays;
 import java.util.List;
@@ -47,9 +47,10 @@ public class PfUtilsTest {
 
     @Test
     public void testMapList() {
-        assertNull(PfUtils.mapList(null, item -> {
+        List<Object> resultList = PfUtils.mapList(null, item -> {
             throw new RuntimeException("should not be invoked");
-        }));
+        });
+        assertTrue(resultList.isEmpty());
 
         List<String> origList = Arrays.asList("abc", "def");
         List<String> newList = PfUtils.mapList(origList, text -> text + "X");
index 6cf41e6..f485b0d 100644 (file)
@@ -23,11 +23,13 @@ package org.onap.policy.models.base.testconcepts;
 import java.util.Arrays;
 import java.util.List;
 
+import lombok.NonNull;
+
 import org.onap.policy.models.base.PfConcept;
 import org.onap.policy.models.base.PfKey;
 import org.onap.policy.models.base.PfValidationResult;
 
-public class DummyPfKey  extends PfKey {
+public class DummyPfKey extends PfKey {
     private static final long serialVersionUID = 1L;
 
     @Override
@@ -94,4 +96,25 @@ public class DummyPfKey  extends PfKey {
     public PfConcept copyTo(PfConcept target) {
         return null;
     }
+
+    @Override
+    public boolean isNewerThan(@NonNull PfKey otherKey) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public int getMajorVersion() {
+        return 0;
+    }
+
+    @Override
+    public int getMinorVersion() {
+        return 0;
+    }
+
+    @Override
+    public int getPatchVersion() {
+        return 0;
+    }
 }
index 6346f9a..5052d36 100644 (file)
@@ -24,7 +24,7 @@ import java.util.ArrayList;
 import java.util.List;
 
 /**
- * Utility class for managing {@link ErrorResponse objects}
+ * Utility class for managing {@link ErrorResponse objects}.
  *
  * @author Liam Fallon (liam.fallon@est.tech)
  */
index 56c49d0..270613a 100644 (file)
@@ -1,50 +1,60 @@
 {
-       "tosca_definitions_version": "tosca_simple_yaml_1_0_0",
-       "topology_template": {
-               "policies": [
-                       {
-                               "onap.scaleout.tca": {
-                                       "type": "onap.policies.monitoring.cdap.tca.hi.lo.app",
-                                       "version": "1.0.0",
-                                       "metadata": {
-                                               "policy-id": "onap.scaleout.tca"
-                                       },
-                                       "properties": {
-                                               "tca_policy": {
-                                                       "domain": "measurementsForVfScaling",
-                                                       "metricsPerEventName": [
-                                                               {
-                                                                       "eventName": "vLoadBalancer",
-                                                                       "controlLoopSchemaType": "VNF",
-                                                                       "policyScope": "type=configuration",
-                                                                       "policyName": "onap.scaleout.tca",
-                                                                       "policyVersion": "v0.0.1",
-                                                                       "thresholds": [
-                                                                               {
-                                                                                       "closedLoopControlName": "ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3",
-                                                                                       "closedLoopEventStatus": "ONSET",
-                                                                                       "version": "1.0.2",
-                                                                                       "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
-                                                                                       "thresholdValue": 500,
-                                                                                       "direction": "LESS_OR_EQUAL",
-                                                                                       "severity": "MAJOR"
-                                                                               },
-                                                                               {
-                                                                                       "closedLoopControlName": "ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3",
-                                                                                       "closedLoopEventStatus": "ONSET",
-                                                                                       "version": "1.0.2",
-                                                                                       "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
-                                                                                       "thresholdValue": 5000,
-                                                                                       "direction": "GREATER_OR_EQUAL",
-                                                                                       "severity": "CRITICAL"
-                                                                               }
-                                                                       ]
-                                                               }
-                                                       ]
-                                               }
-                                       }
-                               }
-                       }
-               ]
-       }
-}
+    "tosca_definitions_version": "tosca_simple_yaml_1_0_0",
+    "topology_template": 
+    {
+        "policies": 
+        [
+            {
+                "onap.scaleout.tca": 
+                {
+                    "type": "onap.policies.monitoring.cdap.tca.hi.lo.app",
+                    "version": "1.0.0",
+                    "metadata": 
+                    {
+                        "policy-id": "onap.scaleout.tca"
+                    },
+
+                    "properties": 
+                    {
+                        "tca_policy": 
+                        {
+                            "domain": "measurementsForVfScaling",
+                            "metricsPerEventName": 
+                            [
+                                {
+                                    "eventName": "vLoadBalancer",
+                                    "controlLoopSchemaType": "VNF",
+                                    "policyScope": "type=configuration",
+                                    "policyName": "onap.scaleout.tca",
+                                    "policyVersion": "v0.0.1",
+                                    "thresholds": 
+                                    [
+                                        {
+                                            "closedLoopControlName": "ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3",
+                                            "closedLoopEventStatus": "ONSET",
+                                            "version": "1.0.2",
+                                            "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
+                                            "thresholdValue": 500,
+                                            "direction": "LESS_OR_EQUAL",
+                                            "severity": "MAJOR"
+                                        },
+
+                                        {
+                                            "closedLoopControlName": "ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3",
+                                            "closedLoopEventStatus": "ONSET",
+                                            "version": "1.0.2",
+                                            "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
+                                            "thresholdValue": 5000,
+                                            "direction": "GREATER_OR_EQUAL",
+                                            "severity": "CRITICAL"
+                                        }
+                                    ]
+                                }
+                            ]
+                        }
+                    }
+                }
+            }
+        ]
+    }
+}
\ No newline at end of file
index 29c29b8..aef04c9 100644 (file)
@@ -1,50 +1,60 @@
 {
-       "tosca_definitions_version": "tosca_simple_yaml_1_0_0",
-       "topology_template": {
-               "policies": [
-                       {
-                               "onap.vfirewall.tca": {
-                                       "type": "onap.policy.monitoring.cdap.tca.hi.lo.app",
-                                       "version": "1.0.0",
-                    "metadata": {
+    "tosca_definitions_version": "tosca_simple_yaml_1_0_0",
+    "topology_template": 
+    {
+        "policies": 
+        [
+            {
+                "onap.vfirewall.tca": 
+                {
+                    "type": "onap.policy.monitoring.cdap.tca.hi.lo.app",
+                    "version": "1.0.0",
+                    "metadata": 
+                    {
                         "policy-id": "onap.vfirewall.tca"
                     },
-                                       "properties": {
-                                               "tca_policy": {
-                                                       "domain": "measurementsForVfScaling",
-                                                       "metricsPerEventName": [
-                                                               {
-                                                                       "eventName": "vLoadBalancer",
-                                                                       "controlLoopSchemaType": "VNF",
-                                                                       "policyScope": "resource=vLoadBalancer;type=configuration",
-                                                                       "policyName": "onap.vfirewall.tca",
-                                                                       "policyVersion": "v0.0.1",
-                                                                       "thresholds": [
-                                                                               {
-                                                                                       "closedLoopControlName": "ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a",
-                                                                                       "closedLoopEventStatus": "ONSET",
-                                                                                       "version": "1.0.2",
-                                                                                       "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
-                                                                                       "thresholdValue": 500,
-                                                                                       "direction": "LESS_OR_EQUAL",
-                                                                                       "severity": "MAJOR"
-                                                                               },
-                                                                               {
-                                                                                       "closedLoopControlName": "ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a",
-                                                                                       "closedLoopEventStatus": "ONSET",
-                                                                                       "version": "1.0.2",
-                                                                                       "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
-                                                                                       "thresholdValue": 5000,
-                                                                                       "direction": "GREATER_OR_EQUAL",
-                                                                                       "severity": "CRITICAL"
-                                                                               }
-                                                                       ]
-                                                               }
-                                                       ]
-                                               }
-                                       }
-                               }
-                       }
-               ]
-       }
-}
+
+                    "properties": 
+                    {
+                        "tca_policy": 
+                        {
+                            "domain": "measurementsForVfScaling",
+                            "metricsPerEventName": 
+                            [
+                                {
+                                    "eventName": "vLoadBalancer",
+                                    "controlLoopSchemaType": "VNF",
+                                    "policyScope": "resource=vLoadBalancer;type=configuration",
+                                    "policyName": "onap.vfirewall.tca",
+                                    "policyVersion": "v0.0.1",
+                                    "thresholds": 
+                                    [
+                                        {
+                                            "closedLoopControlName": "ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a",
+                                            "closedLoopEventStatus": "ONSET",
+                                            "version": "1.0.2",
+                                            "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
+                                            "thresholdValue": 500,
+                                            "direction": "LESS_OR_EQUAL",
+                                            "severity": "MAJOR"
+                                        },
+
+                                        {
+                                            "closedLoopControlName": "ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a",
+                                            "closedLoopEventStatus": "ONSET",
+                                            "version": "1.0.2",
+                                            "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated",
+                                            "thresholdValue": 5000,
+                                            "direction": "GREATER_OR_EQUAL",
+                                            "severity": "CRITICAL"
+                                        }
+                                    ]
+                                }
+                            ]
+                        }
+                    }
+                }
+            }
+        ]
+    }
+}
\ No newline at end of file
index bb67a40..4a26b16 100644 (file)
@@ -24,6 +24,7 @@ package org.onap.policy.models.pdp.concepts;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
index 22c7a71..51bb66c 100644 (file)
@@ -1,8 +1,9 @@
-/*
+/*-
  * ============LICENSE_START=======================================================
  * ONAP Policy Models
  * ================================================================================
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -42,7 +43,7 @@ public class TestPdpGroup {
         PdpGroup orig = new PdpGroup();
 
         // verify with null values
-        assertEquals(orig.toString(), new PdpGroup(orig).toString());
+        assertEquals("PdpGroup(pdpGroupState=null, properties=null, pdpSubgroups=[])", new PdpGroup(orig).toString());
 
         // verify with all values
         orig.setDescription("my-descript");
@@ -60,7 +61,11 @@ public class TestPdpGroup {
         props.put("key-B", "value-B");
         orig.setProperties(props);
 
-        assertEquals(orig.toString(), new PdpGroup(orig).toString());
+        assertEquals("PdpGroup(pdpGroupState=SAFE, properties={key-A=value-A, key-B=value-B}, "
+                + "pdpSubgroups=[PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], "
+                + "currentInstanceCount=10, desiredInstanceCount=0, properties=null, pdpInstances=[]), "
+                + "PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], currentInstanceCount=11, "
+                + "desiredInstanceCount=0, properties=null, pdpInstances=[])])", new PdpGroup(orig).toString());
     }
 
     @Test
index 2a20d2f..bc6363f 100644 (file)
@@ -1,8 +1,9 @@
-/*
+/*-
  * ============LICENSE_START=======================================================
  * ONAP Policy Models
  * ================================================================================
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -41,7 +42,10 @@ public class TestPdpSubGroup {
         PdpSubGroup orig = new PdpSubGroup();
 
         // verify with null values
-        assertEquals(orig.toString(), new PdpSubGroup(orig).toString());
+        assertEquals(
+                "PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], "
+                        + "currentInstanceCount=0, desiredInstanceCount=0, properties=null, pdpInstances=[])",
+                new PdpSubGroup(orig).toString());
 
         // verify with all values
         orig.setCurrentInstanceCount(10);
index 970aa8f..43f75d2 100644 (file)
@@ -41,7 +41,7 @@ import org.onap.policy.models.provider.PolicyModelsProvider;
 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy;
 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
-import org.onap.policy.models.tosca.legacy.provider.LegacyToscaProvider;
+import org.onap.policy.models.tosca.legacy.provider.LegacyProvider;
 import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
 import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider;
 import org.slf4j.Logger;
@@ -190,53 +190,53 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider {
     @Override
     public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException {
         assertInitilized();
-        return new LegacyToscaProvider().getOperationalPolicy(pfDao, policyId);
+        return new LegacyProvider().getOperationalPolicy(pfDao, policyId);
     }
 
     @Override
     public LegacyOperationalPolicy createOperationalPolicy(
             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
         assertInitilized();
-        return new LegacyToscaProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
+        return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
     }
 
     @Override
     public LegacyOperationalPolicy updateOperationalPolicy(
             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
         assertInitilized();
-        return new LegacyToscaProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
+        return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
     }
 
     @Override
     public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException {
         assertInitilized();
-        return new LegacyToscaProvider().deleteOperationalPolicy(pfDao, policyId);
+        return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId);
     }
 
     @Override
     public LegacyGuardPolicy getGuardPolicy(@NonNull final String policyId) throws PfModelException {
         assertInitilized();
-        return new LegacyToscaProvider().getGuardPolicy(pfDao, policyId);
+        return new LegacyProvider().getGuardPolicy(pfDao, policyId);
     }
 
     @Override
     public LegacyGuardPolicy createGuardPolicy(@NonNull final LegacyGuardPolicy legacyGuardPolicy)
             throws PfModelException {
         assertInitilized();
-        return new LegacyToscaProvider().createGuardPolicy(pfDao, legacyGuardPolicy);
+        return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy);
     }
 
     @Override
     public LegacyGuardPolicy updateGuardPolicy(@NonNull final LegacyGuardPolicy legacyGuardPolicy)
             throws PfModelException {
         assertInitilized();
-        return new LegacyToscaProvider().updateGuardPolicy(pfDao, legacyGuardPolicy);
+        return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy);
     }
 
     @Override
     public LegacyGuardPolicy deleteGuardPolicy(@NonNull final String policyId) throws PfModelException {
         assertInitilized();
-        return new LegacyToscaProvider().deleteGuardPolicy(pfDao, policyId);
+        return new LegacyProvider().deleteGuardPolicy(pfDao, policyId);
     }
 
     @Override
index c5dd8f0..e4ecb9d 100644 (file)
@@ -316,10 +316,30 @@ public class DatabasePolicyModelsProviderTest {
                 assertEquals("policy not found: NULL:0.0.0", npe.getMessage());
             }
 
-            assertNull(databaseProvider.getOperationalPolicy("policy_id"));
-            assertNull(databaseProvider.createOperationalPolicy(new LegacyOperationalPolicy()));
-            assertNull(databaseProvider.updateOperationalPolicy(new LegacyOperationalPolicy()));
-            assertNull(databaseProvider.deleteOperationalPolicy("policy_id"));
+            try {
+                assertNull(databaseProvider.getOperationalPolicy("policy_id"));
+                fail("test should throw an exception");
+            } catch (Exception npe) {
+                assertEquals("no policy found for policy ID: policy_id", npe.getMessage());
+            }
+            try {
+                assertNull(databaseProvider.createOperationalPolicy(new LegacyOperationalPolicy()));
+                fail("test should throw an exception");
+            } catch (Exception npe) {
+                assertEquals("name is marked @NonNull but is null", npe.getMessage());
+            }
+            try {
+                assertNull(databaseProvider.updateOperationalPolicy(new LegacyOperationalPolicy()));
+                fail("test should throw an exception");
+            } catch (Exception npe) {
+                assertEquals("no policy found for policy ID: null", npe.getMessage());
+            }
+            try {
+                assertNull(databaseProvider.deleteOperationalPolicy("policy_id"));
+                fail("test should throw an exception");
+            } catch (Exception npe) {
+                assertEquals("no policy found for policy ID: policy_id", npe.getMessage());
+            }
 
             assertNull(databaseProvider.getGuardPolicy("policy_id"));
             assertNull(databaseProvider.createGuardPolicy(new LegacyGuardPolicy()));
diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java
new file mode 100644 (file)
index 0000000..90d00fc
--- /dev/null
@@ -0,0 +1,143 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.models.provider.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import com.google.gson.Gson;
+
+import java.util.Base64;
+
+import lombok.NonNull;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
+import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test persistence of monitoring policies to and from the database.
+ *
+ * @author Liam Fallon (liam.fallon@est.tech)
+ */
+public class PolicyLegacyOperationalPersistenceTest {
+    // Logger for this class
+    private static final Logger LOGGER = LoggerFactory.getLogger(PolicyLegacyOperationalPersistenceTest.class);
+
+    private Gson gson;
+
+    private PolicyModelsProvider databaseProvider;
+
+    // @formatter:off
+    private String[] policyInputResourceNames = {
+        "policies/vCPE.policy.operational.input.json",
+        "policies/vDNS.policy.operational.input.json",
+        "policies/vFirewall.policy.operational.input.json"
+    };
+
+    private String[] policyOutputResourceNames = {
+        "policies/vCPE.policy.operational.output.json",
+        "policies/vDNS.policy.operational.output.json",
+        "policies/vFirewall.policy.operational.output.json"
+    };
+    // @formatter:on
+
+    /**
+     * Initialize provider.
+     *
+     * @throws PfModelException on exceptions in the tests
+     */
+    @Before
+    public void setupParameters() throws PfModelException {
+        PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
+        parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
+        parameters.setDatabaseUser("policy");
+        parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
+        parameters.setPersistenceUnit("ToscaConceptTest");
+
+        databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
+        databaseProvider.init();
+    }
+
+    /**
+     * Set up GSON.
+     */
+    @Before
+    public void setupGson() {
+        gson = new Gson();
+    }
+
+    @After
+    public void teardown() throws Exception {
+        databaseProvider.close();
+    }
+
+    @Test
+    public void testPolicyPersistence() {
+        try {
+            for (int i = 0; i < policyInputResourceNames.length; i++) {
+                String policyInputString = ResourceUtils.getResourceAsString(policyInputResourceNames[i]);
+                String policyOutputString = ResourceUtils.getResourceAsString(policyOutputResourceNames[i]);
+                testJsonStringPolicyPersistence(policyInputString, policyOutputString);
+            }
+        } catch (Exception exc) {
+            LOGGER.warn("error processing policies", exc);
+            fail("test should not throw an exception");
+        }
+    }
+
+    /**
+     * Check persistence of a policy.
+     *
+     * @param policyInputString the policy as a string
+     * @param policyOutputString the expected output string
+     * @throws Exception any exception thrown
+     */
+    public void testJsonStringPolicyPersistence(@NonNull final String policyInputString,
+            final String policyOutputString) throws Exception {
+        LegacyOperationalPolicy lop = gson.fromJson(policyInputString, LegacyOperationalPolicy.class);
+
+        assertNotNull(lop);
+
+        LegacyOperationalPolicy createdLop = databaseProvider.createOperationalPolicy(lop);
+        assertEquals(createdLop, lop);
+
+        LegacyOperationalPolicy gotLop = databaseProvider.getOperationalPolicy(lop.getPolicyId());
+        assertEquals(gotLop, lop);
+
+        String actualRetrievedJson = gson.toJson(gotLop);
+
+        // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters
+        assertEquals(
+                policyOutputString.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_", "'"),
+                actualRetrievedJson.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_",
+                        "'"));
+    }
+}
diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java
new file mode 100644 (file)
index 0000000..a4b1dcd
--- /dev/null
@@ -0,0 +1,159 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.models.provider.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import java.util.Base64;
+
+import lombok.NonNull;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.models.base.PfConceptKey;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.base.PfValidationResult;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
+import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
+import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.yaml.snakeyaml.Yaml;
+
+/**
+ * Test persistence of monitoring policies to and from the database.
+ *
+ * @author Liam Fallon (liam.fallon@est.tech)
+ */
+public class PolicyToscaPersistenceTest {
+    // Logger for this class
+    private static final Logger LOGGER = LoggerFactory.getLogger(PolicyToscaPersistenceTest.class);
+
+    private Gson gson;
+
+    private PolicyModelsProvider databaseProvider;
+
+    // @formatter:off
+    private String[] policyResourceNames = {
+        "policies/vCPE.policy.monitoring.input.tosca.json",
+        "policies/vCPE.policy.monitoring.input.tosca.yaml",
+        "policies/vCPE.policy.operational.input.tosca.yaml",
+        "policies/vDNS.policy.guard.frequency.input.tosca.json",
+        "policies/vDNS.policy.guard.frequency.input.tosca.yaml",
+        "policies/vDNS.policy.monitoring.input.tosca.json",
+        "policies/vDNS.policy.monitoring.input.tosca.yaml",
+        "policies/vDNS.policy.operational.input.tosca.yaml",
+        "policies/vFirewall.policy.monitoring.input.tosca.json",
+        "policies/vFirewall.policy.monitoring.input.tosca.yaml",
+        "policies/vFirewall.policy.operational.input.tosca.json",
+        "policies/vFirewall.policy.operational.input.tosca.yaml"
+    };
+    // @formatter:on
+
+    /**
+     * Initialize provider.
+     *
+     * @throws PfModelException on exceptions in the tests
+     */
+    @Before
+    public void setupParameters() throws PfModelException {
+        PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
+        parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
+        parameters.setDatabaseUser("policy");
+        parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
+        parameters.setPersistenceUnit("ToscaConceptTest");
+
+        databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
+        databaseProvider.init();
+    }
+
+    /**
+     * Set up GSON.
+     */
+    @Before
+    public void setupGson() {
+        gson = new ToscaServiceTemplateMessageBodyHandler().getGson();
+    }
+
+    @After
+    public void teardown() throws Exception {
+        databaseProvider.close();
+    }
+
+    @Test
+    public void testPolicyPersistence() {
+        try {
+            for (String policyResourceName : policyResourceNames) {
+                String policyString = ResourceUtils.getResourceAsString(policyResourceName);
+
+                if (policyResourceName.endsWith("yaml")) {
+                    testYamlStringPolicyPersistence(policyString);
+                } else {
+                    testJsonStringPolicyPersistence(policyString);
+                }
+            }
+        } catch (Exception exc) {
+            LOGGER.warn("error processing policies", exc);
+            fail("test should not throw an exception");
+        }
+    }
+
+    private void testYamlStringPolicyPersistence(final String policyString) throws Exception {
+        Object yamlObject = new Yaml().load(policyString);
+        String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject);
+
+        testJsonStringPolicyPersistence(yamlAsJsonString);
+    }
+
+    /**
+     * Check persistence of a policy.
+     *
+     * @param policyString the policy as a string
+     * @throws Exception any exception thrown
+     */
+    public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception {
+        ToscaServiceTemplate serviceTemplate = gson.fromJson(policyString, ToscaServiceTemplate.class);
+
+        assertNotNull(serviceTemplate);
+        LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString());
+        assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid());
+
+        databaseProvider.createPolicies(serviceTemplate);
+
+        for (PfConceptKey policyKey : serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().keySet()) {
+            ToscaPolicy incomingPolicy = serviceTemplate.getTopologyTemplate().getPolicies().get(policyKey);
+            ToscaPolicy databasePolicy =
+                    databaseProvider.getPolicies(policyKey).getTopologyTemplate().getPolicies().get(policyKey);
+            assertEquals(incomingPolicy, databasePolicy);
+        }
+    }
+}
index 60a1e45..1db4d6e 100644 (file)
@@ -36,6 +36,7 @@ public class LegacyOperationalPolicy {
     @SerializedName("policy-id")
     private String policyId;
 
+    @SerializedName("policy-version")
     private String policyVersion;
 
     private String content;
index 2f87020..65f4775 100644 (file)
@@ -23,14 +23,19 @@ package org.onap.policy.models.tosca.legacy.mapping;
 import java.util.HashMap;
 import java.util.Map;
 
+import javax.ws.rs.core.Response;
+
 import org.onap.policy.models.base.PfConceptKey;
-import org.onap.policy.models.base.PfReferenceKey;
+import org.onap.policy.models.base.PfModelRuntimeException;
 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
 import org.onap.policy.models.tosca.simple.concepts.ToscaPolicies;
 import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy;
 import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
 import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate;
 import org.onap.policy.models.tosca.simple.mapping.ToscaServiceTemplateMapper;
+import org.onap.policy.models.tosca.utils.ToscaUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * This class maps a legacy operational policy to and from a TOSCA service template.
@@ -39,51 +44,72 @@ import org.onap.policy.models.tosca.simple.mapping.ToscaServiceTemplateMapper;
  */
 public class LegacyOperationalPolicyMapper
         implements ToscaServiceTemplateMapper<LegacyOperationalPolicy, LegacyOperationalPolicy> {
+    private static final Logger LOGGER = LoggerFactory.getLogger(LegacyOperationalPolicyMapper.class);
 
-    // TODO: Do this correctly with an atomic integer
-    private static int nextVersion = 1;
+    private static final PfConceptKey LEGACY_OPERATIONAL_TYPE =
+            new PfConceptKey("onap.policies.controlloop.Operational", "1.0.0");
 
     @Override
-    public ToscaServiceTemplate toToscaServiceTemplate(LegacyOperationalPolicy legacyOperationalPolicy) {
-        PfConceptKey policyKey =
-                new PfConceptKey(legacyOperationalPolicy.getPolicyId(), getNextVersion());
+    public ToscaServiceTemplate toToscaServiceTemplate(final LegacyOperationalPolicy legacyOperationalPolicy) {
+        String incomingVersion = legacyOperationalPolicy.getPolicyVersion();
+        if (incomingVersion == null) {
+            incomingVersion = "1";
+        }
+
+        PfConceptKey policyKey = new PfConceptKey(legacyOperationalPolicy.getPolicyId(), incomingVersion + ".0.0");
 
-        ToscaPolicy toscaPolicy = new ToscaPolicy(policyKey);
+        final ToscaPolicy toscaPolicy = new ToscaPolicy(policyKey);
 
-        // TODO: Find out how to parse the PolicyType from the content
-        // TODO: Check if this is the correct way to set the policy type version
-        toscaPolicy.setType(new PfConceptKey("SomeDerivedPolicyType", "1.0.1"));
+        toscaPolicy.setType(LEGACY_OPERATIONAL_TYPE);
 
-        Map<String, String> propertyMap = new HashMap<>();
+        final Map<String, String> propertyMap = new HashMap<>();
         toscaPolicy.setProperties(propertyMap);
         toscaPolicy.getProperties().put("Content", legacyOperationalPolicy.getContent());
 
-        PfConceptKey serviceTemplateKey = new PfConceptKey("ServiceTemplate", "1.0.2");
-        ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(serviceTemplateKey);
+        final ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
         serviceTemplate.setToscaDefinitionsVersion("tosca_simple_yaml_1_0");
 
-        PfReferenceKey topologyTemplateKey = new PfReferenceKey(serviceTemplateKey, "TopolocyTemplate");
-        serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate(topologyTemplateKey));
+        serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate());
 
-        PfConceptKey policiesKey = new PfConceptKey("Policies", "1.0.3");
-        serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies(policiesKey));
+        serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies());
         serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(policyKey, toscaPolicy);
 
         return serviceTemplate;
     }
 
     @Override
-    public LegacyOperationalPolicy fromToscaServiceTemplate(ToscaServiceTemplate serviceTemplate) {
-        // TODO Auto-generated method stub
-        return null;
-    }
+    public LegacyOperationalPolicy fromToscaServiceTemplate(final ToscaServiceTemplate serviceTemplate) {
+        ToscaUtils.assertPoliciesExist(serviceTemplate);
+
+        if (serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().size() > 1) {
+            String errorMessage = "more than one policy found in service template";
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        // Get the policy
+        final ToscaPolicy toscaPolicy =
+                serviceTemplate.getTopologyTemplate().getPolicies().getAll(null).iterator().next();
+
+        final LegacyOperationalPolicy legacyOperationalPolicy = new LegacyOperationalPolicy();
+        legacyOperationalPolicy.setPolicyId(toscaPolicy.getKey().getName());
+        legacyOperationalPolicy.setPolicyVersion(Integer.toString(toscaPolicy.getKey().getMajorVersion()));
+
+        if (toscaPolicy.getProperties() == null) {
+            String errorMessage = "no properties defined on TOSCA policy";
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        final String content = toscaPolicy.getProperties().get("Content");
+        if (toscaPolicy.getProperties() == null) {
+            String errorMessage = "property \"Content\" not defined on TOSCA policy";
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        legacyOperationalPolicy.setContent(content);
 
-    /**
-     * Get the next policy version.
-     *
-     * @return the next version
-     */
-    private static String getNextVersion() {
-        return "1.0." + nextVersion++;
+        return legacyOperationalPolicy;
     }
 }
diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java
new file mode 100644 (file)
index 0000000..42343e1
--- /dev/null
@@ -0,0 +1,268 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.models.tosca.legacy.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.ws.rs.core.Response;
+
+import lombok.NonNull;
+
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.base.PfModelRuntimeException;
+import org.onap.policy.models.dao.PfDao;
+import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy;
+import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
+import org.onap.policy.models.tosca.legacy.mapping.LegacyOperationalPolicyMapper;
+import org.onap.policy.models.tosca.simple.concepts.ToscaPolicies;
+import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
+import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate;
+import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class provides the provision of information on TOSCA concepts in the database to callers in legacy formats.
+ *
+ * @author Liam Fallon (liam.fallon@est.tech)
+ */
+public class LegacyProvider {
+    private static final Logger LOGGER = LoggerFactory.getLogger(LegacyProvider.class);
+
+    private static final String FIRST_POLICY_VERSION = "1";
+
+    // Recurring constants
+    private static final String NO_POLICY_FOUND_FOR_POLICY_ID = "no policy found for policy ID: ";
+
+    /**
+     * Get legacy operational policy.
+     *
+     * @param dao the DAO to use to access the database
+     * @param policyId ID of the policy.
+     * @return the policies found
+     * @throws PfModelException on errors getting policies
+     */
+    public LegacyOperationalPolicy getOperationalPolicy(@NonNull final PfDao dao, @NonNull final String policyId)
+            throws PfModelException {
+
+        ToscaPolicy newestPolicy = getLatestPolicy(dao, policyId);
+
+        if (newestPolicy == null) {
+            String errorMessage = NO_POLICY_FOUND_FOR_POLICY_ID + policyId;
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        // Create the structure of the TOSCA service template to contain the policy type
+        ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
+        serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate());
+        serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies());
+        serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(newestPolicy.getKey(), newestPolicy);
+
+        return new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(serviceTemplate);
+    }
+
+    /**
+     * Create legacy operational policy.
+     *
+     * @param dao the DAO to use to access the database
+     * @param legacyOperationalPolicy the definition of the policy to be created.
+     * @return the created policy
+     * @throws PfModelException on errors creating policies
+     */
+    public LegacyOperationalPolicy createOperationalPolicy(@NonNull final PfDao dao,
+            @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
+
+        // We need to find the latest policy and update the major version, if there is no policy with this ID, then
+        // we set it to the first version
+        ToscaPolicy newestPolicy = getLatestPolicy(dao, legacyOperationalPolicy.getPolicyId());
+
+        if (newestPolicy == null) {
+            legacyOperationalPolicy.setPolicyVersion(FIRST_POLICY_VERSION);
+        } else {
+            legacyOperationalPolicy.setPolicyVersion(Integer.toString(newestPolicy.getKey().getMajorVersion() + 1));
+        }
+
+        ToscaServiceTemplate incomingServiceTemplate =
+                new LegacyOperationalPolicyMapper().toToscaServiceTemplate(legacyOperationalPolicy);
+        ToscaServiceTemplate outgoingingServiceTemplate =
+                new SimpleToscaProvider().createPolicies(dao, incomingServiceTemplate);
+
+        return new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(outgoingingServiceTemplate);
+    }
+
+    /**
+     * Update legacy operational policy.
+     *
+     * @param dao the DAO to use to access the database
+     * @param legacyOperationalPolicy the definition of the policy to be updated
+     * @return the updated policy
+     * @throws PfModelException on errors updating policies
+     */
+    public LegacyOperationalPolicy updateOperationalPolicy(@NonNull final PfDao dao,
+            @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
+
+        // We need to find the latest policy and use the major version, if there is no policy with this ID, then
+        // we have an error
+        ToscaPolicy newestPolicy = getLatestPolicy(dao, legacyOperationalPolicy.getPolicyId());
+
+        if (newestPolicy == null) {
+            String errorMessage = NO_POLICY_FOUND_FOR_POLICY_ID + legacyOperationalPolicy.getPolicyId();
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        } else {
+            legacyOperationalPolicy.setPolicyVersion(Integer.toString(newestPolicy.getKey().getMajorVersion()));
+        }
+
+        ToscaServiceTemplate incomingServiceTemplate =
+                new LegacyOperationalPolicyMapper().toToscaServiceTemplate(legacyOperationalPolicy);
+        ToscaServiceTemplate outgoingingServiceTemplate =
+                new SimpleToscaProvider().createPolicies(dao, incomingServiceTemplate);
+
+        return new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(outgoingingServiceTemplate);
+    }
+
+    /**
+     * Delete legacy operational policy.
+     *
+     * @param dao the DAO to use to access the database
+     * @param policyId ID of the policy.
+     * @return the deleted policy
+     * @throws PfModelException on errors deleting policies
+     */
+    public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final PfDao dao, @NonNull final String policyId)
+            throws PfModelException {
+
+        // Get all the policies in the database and check the policy ID against the policies returned
+        List<ToscaPolicy> policyList = dao.getAll(ToscaPolicy.class);
+
+        // Find the latest policy that matches the ID
+        List<ToscaPolicy> policyDeleteList = new ArrayList<>();
+
+        for (ToscaPolicy policy : policyList) {
+            if (policyId.equals(policy.getKey().getName())) {
+                policyDeleteList.add(policy);
+            }
+        }
+
+        if (policyDeleteList.isEmpty()) {
+            String errorMessage = NO_POLICY_FOUND_FOR_POLICY_ID + policyId;
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        // Create the structure of the TOSCA service template to contain the policy type
+        ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
+        serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate());
+        serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies());
+
+        for (ToscaPolicy deletePolicy : policyDeleteList) {
+            dao.delete(deletePolicy);
+            serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(deletePolicy.getKey(),
+                    deletePolicy);
+        }
+
+        return new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(serviceTemplate);
+    }
+
+    /**
+     * Get legacy guard policy.
+     *
+     * @param dao the DAO to use to access the database
+     * @param policyId ID of the policy.
+     * @return the policies found
+     * @throws PfModelException on errors getting policies
+     */
+    public LegacyGuardPolicy getGuardPolicy(@NonNull final PfDao dao, @NonNull final String policyId)
+            throws PfModelException {
+        return null;
+    }
+
+    /**
+     * Create legacy guard policy.
+     *
+     * @param dao the DAO to use to access the database
+     * @param legacyGuardPolicy the definition of the policy to be created.
+     * @return the created policy
+     * @throws PfModelException on errors creating policies
+     */
+    public LegacyGuardPolicy createGuardPolicy(@NonNull final PfDao dao,
+            @NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException {
+        return null;
+    }
+
+    /**
+     * Update legacy guard policy.
+     *
+     * @param dao the DAO to use to access the database
+     * @param legacyGuardPolicy the definition of the policy to be updated
+     * @return the updated policy
+     * @throws PfModelException on errors updating policies
+     */
+    public LegacyGuardPolicy updateGuardPolicy(@NonNull final PfDao dao,
+            @NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException {
+        return null;
+    }
+
+
+    /**
+     * Delete legacy guard policy.
+     *
+     * @param dao the DAO to use to access the database
+     * @param policyId ID of the policy.
+     * @return the deleted policy
+     * @throws PfModelException on errors deleting policies
+     */
+    public LegacyGuardPolicy deleteGuardPolicy(@NonNull final PfDao dao, @NonNull final String policyId)
+            throws PfModelException {
+        return null;
+    }
+
+    /**
+     * Get the latest policy for a policy ID.
+     *
+     * @param dao The DAO to read from
+     * @param policyId the ID of the policy
+     * @return the policy
+     */
+    private ToscaPolicy getLatestPolicy(final PfDao dao, final String policyId) {
+        // Get all the policies in the database and check the policy ID against the policies returned
+        List<ToscaPolicy> policyList = dao.getAll(ToscaPolicy.class);
+
+        // Find the latest policy that matches the ID
+        ToscaPolicy newestPolicy = null;
+
+        for (ToscaPolicy policy : policyList) {
+            if (!policyId.equals(policy.getKey().getName())) {
+                continue;
+            }
+
+            // We found a matching policy
+            if (newestPolicy == null || policy.getKey().isNewerThan(newestPolicy.getKey())) {
+                // First policy found
+                newestPolicy = policy;
+            }
+        }
+        return newestPolicy;
+    }
+}
diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyToscaProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyToscaProvider.java
deleted file mode 100644 (file)
index da9d929..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- *  Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.models.tosca.legacy.provider;
-
-import lombok.NonNull;
-
-import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.dao.PfDao;
-import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy;
-import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
-
-/**
- * This class provides the provision of information on TOSCA concepts in the database to callers in legacy formats.
- *
- * @author Liam Fallon (liam.fallon@est.tech)
- */
-public class LegacyToscaProvider {
-    /**
-     * Get legacy operational policy.
-     *
-     * @param dao the DAO to use to access the database
-     * @param policyId ID of the policy.
-     * @return the policies found
-     * @throws PfModelException on errors getting policies
-     */
-    public LegacyOperationalPolicy getOperationalPolicy(@NonNull final PfDao dao, @NonNull final String policyId)
-            throws PfModelException {
-        return null;
-    }
-
-    /**
-     * Create legacy operational policy.
-     *
-     * @param dao the DAO to use to access the database
-     * @param legacyOperationalPolicy the definition of the policy to be created.
-     * @return the created policy
-     * @throws PfModelException on errors creating policies
-     */
-    public LegacyOperationalPolicy createOperationalPolicy(@NonNull final PfDao dao,
-            @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
-        return null;
-    }
-
-    /**
-     * Update legacy operational policy.
-     *
-     * @param dao the DAO to use to access the database
-     * @param legacyOperationalPolicy the definition of the policy to be updated
-     * @return the updated policy
-     * @throws PfModelException on errors updating policies
-     */
-    public LegacyOperationalPolicy updateOperationalPolicy(@NonNull final PfDao dao,
-            @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
-        return null;
-    }
-
-    /**
-     * Delete legacy operational policy.
-     *
-     * @param dao the DAO to use to access the database
-     * @param policyId ID of the policy.
-     * @return the deleted policy
-     * @throws PfModelException on errors deleting policies
-     */
-    public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final PfDao dao, @NonNull final String policyId)
-            throws PfModelException {
-        return null;
-    }
-
-    /**
-     * Get legacy guard policy.
-     *
-     * @param dao the DAO to use to access the database
-     * @param policyId ID of the policy.
-     * @return the policies found
-     * @throws PfModelException on errors getting policies
-     */
-    public LegacyGuardPolicy getGuardPolicy(@NonNull final PfDao dao, @NonNull final String policyId)
-            throws PfModelException {
-        return null;
-    }
-
-    /**
-     * Create legacy guard policy.
-     *
-     * @param dao the DAO to use to access the database
-     * @param legacyGuardPolicy the definition of the policy to be created.
-     * @return the created policy
-     * @throws PfModelException on errors creating policies
-     */
-    public LegacyGuardPolicy createGuardPolicy(@NonNull final PfDao dao,
-            @NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException {
-        return null;
-    }
-
-    /**
-     * Update legacy guard policy.
-     *
-     * @param dao the DAO to use to access the database
-     * @param legacyGuardPolicy the definition of the policy to be updated
-     * @return the updated policy
-     * @throws PfModelException on errors updating policies
-     */
-    public LegacyGuardPolicy updateGuardPolicy(@NonNull final PfDao dao,
-            @NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException {
-        return null;
-    }
-
-    /**
-     * Delete legacy guard policy.
-     *
-     * @param dao the DAO to use to access the database
-     * @param policyId ID of the policy.
-     * @return the deleted policy
-     * @throws PfModelException on errors deleting policies
-     */
-    public LegacyGuardPolicy deleteGuardPolicy(@NonNull final PfDao dao, @NonNull final String policyId)
-            throws PfModelException {
-        return null;
-    }
-}
index ee9c2ea..f318bb6 100644 (file)
@@ -47,7 +47,7 @@ import org.onap.policy.models.base.PfConceptKey;
 public class ToscaPolicies extends PfConceptContainer<ToscaPolicy> {
     private static final long serialVersionUID = -7526648702327776101L;
 
-    public static final String DEFAULT_NAME = "ToscaPoliciessSimple";
+    public static final String DEFAULT_NAME = "ToscaPoliciesSimple";
     public static final String DEFAULT_VERSION = "1.0.0";
 
     /**
index 2240ef0..c7984c5 100644 (file)
@@ -34,6 +34,7 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyType;
 import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyTypes;
 import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
 import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate;
+import org.onap.policy.models.tosca.utils.ToscaUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -84,7 +85,7 @@ public class SimpleToscaProvider {
     public ToscaServiceTemplate createPolicyTypes(@NonNull final PfDao dao,
             @NonNull final ToscaServiceTemplate serviceTemplate) throws PfModelException {
 
-        assertPolicyTypesExist(serviceTemplate);
+        ToscaUtils.assertPolicyTypesExist(serviceTemplate);
 
         for (ToscaPolicyType policyType : serviceTemplate.getPolicyTypes().getAll(null)) {
             dao.create(policyType);
@@ -114,7 +115,7 @@ public class SimpleToscaProvider {
     public ToscaServiceTemplate updatePolicyTypes(@NonNull final PfDao dao,
             @NonNull final ToscaServiceTemplate serviceTemplate) throws PfModelException {
 
-        assertPolicyTypesExist(serviceTemplate);
+        ToscaUtils.assertPolicyTypesExist(serviceTemplate);
 
         for (ToscaPolicyType policyType : serviceTemplate.getPolicyTypes().getAll(null)) {
             dao.update(policyType);
@@ -192,7 +193,7 @@ public class SimpleToscaProvider {
     public ToscaServiceTemplate createPolicies(@NonNull final PfDao dao,
             @NonNull final ToscaServiceTemplate serviceTemplate) throws PfModelException {
 
-        assertPoliciesExist(serviceTemplate);
+        ToscaUtils.assertPoliciesExist(serviceTemplate);
 
         for (ToscaPolicy policy : serviceTemplate.getTopologyTemplate().getPolicies().getAll(null)) {
             dao.create(policy);
@@ -222,7 +223,7 @@ public class SimpleToscaProvider {
     public ToscaServiceTemplate updatePolicies(@NonNull final PfDao dao,
             @NonNull final ToscaServiceTemplate serviceTemplate) throws PfModelException {
 
-        assertPoliciesExist(serviceTemplate);
+        ToscaUtils.assertPoliciesExist(serviceTemplate);
 
         for (ToscaPolicy policy : serviceTemplate.getTopologyTemplate().getPolicies().getAll(null)) {
             dao.update(policy);
@@ -258,44 +259,4 @@ public class SimpleToscaProvider {
 
         return serviceTemplate;
     }
-
-    /**
-     * Check if policy types have been specified is initialized.
-     */
-    private void assertPolicyTypesExist(final ToscaServiceTemplate serviceTemplate) {
-        if (serviceTemplate.getPolicyTypes() == null) {
-            String errorMessage = "no policy types specified on service template";
-            LOGGER.warn(errorMessage);
-            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
-        }
-
-        if (serviceTemplate.getPolicyTypes().getConceptMap().isEmpty()) {
-            String errorMessage = "list of policy types specified on service template is empty";
-            LOGGER.warn(errorMessage);
-            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
-        }
-    }
-
-    /**
-     * Check if policy types have been specified is initialized.
-     */
-    private void assertPoliciesExist(final ToscaServiceTemplate serviceTemplate) {
-        if (serviceTemplate.getTopologyTemplate() == null) {
-            String errorMessage = "topology template not specified on service template";
-            LOGGER.warn(errorMessage);
-            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
-        }
-
-        if (serviceTemplate.getTopologyTemplate().getPolicies() == null) {
-            String errorMessage = "no policies specified on topology template of service template";
-            LOGGER.warn(errorMessage);
-            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
-        }
-
-        if (serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().isEmpty()) {
-            String errorMessage = "list of policies specified on topology template of service template is empty";
-            LOGGER.warn(errorMessage);
-            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
-        }
-    }
 }
diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java
new file mode 100644 (file)
index 0000000..a02bfa4
--- /dev/null
@@ -0,0 +1,85 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.models.tosca.utils;
+
+import javax.ws.rs.core.Response;
+
+import org.onap.policy.models.base.PfModelRuntimeException;
+import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utility class for TOSCA concepts.
+ *
+ * @author Liam Fallon (liam.fallon@est.tech)
+ */
+public final class ToscaUtils {
+    private static final Logger LOGGER = LoggerFactory.getLogger(ToscaUtils.class);
+
+    /**
+     * Private constructor to prevent subclassing.
+     */
+    private ToscaUtils() {
+    }
+
+    /**
+     * Check if policy types have been specified is initialized.
+     */
+    public static void assertPolicyTypesExist(final ToscaServiceTemplate serviceTemplate) {
+        if (serviceTemplate.getPolicyTypes() == null) {
+            String errorMessage = "no policy types specified on service template";
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        if (serviceTemplate.getPolicyTypes().getConceptMap().isEmpty()) {
+            String errorMessage = "list of policy types specified on service template is empty";
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+    }
+
+    /**
+     * Check if policy types have been specified is initialized.
+     */
+    public static void assertPoliciesExist(final ToscaServiceTemplate serviceTemplate) {
+        if (serviceTemplate.getTopologyTemplate() == null) {
+            String errorMessage = "topology template not specified on service template";
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        if (serviceTemplate.getTopologyTemplate().getPolicies() == null) {
+            String errorMessage = "no policies specified on topology template of service template";
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        if (serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().isEmpty()) {
+            String errorMessage = "list of policies specified on topology template of service template is empty";
+            LOGGER.warn(errorMessage);
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+    }
+
+
+}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProviderTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProviderTest.java
new file mode 100644 (file)
index 0000000..271e019
--- /dev/null
@@ -0,0 +1,317 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.models.tosca.legacy.provider;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import com.google.gson.Gson;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.dao.DaoParameters;
+import org.onap.policy.models.dao.PfDao;
+import org.onap.policy.models.dao.PfDaoFactory;
+import org.onap.policy.models.dao.impl.DefaultPfDao;
+import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
+
+/**
+ * Test the {@link LegacyProvider} class.
+ *
+ * @author Liam Fallon (liam.fallon@est.tech)
+ */
+public class LegacyProviderTest {
+    private Connection connection;
+    private PfDao pfDao;
+    private Gson gson;
+
+
+    /**
+     * Set up the DAO towards the database.
+     *
+     * @throws Exception on database errors
+     */
+    @Before
+    public void setupDao() throws Exception {
+        // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database
+        // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance
+        connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY");
+
+        final DaoParameters daoParameters = new DaoParameters();
+        daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName());
+
+        // Use the persistence unit ToscaConceptTest to test towards the h2 database
+        // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance
+        daoParameters.setPersistenceUnit("ToscaConceptTest");
+
+        pfDao = new PfDaoFactory().createPfDao(daoParameters);
+        pfDao.init(daoParameters);
+    }
+
+    /**
+     * Set up GSON.
+     */
+    @Before
+    public void setupGson() {
+        gson = new Gson();
+    }
+
+    @After
+    public void teardown() throws Exception {
+        pfDao.close();
+        connection.close();
+    }
+
+    @Test
+    public void testPoliciesGet() throws PfModelException {
+        try {
+            new LegacyProvider().getOperationalPolicy(null, null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("dao is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().getOperationalPolicy(null, "");
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("dao is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().getOperationalPolicy(pfDao, null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("policyId is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().getOperationalPolicy(pfDao, "I Dont Exist");
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("no policy found for policy ID: I Dont Exist", exc.getMessage());
+        }
+
+        LegacyOperationalPolicy originalLop =
+                gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"),
+                        LegacyOperationalPolicy.class);
+
+        assertNotNull(originalLop);
+
+        LegacyOperationalPolicy createdLop = new LegacyProvider().createOperationalPolicy(pfDao, originalLop);
+
+        assertEquals(originalLop, createdLop);
+
+        LegacyOperationalPolicy gotLop = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId());
+
+        assertEquals(gotLop, originalLop);
+
+        String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json");
+        String actualJsonOutput = gson.toJson(gotLop);
+
+        assertEquals(actualJsonOutput.replaceAll("\\s+", ""), expectedJsonOutput.replaceAll("\\s+", ""));
+
+        LegacyOperationalPolicy createdLopV2 = new LegacyProvider().createOperationalPolicy(pfDao, originalLop);
+        LegacyOperationalPolicy gotLopV2 = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId());
+        assertEquals(gotLopV2, createdLopV2);
+    }
+
+    @Test
+    public void testPolicyCreate() throws PfModelException {
+        try {
+            new LegacyProvider().createOperationalPolicy(null, null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("dao is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().createOperationalPolicy(null, new LegacyOperationalPolicy());
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("dao is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().createOperationalPolicy(pfDao, null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("legacyOperationalPolicy is marked @NonNull but is null", exc.getMessage());
+        }
+
+        LegacyOperationalPolicy originalLop =
+                gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"),
+                        LegacyOperationalPolicy.class);
+
+        assertNotNull(originalLop);
+
+        LegacyOperationalPolicy createdLop = new LegacyProvider().createOperationalPolicy(pfDao, originalLop);
+
+        assertEquals(originalLop, createdLop);
+
+        LegacyOperationalPolicy gotLop = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId());
+
+        assertEquals(gotLop, originalLop);
+
+        String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json");
+        String actualJsonOutput = gson.toJson(gotLop);
+
+        assertEquals(actualJsonOutput.replaceAll("\\s+", ""), expectedJsonOutput.replaceAll("\\s+", ""));
+    }
+
+
+    @Test
+    public void testPolicyUpdate() throws PfModelException {
+        try {
+            new LegacyProvider().updateOperationalPolicy(null, null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("dao is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().updateOperationalPolicy(null, new LegacyOperationalPolicy());
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("dao is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().updateOperationalPolicy(pfDao, null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("legacyOperationalPolicy is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().updateOperationalPolicy(pfDao, new LegacyOperationalPolicy());
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("no policy found for policy ID: null", exc.getMessage());
+        }
+
+        LegacyOperationalPolicy originalLop =
+                gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"),
+                        LegacyOperationalPolicy.class);
+
+        assertNotNull(originalLop);
+
+        LegacyOperationalPolicy createdLop = new LegacyProvider().createOperationalPolicy(pfDao, originalLop);
+        assertEquals(originalLop, createdLop);
+
+        LegacyOperationalPolicy gotLop = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId());
+        assertEquals(gotLop, originalLop);
+
+        originalLop.setContent("Some New Content");
+        LegacyOperationalPolicy updatedLop = new LegacyProvider().updateOperationalPolicy(pfDao, originalLop);
+        assertEquals(originalLop, updatedLop);
+
+        LegacyOperationalPolicy gotUpdatedLop =
+                new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId());
+        assertEquals(gotUpdatedLop, originalLop);
+        assertEquals("Some New Content", gotUpdatedLop.getContent());
+    }
+
+
+    @Test
+    public void testPoliciesDelete() throws PfModelException {
+        try {
+            new LegacyProvider().deleteOperationalPolicy(null, null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("dao is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().deleteOperationalPolicy(null, "");
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("dao is marked @NonNull but is null", exc.getMessage());
+        }
+
+        try {
+            new LegacyProvider().deleteOperationalPolicy(pfDao, null);
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("policyId is marked @NonNull but is null", exc.getMessage());
+        }
+
+
+        try {
+            new LegacyProvider().deleteOperationalPolicy(pfDao, "I Dont Exist");
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("no policy found for policy ID: I Dont Exist", exc.getMessage());
+        }
+
+        LegacyOperationalPolicy originalLop =
+                gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"),
+                        LegacyOperationalPolicy.class);
+
+        assertNotNull(originalLop);
+
+        LegacyOperationalPolicy createdLop = new LegacyProvider().createOperationalPolicy(pfDao, originalLop);
+        assertEquals(originalLop, createdLop);
+
+        LegacyOperationalPolicy gotLop = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId());
+
+        assertEquals(gotLop, originalLop);
+
+        String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json");
+        String actualJsonOutput = gson.toJson(gotLop);
+
+        assertEquals(actualJsonOutput.replaceAll("\\s+", ""), expectedJsonOutput.replaceAll("\\s+", ""));
+
+        LegacyOperationalPolicy deletedLop =
+                new LegacyProvider().deleteOperationalPolicy(pfDao, originalLop.getPolicyId());
+        assertEquals(deletedLop, originalLop);
+
+        try {
+            new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId());
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("no policy found for policy ID: operational.restart", exc.getMessage());
+        }
+
+        LegacyOperationalPolicy otherLop = new LegacyOperationalPolicy();
+        otherLop.setPolicyId("another-policy");
+        otherLop.setPolicyVersion("1");
+        otherLop.setContent("content");
+
+        LegacyOperationalPolicy createdOtherLop = new LegacyProvider().createOperationalPolicy(pfDao, otherLop);
+        assertEquals(otherLop, createdOtherLop);
+
+        try {
+            new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId());
+            fail("test should throw an exception here");
+        } catch (Exception exc) {
+            assertEquals("no policy found for policy ID: operational.restart", exc.getMessage());
+        }
+
+    }
+}
index 3c9deb7..5d1fa42 100644 (file)
@@ -68,7 +68,7 @@ public class LegacyOperationalPolicySerializationTest {
         LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString());
         assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid());
 
-        assertEquals("operational.restart:1.0.1",
+        assertEquals("operational.restart:1.0.0",
                 serviceTemplate.getTopologyTemplate().getPolicies().get("operational.restart").getId());
     }
 }