Merge "Add and Modify JUnits for Code Coverage"
authorJorge Hernandez <jorge.hernandez-herrero@att.com>
Sat, 30 Nov 2019 17:58:01 +0000 (17:58 +0000)
committerGerrit Code Review <gerrit@onap.org>
Sat, 30 Nov 2019 17:58:01 +0000 (17:58 +0000)
ONAP-REST/src/main/java/org/onap/policy/rest/util/MsModelUtils.java
ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java
ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java
ONAP-REST/src/test/resources/policies/MicroServicePolicy.json [new file with mode: 0644]
ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java
ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java
ONAP-XACML/src/test/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactoryTest.java [new file with mode: 0644]
ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineFactoryTest.java
ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineTest.java

index 5b596be..b185725 100644 (file)
@@ -202,7 +202,6 @@ public class MsModelUtils {
             processXmiEpackage(file);
         }
         return classMap;
-
     }
 
     /**
index 6bab919..adb8995 100644 (file)
@@ -47,6 +47,8 @@ import javax.json.JsonObject;
 import javax.json.JsonReader;
 import javax.json.JsonValue;
 
+import lombok.Getter;
+
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 
@@ -113,6 +115,7 @@ public class PolicyValidation {
     private static Map<String, String> jsonRequestMap = new HashMap<>();
     private static List<String> modelRequiredFieldsList = new ArrayList<>();
 
+    @Getter
     private static CommonClassDao commonClassDao;
 
     private Set<String> allReqTrueKeys = new HashSet<>();
@@ -230,7 +233,7 @@ public class PolicyValidation {
             // Decision Policy Attributes Validation
             if (!"API".equals(policyData.getApiflag()) && policyData.getSettings() != null
                             && !policyData.getSettings().isEmpty()) {
-                for (Object attribute : policyData.getAttributes()) {
+                for (Object attribute : policyData.getSettings()) {
                     if (attribute instanceof LinkedHashMap<?, ?>) {
                         String value = null;
                         if (((LinkedHashMap<?, ?>) attribute).get("key") == null) {
index 47b0f49..3efb825 100644 (file)
 
 package org.onap.policy.rest.util;
 
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
 
+import java.io.IOException;
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.UUID;
 
 import org.junit.After;
@@ -33,6 +40,7 @@ import org.junit.Before;
 import org.junit.Test;
 import org.onap.policy.api.PolicyConfigType;
 import org.onap.policy.api.PolicyParameters;
+import org.onap.policy.common.utils.resources.TextFileUtils;
 import org.onap.policy.rest.adapter.PolicyRestAdapter;
 
 public class PolicyValidationTest {
@@ -54,19 +62,7 @@ public class PolicyValidationTest {
         policyParameters.setPolicyDescription("This is a sample Micro Service policy Create example");
         policyParameters.setOnapName("DCAE");
         policyParameters.setPriority("1");
-        String msJsonString = "{\"service\":\"TOSCA_namingJenny\",\"location\":\"Test  DictMSLoc\","
-                        + "\"uuid\":\"testDict  DCAEUIID\",\"policyName\":\"testModelValidation\","
-                        + "\"description\":\"test\",\"configName\":\"testDict  MSConfName\","
-                        + "\"templateVersion\":\"1607\",\"version\":\"gw12181031\",\"priority\":\"5\","
-                        + "\"policyScope\":\"resource=ResourcetypeVenktest1,service=ServiceName1707,type=Name1707,"
-                        + "closedLoopControlName=Retest_retest1\",\"riskType\":\"Test\",\"riskLevel\":\"3\","
-                        + "\"guard\":\"True\",\"content\":{\"police-instance-name\":\"testing\","
-                        + "\"naming-models\":[{\"naming-properties\":[{\"property-value\":\"test\","
-                        + "\"source-endpoint\":\"test\",\"property-name\":\"testPropertyname\","
-                        + "\"increment-sequence\":{\"scope\":\"VNF\",\"start-value\":\"1\",\"length\":\"3\","
-                        + "\"increment\":\"2\"},\"source-system\":\"TOSCA\"}],\"naming-type\":\"testNamingType\","
-                        + "\"naming-recipe\":\"testNamingRecipe\"}]}}";
-        ;
+        String msJsonString = TextFileUtils.getTextFileAsString("src/test/resources/policies/MicroServicePolicy.json");
         policyParameters.setConfigBody(msJsonString);
         policyParameters.setRequestID(UUID.randomUUID());
         SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
@@ -80,10 +76,32 @@ public class PolicyValidationTest {
         PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
         PolicyRestAdapter policyData = wrapper.populateRequestParameters(policyParameters);
         PolicyValidation validation = new PolicyValidation();
-        StringBuilder responseString = validation.validatePolicy(policyData);
+        String responseString = validation.validatePolicy(policyData).toString();
 
-        assertNotSame("success", responseString.toString());
+        assertNotSame("success", responseString);
 
+        new PolicyValidation(null);
+        assertNull(PolicyValidation.getCommonClassDao());
+
+        policyData.setConfigPolicyType("ClosedLoop_Fault");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).doesNotContain("success");
+
+        policyData.setConfigPolicyType("ClosedLoop_PM");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).doesNotContain("success");
+
+        policyData.setConfigPolicyType("Enforcer Config");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).doesNotContain("success");
+
+        policyData.setConfigPolicyType("Optimization");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).doesNotContain("success");
+
+        policyData.setConfigPolicyType("Strange");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).doesNotContain("success");
     }
 
     @Test
@@ -93,4 +111,234 @@ public class PolicyValidationTest {
         assertEquals("success", result);
     }
 
+    @Test
+    public void testPolicyHeadingValidation() throws IOException {
+        PolicyValidation validation = new PolicyValidation();
+        PolicyRestAdapter policyData = new PolicyRestAdapter();
+
+        String responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("PolicyName Should not be empty");
+
+        policyData.setPolicyName("%%%~~~%%%");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}");
+
+        policyData.setPolicyName("ALegalPolicyName");
+        policyData.setPolicyDescription("@CreatedBy:");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString)
+                        .contains("The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:");
+        policyData.setPolicyDescription("@CreatedBy:");
+
+        policyData.setPolicyDescription("A Legal Description");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString)
+                        .doesNotContain("The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:");
+    }
+
+    @Test
+    public void testPolicyAttributeValidation() throws IOException {
+        PolicyValidation validation = new PolicyValidation();
+        PolicyRestAdapter policyData = new PolicyRestAdapter();
+        policyData.setPolicyName("ALegalPolicyName");
+        policyData.setPolicyDescription("A Valid Description");
+
+        String responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        policyData.setApiflag("API");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        policyData.setApiflag("NOTAPI");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        List<Object> attributes = new ArrayList<>();
+        policyData.setAttributes(attributes);
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        attributes.add(new String("hello"));
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+        attributes.clear();
+
+        Map<String, String> mapAttribute = new LinkedHashMap<>();
+        attributes.add(mapAttribute);
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Component Attributes</b>:<i> has one missing Component Attribute value");
+
+        mapAttribute.put("key", "value");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>",
+                        responseString);
+
+        mapAttribute.put("key", "");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("<b>Attributes or Component Attributes</b>:<i>null : value has spaces or invalid characters</i>"
+                        + "<br><b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>",
+                        responseString);
+        mapAttribute.clear();
+
+        responseString = validation.validatePolicy(policyData).toString();
+        mapAttribute.put("hello", "aaa");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("<b>Component Attributes</b>:<i> has one missing Component Attribute key</i><br>"
+                        + "<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>",
+                        responseString);
+
+        policyData.setPolicyType("Config");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("<b>RiskType</b>: Risk Type Should not be Empty</i><br>"
+                        + "<b>RiskLevel</b>: Risk Level Should not be Empty</i><br>"
+                        + "<b>Guard</b>: Guard Value Should not be Empty</i><br>", responseString);
+
+        policyData.setConfigPolicyType("Base");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("has one missing Attribute key");
+
+        policyData.setConfigPolicyType("BRMS_Param");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("has one missing Attribute key");
+
+        policyData.setConfigPolicyType("BRMS_Raw");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("has one missing Attribute key");
+
+        policyData.setConfigPolicyType(null);
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Risk Level Should not be Empty");
+
+        mapAttribute.clear();
+        mapAttribute.put("value", "thevalue");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Risk Level Should not be Empty");
+
+        mapAttribute.put("value", "$$$%%%%");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Risk Level Should not be Empty");
+
+        policyData.setConfigPolicyType("Base");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("value has spaces or invalid characters");
+
+        policyData.setConfigPolicyType("BRMS_Param");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("value has spaces or invalid characters");
+
+        policyData.setConfigPolicyType("BRMS_Raw");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("value has spaces or invalid characters");
+
+        policyData.setConfigPolicyType(null);
+        policyData.setPolicyType(null);
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("value has spaces or invalid characters");
+    }
+
+    @Test
+    public void testPolicySettingsValidation() throws IOException {
+        PolicyValidation validation = new PolicyValidation();
+        PolicyRestAdapter policyData = new PolicyRestAdapter();
+        policyData.setPolicyName("ALegalPolicyName");
+        policyData.setPolicyDescription("A Valid Description");
+
+        String responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        policyData.setApiflag("API");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        policyData.setApiflag("NOTAPI");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        List<Object> settings = new ArrayList<>();
+        policyData.setSettings(settings);
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        settings.add("hello");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+        settings.clear();
+
+        Map<String, String> mapSetting = new LinkedHashMap<>();
+        settings.add(mapSetting);
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Settings Attributes</b>:<i> has one missing Attribute key");
+
+        mapSetting.put("key", "value");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>", responseString);
+
+        mapSetting.put("key", "");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>", responseString);
+        mapSetting.clear();
+
+        mapSetting.put("value", "thevalue");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("has one missing Attribute key");
+
+        mapSetting.put("value", "$$$%%%");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("value has spaces or invalid characters");
+    }
+
+    @Test
+    public void testPolicyRuleAlgorithmsValidation() throws IOException {
+        PolicyValidation validation = new PolicyValidation();
+        PolicyRestAdapter policyData = new PolicyRestAdapter();
+        policyData.setPolicyName("ALegalPolicyName");
+        policyData.setPolicyDescription("A Valid Description");
+
+        String responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        policyData.setApiflag("API");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        policyData.setApiflag("NOTAPI");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        List<Object> ruleAlgorithmschoices = new ArrayList<>();
+        policyData.setRuleAlgorithmschoices(ruleAlgorithmschoices);
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        ruleAlgorithmschoices.add("hello");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+        ruleAlgorithmschoices.clear();
+
+        Map<String, String> mapChoice = new LinkedHashMap<>();
+        ruleAlgorithmschoices.add(mapChoice);
+        assertNull(validation.validatePolicy(policyData));
+
+        mapChoice.clear();
+        mapChoice.put("id", "TheID");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Field 1 value is not selected");
+
+        mapChoice.put("dynamicRuleAlgorithmField1", "Field1");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Field 2 value is not selected");
+
+        mapChoice.put("dynamicRuleAlgorithmCombo", "Combo");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Field 3 value is empty");
+
+        mapChoice.put("dynamicRuleAlgorithmField2", "Field2");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertEquals("success", responseString);
+
+        mapChoice.put("dynamicRuleAlgorithmField2", "%%%$$$");
+        responseString = validation.validatePolicy(policyData).toString();
+        assertThat(responseString).contains("Field 3 value has special characters");
+    }
 }
diff --git a/ONAP-REST/src/test/resources/policies/MicroServicePolicy.json b/ONAP-REST/src/test/resources/policies/MicroServicePolicy.json
new file mode 100644 (file)
index 0000000..b9c06e5
--- /dev/null
@@ -0,0 +1,38 @@
+{
+    "service": "TOSCA_namingJenny",
+    "location": "Test  DictMSLoc",
+    "uuid": "testDict  DCAEUIID",
+    "policyName": "testModelValidation",
+    "description": "test",
+    "configName": "testDict  MSConfName",
+    "templateVersion": "1607",
+    "version": "gw12181031",
+    "priority": "5",
+    "policyScope": "resource=ResourcetypeVenktest1,service=ServiceName1707,type=Name1707,closedLoopControlName=Retest_retest1",
+    "riskType": "Test",
+    "riskLevel": "3",
+    "guard": "True",
+    "content": {
+        "police-instance-name": "testing",
+        "naming-models": [
+            {
+                "naming-properties": [
+                    {
+                        "property-value": "test",
+                        "source-endpoint": "test",
+                        "property-name": "testPropertyname",
+                        "increment-sequence": {
+                            "scope": "VNF",
+                            "start-value": "1",
+                            "length": "3",
+                            "increment": "2"
+                        },
+                        "source-system": "TOSCA"
+                    }
+                ],
+                "naming-type": "testNamingType",
+                "naming-recipe": "testNamingRecipe"
+            }
+        ]
+    }
+}
index 464313e..1fb2518 100644 (file)
@@ -66,9 +66,13 @@ import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
  *
  */
 public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
-    public static final String pipPropertyFile = "pip.properties";
+    public static final String PIP_PROPERTY_FILE = "pip.properties";
 
-    private static final String addGroup = "addGroup ";
+    private static final String STR_ADDGROUP = "addGroup ";
+    private static final String STR_CLASS = "StdEngine";
+    private static final String STR_APPEND_NAME = ".name";
+    private static final String STR_APPEND_DESCRIPTION = ".description";
+    private static final String STR_APPEND_PDPS = ".pdps";
 
     private static Log logger = LogFactory.getLog(StdEngine.class);
 
@@ -143,13 +147,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         if (this.repository == null) {
             throw new PAPException("No repository specified.");
         }
-        if (Files.notExists(this.repository)) {
+        if (! this.repository.toFile().exists()) {
             Files.createDirectory(repository);
         }
-        if (!Files.isDirectory(this.repository)) {
+        if (! this.repository.toFile().isDirectory()) {
             throw new PAPException("Repository is NOT a directory: " + this.repository.toAbsolutePath());
         }
-        if (!Files.isWritable(this.repository)) {
+        if (! this.repository.toFile().canWrite()) {
             throw new PAPException("Repository is NOT writable: " + this.repository.toAbsolutePath());
         }
         //
@@ -177,7 +181,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
             //
             this.groups = this.readProperties(this.repository, properties);
         } catch (IOException e) {
-            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to load properties file");
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to load properties file");
             this.groups = new HashSet<>();
         }
         //
@@ -210,7 +214,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
             //
             // Does it exist?
             //
-            if (Files.notExists(defaultPath)) {
+            if (! defaultPath.toFile().exists()) {
                 //
                 // Create its directory
                 //
@@ -227,7 +231,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                     try (OutputStream os = Files.newOutputStream(policyPath)) {
                         props.store(os, "");
                     } catch (IOException e) {
-                        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine",
+                        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
                                 "Failed to write default policy properties");
                     }
                 }
@@ -239,7 +243,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                     try (OutputStream os = Files.newOutputStream(pipPath)) {
                         props.store(os, "");
                     } catch (IOException e) {
-                        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine",
+                        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
                                 "Failed to write default pip properties");
                     }
                 }
@@ -247,7 +251,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
             //
             // Create the default group
             //
-            StdPDPGroup newDefault = new StdPDPGroup(defaultId, true, "default",
+            StdPDPGroup newDefault = new StdPDPGroup(defaultId, true, PROP_PAP_GROUPS_DEFAULT_NAME,
                     "The default group where new PDP's are put.", defaultPath);
             //
             // Add it to our list
@@ -266,7 +270,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                     properties.store(os, "");
                 }
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine",
+                PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, STR_CLASS,
                         "Failed to save properties with new default group information.");
             }
             //
@@ -275,7 +279,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
             wasDefaultGroupJustAdded = true;
             return newDefault;
         } catch (IOException e) {
-            PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create default group");
+            PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, STR_CLASS, "Failed to create default group");
             throw new PAPException("Failed to create default group");
         }
     }
@@ -333,7 +337,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         // If it exists already
         //
         if (Files.exists(groupPath)) {
-            logger.warn(addGroup + id + " directory exists");
+            logger.warn(STR_ADDGROUP + id + " directory exists");
         } else {
             try {
                 //
@@ -341,7 +345,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                 //
                 Files.createDirectory(groupPath);
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create " + groupPath);
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to create " + groupPath);
                 throw new PAPException("Failed to create " + id);
             }
         }
@@ -350,8 +354,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         //
 
         Path policyProperties = Paths.get(groupPath.toString(), "xacml.policy.properties");
-        if (Files.exists(policyProperties)) {
-            logger.warn(addGroup + id + " file exists");
+        if (policyProperties.toFile().exists()) {
+            logger.warn(STR_ADDGROUP + id + " file exists");
         } else {
             Properties props = new Properties();
             props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
@@ -362,7 +366,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                     props.store(os, "");
                 }
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create policyProperties");
+                PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, STR_CLASS, "Failed to create policyProperties");
                 throw new PAPException("Failed to create " + id);
             }
         }
@@ -371,8 +375,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         //
         Path pipProperties = Paths.get(groupPath.toString(), "xacml.pip.properties");
         Properties props = new Properties();
-        if (Files.exists(pipProperties)) {
-            logger.warn(addGroup + id + " file exists.");
+        if (pipProperties.toFile().exists()) {
+            logger.warn(STR_ADDGROUP + id + " file exists.");
         } else {
             try {
                 props = setPipProperties(props);
@@ -381,7 +385,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                     props.store(os, "");
                 }
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create pipProperties");
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to create pipProperties");
                 throw new PAPException("Failed to create " + id);
             }
 
@@ -628,8 +632,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         List<String> ids = new ArrayList<>();
         for (PDPGroup group : this.groups) {
             ids.add(group.getId());
-            properties.setProperty(group.getId() + ".name", group.getName() == null ? "" : group.getName());
-            properties.setProperty(group.getId() + ".description",
+            properties.setProperty(group.getId() + STR_APPEND_NAME, group.getName() == null ? "" : group.getName());
+            properties.setProperty(group.getId() + STR_APPEND_DESCRIPTION,
                     group.getDescription() == null ? "" : group.getDescription());
             //
             // Iterate its PDPs
@@ -637,8 +641,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
             List<String> pdps = new ArrayList<>();
             for (PDP pdp : group.getPdps()) {
                 pdps.add(pdp.getId());
-                properties.setProperty(pdp.getId() + ".name", pdp.getName() == null ? "" : pdp.getName());
-                properties.setProperty(pdp.getId() + ".description",
+                properties.setProperty(pdp.getId() + STR_APPEND_NAME, pdp.getName() == null ? "" : pdp.getName());
+                properties.setProperty(pdp.getId() + STR_APPEND_DESCRIPTION,
                         pdp.getDescription() == null ? "" : pdp.getDescription());
                 if (pdp instanceof OnapPDP) {
                     properties.setProperty(pdp.getId() + ".jmxport",
@@ -654,7 +658,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
             if (logger.isDebugEnabled()) {
                 logger.debug("Group " + group.getId() + " PDPS: " + pdpList);
             }
-            properties.setProperty(group.getId() + ".pdps", pdpList);
+            properties.setProperty(group.getId() + STR_APPEND_PDPS, pdpList);
         }
         if (ids.isEmpty()) {
             throw new PAPException("Inconsistency - we have NO groups. We should have at least one.");
@@ -685,20 +689,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         }
     }
 
-    /**
-     * removeGroupProperties.
-     *
-     * @param id String
-     * @param properties Properties
-     */
-    public static void removeGroupProperties(String id, Properties properties) {
-        for (Object key : properties.keySet()) {
-            if (key.toString().startsWith(id + ".")) {
-                properties.remove(key);
-            }
-        }
-    }
-
     /**
      * setGroupProperties.
      *
@@ -734,8 +724,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         //
         // Set its properties
         //
-        properties.setProperty(group.getId() + ".name", group.getName());
-        properties.setProperty(group.getId() + ".description", group.getDescription());
+        properties.setProperty(group.getId() + STR_APPEND_NAME, group.getName());
+        properties.setProperty(group.getId() + STR_APPEND_DESCRIPTION, group.getDescription());
         //
         // Set its PDP list
         //
@@ -750,9 +740,9 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                 }
                 pdpList = Joiner.on(',').skipNulls().join(ids);
             }
-            properties.setProperty(group.getId() + ".pdps", pdpList);
+            properties.setProperty(group.getId() + STR_APPEND_PDPS, pdpList);
         } else {
-            properties.setProperty(group.getId() + ".pdps", "");
+            properties.setProperty(group.getId() + STR_APPEND_PDPS, "");
         }
     }
 
@@ -800,7 +790,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
             //
             this.saveConfiguration();
         } catch (IOException | PAPException e) {
-            PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Failed to save configuration");
+            PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, STR_CLASS, "Failed to save configuration");
         }
     }
 
@@ -810,8 +800,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions");
         props.setProperty("AAF.classname", "org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine");
         // read from PIP properties file.
-        Path file = Paths.get(pipPropertyFile);
-        if (!Files.notExists(file)) {
+        Path file = Paths.get(PIP_PROPERTY_FILE);
+        if (file.toFile().exists()) {
             InputStream in;
             Properties prop = new Properties();
             try {
@@ -961,7 +951,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                     throw new PAPException("Unable to rename directory; reason unknown");
                 }
             } catch (Exception e) {
-                PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Unable to rename directory");
+                PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, STR_CLASS, "Unable to rename directory");
                 throw new PAPException(
                         "Unable to move directory from '" + oldPath + "' to '" + newPath + "': " + e.getMessage(), e);
             }
@@ -1036,7 +1026,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
         //
         // If it exists already
         //
-        if (!Files.exists(groupPath)) {
+        if (! groupPath.toFile().exists()) {
             logger.warn("removeGroup " + id + " directory does not exist" + groupPath.toString());
         } else {
             try {
@@ -1054,7 +1044,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
                 //
                 Files.delete(groupPath);
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to delete " + groupPath);
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to delete " + groupPath);
                 throw new PAPException("Failed to delete " + id);
             }
         }
index d406a54..daa3764 100644 (file)
@@ -59,13 +59,21 @@ import org.onap.policy.xacml.api.pap.OnapPDP;
 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
 
-@EqualsAndHashCode(callSuper=false)
+@EqualsAndHashCode(callSuper = false)
 @ToString
 public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         implements OnapPDPGroup, StdItemSetChangeListener, Comparable<Object>, Serializable {
 
     private static final long serialVersionUID = 1L;
-    private static final String groupNotExist = "Group directory does NOT exist";
+    private static final String MSG_GROUPNOTEXIST = "Group directory does NOT exist";
+    private static final String MSG_LOADFAILURE = "Failed to load group policy properties file: ";
+    private static final String STR_APPEND_NAME = ".name";
+    private static final String STR_APPEND_DESCRIPTION = ".description";
+    private static final String STR_APPEND_PDPS = ".pdps";
+    private static final String STR_CLASS = "StdPDPGroup";
+    private static final String PROPS_POLICY = "xacml.policy.properties";
+    private static final String PROPS_PIP = "xacml.pip.properties";
+
     private static Log logger = LogFactory.getLog(StdPDPGroup.class);
 
     private String id;
@@ -174,11 +182,11 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         //
         for (Object key : properties.keySet()) {
             if (key.toString().startsWith(this.id + ".")) {
-                if (key.toString().endsWith(".name")) {
+                if (key.toString().endsWith(STR_APPEND_NAME)) {
                     this.name = properties.getProperty(key.toString());
-                } else if (key.toString().endsWith(".description")) {
+                } else if (key.toString().endsWith(STR_APPEND_DESCRIPTION)) {
                     this.description = properties.getProperty(key.toString());
-                } else if (key.toString().endsWith(".pdps")) {
+                } else if (key.toString().endsWith(STR_APPEND_PDPS)) {
                     String pdpList = properties.getProperty(key.toString());
                     if (pdpList != null && pdpList.length() > 0) {
                         for (String pdpId : Splitter.on(',').omitEmptyStrings().trimResults().split(pdpList)) {
@@ -197,25 +205,25 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         //
         // Validate our directory
         //
-        if (Files.notExists(directory)) {
+        if (! directory.toFile().exists()) {
             logger.warn("Group directory does NOT exist: " + directory.toString());
             try {
                 Files.createDirectory(directory);
-                this.status.addLoadWarning(groupNotExist);
+                this.status.addLoadWarning(MSG_GROUPNOTEXIST);
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", groupNotExist);
-                this.status.addLoadError(groupNotExist);
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, MSG_GROUPNOTEXIST);
+                this.status.addLoadError(MSG_GROUPNOTEXIST);
                 this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS);
             }
         }
         //
         // Parse policies
         //
-        this.loadPolicies(Paths.get(directory.toString(), "xacml.policy.properties"));
+        this.loadPolicies(Paths.get(directory.toString(), PROPS_POLICY));
         //
         // Parse pip config
         //
-        this.loadPIPConfig(Paths.get(directory.toString(), "xacml.pip.properties"));
+        this.loadPIPConfig(Paths.get(directory.toString(), PROPS_PIP));
     }
 
     /**
@@ -253,10 +261,10 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
                 //
                 this.readPolicyProperties(directory, policyProperties);
             } catch (IOException e) {
-                logger.warn("Failed to load group policy properties file: " + file, e);
+                logger.warn(MSG_LOADFAILURE + file, e);
                 this.status.addLoadError("Not policy properties defined");
                 this.status.setStatus(Status.LOAD_ERRORS);
-                throw new PAPException("Failed to load group policy properties file: " + file);
+                throw new PAPException(MSG_LOADFAILURE + file);
             }
         }
     }
@@ -313,7 +321,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
                 logger.warn("Failed to open group PIP Config properties file: " + file, e);
                 this.status.addLoadError("Not PIP config properties defined");
                 this.status.setStatus(Status.LOAD_ERRORS);
-                throw new PAPException("Failed to load group policy properties file: " + file);
+                throw new PAPException(MSG_LOADFAILURE + file);
 
             }
         }
@@ -500,7 +508,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         for (PDPPolicy policy : this.policies) {
             // for all policies need to tell PDP the "name", which is the base name for the file id
             if (policy.getName() != null) {
-                properties.setProperty(policy.getId() + ".name", policy.getName());
+                properties.setProperty(policy.getId() + STR_APPEND_NAME, policy.getName());
             }
             // put the policy on the correct list
             if (policy.isRoot()) {
@@ -550,7 +558,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
                 try {
                     Files.delete(tempFile);
                 } catch (Exception ee) {
-                    PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup",
+                    PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, STR_CLASS,
                             "Policy was invalid, could NOT delete it.");
                 }
                 throw new PAPException("Policy is invalid");
@@ -568,7 +576,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
             //
             return tempRootPolicy;
         } catch (IOException e) {
-            PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", "Failed to publishPolicy");
+            PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, STR_CLASS, "Failed to publishPolicy");
         }
         return null;
     }
@@ -586,69 +594,18 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
      * @throws PAPException PAPException
      */
     public void copyPolicyToFile(String id, InputStream policy) throws PAPException {
-        try {
-            //
-            // Copy the policy over
-            //
-            long num;
-            Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id);
-
-            Path policyFile;
-            if (Files.exists(policyFilePath)) {
-                policyFile = policyFilePath;
-            } else {
-                policyFile = Files.createFile(policyFilePath);
-            }
-
-            try (OutputStream os = Files.newOutputStream(policyFile)) {
-                num = ByteStreams.copy(policy, os);
-            }
-
-            logger.info("Copied " + num + " bytes for policy " + name);
-
-            for (PDPPolicy p : policies) {
-                if (p.getId().equals(id)) {
-                    // we just re-copied/refreshed/updated the policy file for a policy that already exists in this
-                    // group
-                    logger.info("Policy '" + id + "' already exists in group '" + getId() + "'");
-                    return;
-                }
-            }
-
-            // policy is new to this group
-            StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri());
-            if (!tempRootPolicy.isValid()) {
-                try {
-                    Files.delete(policyFile);
-                } catch (Exception ee) {
-                    PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup",
-                            "Policy was invalid, could NOT delete it.");
-                }
-                throw new PAPException("Policy is invalid");
-            }
-            //
-            // Add it in
-            //
-            this.policies.add(tempRootPolicy);
-            //
-            // We are changed
-            //
-            this.firePDPGroupChanged(this);
-        } catch (IOException e) {
-            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile");
-            throw new PAPException("Failed to copy policy to file: " + e);
-        }
+        copyPolicyToFile(id, this.name, policy);
     }
 
     /**
      * Policy Engine API Copy one policy file into the Group's directory but do not change the configuration.
      *
      * @param id String
-     * @param name String
+     * @param fileName String
      * @param policy InputStream
      * @throws PAPException PAPException
      */
-    public void copyPolicyToFile(String id, String name, InputStream policy) throws PAPException {
+    public void copyPolicyToFile(String id, String fileName, InputStream policy) throws PAPException {
         try {
             //
             // Copy the policy over
@@ -657,7 +614,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
             Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id);
 
             Path policyFile;
-            if (Files.exists(policyFilePath)) {
+            if (policyFilePath.toFile().exists()) {
                 policyFile = policyFilePath;
             } else {
                 policyFile = Files.createFile(policyFilePath);
@@ -667,7 +624,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
                 num = ByteStreams.copy(policy, os);
             }
 
-            logger.info("Copied " + num + " bytes for policy " + name);
+            logger.info("Copied " + num + " bytes for policy " + fileName);
             for (PDPPolicy p : policies) {
                 if (p.getId().equals(id)) {
                     // we just re-copied/refreshed/updated the policy file for a policy that already exists in this
@@ -678,12 +635,12 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
             }
 
             // policy is new to this group
-            StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri());
+            StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, fileName, policyFile.toUri());
             if (!tempRootPolicy.isValid()) {
                 try {
                     Files.delete(policyFile);
                 } catch (Exception ee) {
-                    PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup",
+                    PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, STR_CLASS,
                             "Policy was invalid, could NOT delete it.");
                 }
                 throw new PAPException("Policy is invalid");
@@ -698,7 +655,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
             this.firePDPGroupChanged(this);
 
         } catch (IOException e) {
-            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile");
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to copyPolicyToFile");
             throw new PAPException("Failed to copy policy to file: " + e);
         }
     }
@@ -730,7 +687,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
             this.firePDPGroupChanged(this);
             return true;
         } catch (Exception e) {
-            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy");
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to delete policy");
         }
         return false;
     }
@@ -762,7 +719,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
             this.firePDPGroupChanged(this);
             return true;
         } catch (Exception e) {
-            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy " + policy);
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to delete policy " + policy);
         }
         return false;
     }
@@ -817,14 +774,14 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         // Validate our directory
         //
         boolean fire = false;
-        if (Files.notExists(directory)) {
+        if (! directory.toFile().exists()) {
             logger.warn("Group directory does NOT exist: " + directory.toString());
             try {
                 Files.createDirectory(directory);
                 fire = true;
                 this.status.addLoadWarning("Created missing group directory");
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup",
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
                         "Failed to create missing Group directory.");
                 this.status.addLoadError("Failed to create missing Group directory.");
                 this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS);
@@ -833,14 +790,14 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         //
         // Validate our PIP config file
         //
-        Path pipPropertiesFile = Paths.get(directory.toString(), "xacml.pip.properties");
-        if (Files.notExists(pipPropertiesFile)) {
+        Path pipPropertiesFile = Paths.get(directory.toString(), PROPS_PIP);
+        if (! pipPropertiesFile.toFile().exists()) {
             try {
                 Files.createFile(pipPropertiesFile);
                 fire = true;
                 this.status.addLoadWarning("Created missing PIP properties file");
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup",
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
                         "Failed to create missing PIP properties file");
                 this.status.addLoadError("Failed to create missing PIP properties file");
                 this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS);
@@ -849,14 +806,14 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         //
         // Valid our policy properties file
         //
-        Path policyPropertiesFile = Paths.get(directory.toString(), "xacml.policy.properties");
-        if (Files.notExists(policyPropertiesFile)) {
+        Path policyPropertiesFile = Paths.get(directory.toString(), PROPS_POLICY);
+        if (! policyPropertiesFile.toFile().exists()) {
             try {
                 Files.createFile(policyPropertiesFile);
                 fire = true;
                 this.status.addLoadWarning("Created missing Policy properties file");
             } catch (IOException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup",
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
                         "Failed to create missing Policy properties file");
                 this.status.addLoadError("Failed to create missing Policy properties file");
                 this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS);
@@ -910,7 +867,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
                 try {
                     policy = new StdPDPPolicy(id, isRoot, policyPath.toUri(), properties);
                 } catch (IOException e) {
-                    PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup",
+                    PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
                             "Failed to create policy object");
                     policy = null;
                 }
@@ -957,7 +914,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         try {
             saveGroupConfiguration();
         } catch (PAPException | IOException e) {
-            PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup",
+            PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, STR_CLASS,
                     "Unable to save group configuration change");
             // don't notify other things of change if we cannot save it???
             return;
@@ -1019,13 +976,13 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
 
         // save info about each policy
         for (PDPPolicy policy : this.policies) {
-            policyProperties.put(policy.getId() + ".name", policy.getName());
+            policyProperties.put(policy.getId() + STR_APPEND_NAME, policy.getName());
         }
 
         //
         // Now we can save the file
         //
-        Path file = Paths.get(this.directory.toString(), "xacml.policy.properties");
+        Path file = Paths.get(this.directory.toString(), PROPS_POLICY);
         try (OutputStream os = Files.newOutputStream(file)) {
             policyProperties.store(os, "");
         } catch (Exception e) {
@@ -1039,11 +996,11 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         //
         // Now we can save the file
         //
-        file = Paths.get(this.directory.toString(), "xacml.pip.properties");
+        file = Paths.get(this.directory.toString(), PROPS_PIP);
         try (OutputStream os = Files.newOutputStream(file)) {
             pipProperties.store(os, "");
         } catch (Exception e) {
-            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Group PIP Config save failed");
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Group PIP Config save failed");
             throw new PAPException("Failed to save pip properties file '" + file + "'");
         }
     }
@@ -1077,8 +1034,8 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier
         props.setProperty("AAF.classname", "org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine");
         props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF");
         // read from PIP properties file.
-        Path file = Paths.get(StdEngine.pipPropertyFile);
-        if (!Files.notExists(file)) {
+        Path file = Paths.get(StdEngine.PIP_PROPERTY_FILE);
+        if (file.toFile().exists()) {
             InputStream in;
             Properties prop = new Properties();
             try {
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactoryTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactoryTest.java
new file mode 100644 (file)
index 0000000..94b28b2
--- /dev/null
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-XACML
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.xacml.api.pap;
+
+import static org.junit.Assert.assertNotNull;
+
+import com.att.research.xacml.util.FactoryException;
+import org.junit.Test;
+import org.onap.policy.xacml.std.pap.StdEngineFactory;
+
+public class ONAPPapEngineFactoryTest {
+
+    @Test
+    public void test() throws FactoryException {
+        ONAPPapEngineFactory factory =
+                ONAPPapEngineFactory.newInstance(StdEngineFactory.class.getName());
+        assertNotNull(factory);
+    }
+
+}
index 43d019d..b7fb32a 100644 (file)
 
 package org.onap.policy.xacml.test.std.pap;
 
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.fail;
 
 import com.att.research.xacml.api.pap.PAPException;
 import com.att.research.xacml.std.pap.StdEngine;
 import com.att.research.xacml.util.FactoryException;
-
+import java.io.File;
 import java.io.IOException;
 import java.util.Properties;
-
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
 import org.onap.policy.xacml.std.pap.StdEngineFactory;
 
 public class StdEngineFactoryTest {
+
+    private static String systemProperty;
+
+    @Rule
+    public TemporaryFolder folder = new TemporaryFolder();
+
+    @BeforeClass
+    public static void saveSystemProperty() {
+        systemProperty = System.getProperty(StdEngine.PROP_PAP_REPO);
+    }
+
+    /**
+     * restoreSystemProperty.
+     */
+    @AfterClass
+    public static void restoreSystemProperty() {
+        if (systemProperty != null) {
+            System.setProperty(StdEngine.PROP_PAP_REPO, systemProperty);
+        } else {
+            System.clearProperty(StdEngine.PROP_PAP_REPO);
+        }
+    }
+
     @Test
     public void testStdEngineFactory() throws FactoryException, PAPException, IOException {
         StdEngineFactory stdFactory = new StdEngineFactory();
         System.setProperty("xacml.pap.pdps", "src/test/resources/pdps");
-        assertTrue(stdFactory.newEngine() != null);
+        assertNotNull(stdFactory.newEngine());
         Properties properties = new Properties();
         properties.setProperty("xacml.pap.pdps", "src/test/resources/pdps");
-        assertTrue(stdFactory.newEngine(properties) != null);
+        assertNotNull(stdFactory.newEngine(properties));
 
         StdEngineFactory stdFactoryNew = new StdEngineFactory();
         System.setProperty("xacml.pap.pdps", "src/test/resources/pdpstest");
-        assertTrue(stdFactoryNew.newEngine() != null);
+        PAPPolicyEngine engine = stdFactoryNew.newEngine();
+        assertNotNull(engine);
+
+        assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
+            engine.newGroup(null, null)
+        );
+
+        assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
+            engine.movePDP(null, null)
+        );
+
     }
 
     @Test
@@ -57,25 +96,54 @@ public class StdEngineFactoryTest {
         String tmpdir = System.getProperty("java.io.tmpdir");
         props.setProperty(StdEngine.PROP_PAP_REPO, tmpdir);
 
-        // Set the system property temporarily
-        String systemKey = StdEngine.PROP_PAP_REPO;
-        String oldProperty = System.getProperty(systemKey);
-        System.setProperty(systemKey, tmpdir);
-
         // Test factory failure cases
         try {
             StdEngineFactory factory = new StdEngineFactory();
-            factory.newEngine();
-            factory.newEngine(props);
+            assertNotNull(factory.newEngine());
+            assertNotNull(factory.newEngine(props));
         } catch (Exception ex) {
             fail("Not expecting any exceptions: " + ex);
         }
 
-        // Restore the original system property
-        if (oldProperty != null) {
-            System.setProperty(systemKey, oldProperty);
-        } else {
-            System.clearProperty(systemKey);
-        }
+    }
+
+    @Test
+    public void testException() throws FactoryException, PAPException, IOException {
+        Properties props = new Properties();
+        File myFolder = folder.newFolder("idontexist");
+        props.setProperty(StdEngine.PROP_PAP_REPO, myFolder.getAbsolutePath());
+        StdEngineFactory factory = new StdEngineFactory();
+        assertNotNull(factory.newEngine(props));
+
+        //
+        //
+        //
+        myFolder.setReadOnly();
+        assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+            factory.newEngine(props)
+        );
+
+        //
+        //
+        //
+        File myFile = folder.newFile("iamafile");
+        props.setProperty(StdEngine.PROP_PAP_REPO, myFile.getAbsolutePath());
+        assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+            factory.newEngine(props)
+        );
+
+        //
+        //
+        //
+        props.setProperty(StdEngine.PROP_PAP_REPO, myFolder.getAbsolutePath() + "/badparent/dontexist");
+        assertNull(factory.newEngine(props));
+
+        //
+        //
+        //
+        System.setProperty(StdEngine.PROP_PAP_REPO, myFolder.getAbsolutePath() + "/badparent/dontexist");
+
+        assertNull(factory.newEngine());
+
     }
 }
index b57a6be..79c2893 100644 (file)
@@ -62,6 +62,11 @@ public class StdEngineTest {
     @Rule
     public ExpectedException expectedException = ExpectedException.none();
 
+    /**
+     * setUpClass.
+     *
+     * @throws IOException IOException
+     */
     @BeforeClass
     public static void setUpClass() throws IOException {
         new File("target/test/resources/pdps").mkdirs();
@@ -73,6 +78,12 @@ public class StdEngineTest {
                 StandardCopyOption.REPLACE_EXISTING);
     }
 
+    /**
+     * setUp.
+     *
+     * @throws PAPException PAPException
+     * @throws IOException IOException
+     */
     @Before
     public void setUp() throws PAPException, IOException {