Adding Junits for policy engine 39/12639/2
authorTej, Tarun <tt3868@att.com>
Fri, 15 Sep 2017 04:52:13 +0000 (00:52 -0400)
committerTej, Tarun <tt3868@att.com>
Fri, 15 Sep 2017 05:37:52 +0000 (01:37 -0400)
Adding Junits to Policy Engine Utils project, removed duplicates, fixed
few defects along the way and fixes to projects.

Issue-Id: POLICY-52
Change-Id: Ia0598300f9bd60f5372b9ef7d8984657478a1611
Signed-off-by: Tej, Tarun <tt3868@att.com>
34 files changed:
ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java
ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java
ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java
ONAP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml
ONAP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml
ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ConfigPolicyService.java
ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java
ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java
ONAP-PDP-REST/xacml.pdp.properties
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
PolicyEngineAPI/pom.xml
PolicyEngineUtils/pom.xml
PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java
PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java
PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java
PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java
PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java
PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java
PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java
PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java [new file with mode: 0644]
PolicyEngineUtils/src/test/java/org/onap/policy/test/PolicyUtilsTest.java [deleted file]
PolicyEngineUtils/src/test/java/org/onap/policy/test/testBackUpMonitor.java [deleted file]
PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java [new file with mode: 0644]
PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java [new file with mode: 0644]
PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/Handler.java [moved from PolicyEngineUtils/src/test/java/org/onap/policy/test/Handler.java with 97% similarity]
PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java [new file with mode: 0644]
PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java [new file with mode: 0644]
PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java [new file with mode: 0644]
PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/testBackUpMonitor.java [new file with mode: 0644]
PolicyEngineUtils/src/test/resources/META-INF/drop.ddl [new file with mode: 0644]
PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml [new file with mode: 0644]
packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties

index 63a62d2..adcffe9 100644 (file)
@@ -24,18 +24,23 @@ import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
-import java.io.StringReader;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.Scanner;
 
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
+import org.apache.commons.io.FilenameUtils;
+import org.onap.policy.common.logging.eelf.MessageCodes;
+import org.onap.policy.common.logging.eelf.PolicyLogger;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.utils.PolicyUtils;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
 
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
@@ -51,21 +56,6 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
 
-import org.apache.commons.io.FilenameUtils;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.XMLReader;
-
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.std.IdentifierImpl;
-
 public class ConfigPolicy extends Policy {
 
        /**
@@ -148,15 +138,15 @@ public class ConfigPolicy extends Policy {
                String id = policyAdapter.getConfigType();
                if (id != null) {
                        if (id.equals(JSON_CONFIG)) {
-                               if (!isJSONValid(configBodyData)) {
+                               if (!PolicyUtils.isJSONValid(configBodyData)) {
                                        isValidForm = false;
                                }
                        } else if (id.equals(XML_CONFIG)) {
-                               if (!isXMLValid(configBodyData)) {
+                               if (!PolicyUtils.isXMLValid(configBodyData)) {
                                        isValidForm = false;
                                }
                        } else if (id.equals(PROPERTIES_CONFIG)) {
-                               if (!isPropValid(configBodyData)||configBodyData.equals("")) {
+                               if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
                                        isValidForm = false;
                                } 
                        } else if (id.equals(OTHER_CONFIG)) {
@@ -169,68 +159,6 @@ public class ConfigPolicy extends Policy {
 
        }
 
-       // Validation for XML.
-       private boolean isXMLValid(String data) {
-
-               SAXParserFactory factory = SAXParserFactory.newInstance();
-               factory.setValidating(false);
-               factory.setNamespaceAware(true);
-               try {
-                       SAXParser parser = factory.newSAXParser();
-                       XMLReader reader = parser.getXMLReader();
-                       reader.setErrorHandler(new XMLErrorHandler());
-                       reader.parse(new InputSource(new StringReader(data)));
-               } catch (ParserConfigurationException | SAXException | IOException e) {
-                       LOGGER.debug(e);
-                       return false;
-               }
-               return true;
-
-       }
-
-       // Validation for Properties file.
-       public boolean isPropValid(String prop) {
-
-               Scanner scanner = new Scanner(prop);
-               while (scanner.hasNextLine()) {
-                       String line = scanner.nextLine();
-                       line.replaceAll("\\s+", "");
-                       if (line.startsWith("#")) {
-                               continue;
-                       } else {
-                               if (line.contains("=")) {
-                                       String[] parts = line.split("=");
-                                       if (parts.length < 2) {
-                                               scanner.close();
-                                               return false;
-                                       }
-                               } else {
-                                       scanner.close();
-                                       return false;
-                               }
-                       }
-               }
-               scanner.close();
-               return true;
-
-       }
-
-       public class XMLErrorHandler implements ErrorHandler {
-
-               public void warning(SAXParseException e) throws SAXException {
-                       System.out.println(e.getMessage());
-               }
-
-               public void error(SAXParseException e) throws SAXException {
-                       System.out.println(e.getMessage());
-               }
-
-               public void fatalError(SAXParseException e) throws SAXException {
-                       System.out.println(e.getMessage());
-               }
-
-       }
-
        @Override
        public Map<String, String> savePolicies() throws PAPException {
                
index 6e43c96..eae3e79 100644 (file)
@@ -285,7 +285,7 @@ public class DecisionPolicy extends Policy {
             activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
                        String blackListString = yamlParams.get("blackList");
                        List<String> blackList = null;
-                       if(blackListString!=null){
+            if(blackListString!=null && !blackListString.trim().isEmpty()){
                                if (blackListString.contains(",")){
                                        blackList = Arrays.asList(blackListString.split(","));                                                          
                                }
@@ -303,6 +303,9 @@ public class DecisionPolicy extends Policy {
                                templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
                                xacmlTemplatePath = templateFile.toPath();
                 cons.setActive_time_range(activeTimeRange);
+                if(blackList==null || blackList.isEmpty()){
+                    throw new BuilderException("blackList is required");
+                }
                 cons.setBlacklist(blackList);
                                break;
                        default:
index 169e6e1..20c76f3 100644 (file)
 
 package org.onap.policy.pap.xacml.rest.components;
 
-import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URI;
 import java.net.URISyntaxException;
-import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.HashMap;
 import java.util.Map;
 
-import javax.json.Json;
-import javax.json.JsonReader;
-
 import org.apache.commons.io.FilenameUtils;
-import org.json.JSONObject;
 import org.onap.policy.common.logging.eelf.MessageCodes;
 import org.onap.policy.common.logging.eelf.PolicyLogger;
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -202,33 +196,6 @@ public abstract class Policy {
                return dynamicMatch;
        }
 
-       //validation for numeric
-       protected boolean isNumeric(String str){
-               for (char c : str.toCharArray()){
-                       if (!Character.isDigit(c)) return false;
-               }
-               return true;
-       }
-
-       // Validation for json.
-       protected static boolean isJSONValid(String data) {
-               JsonReader jsonReader = null;
-               try {
-                   new JSONObject(data);
-                       InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
-                       jsonReader = Json.createReader(stream);
-                       LOGGER.info("Json Value is: " + jsonReader.read().toString() );
-               } catch (Exception e) {
-                       LOGGER.error("Exception Occured while reading json"+e);
-                       return false;
-               }finally{
-                       if(jsonReader != null){
-                               jsonReader.close();
-                       }
-               }
-               return true;
-       }
-
        //  the Policy Name as Unique One throws error
        @SuppressWarnings("static-access")
        protected Path getNextFilename(Path parent, String policyType, String polcyFileName, Integer version) {
index 19e567d..a8e1b94 100644 (file)
                     <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="ONAPName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
                 </Match>
                 <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
-                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${actor}</AttributeValue>
+                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">(?i)${actor}</AttributeValue>
                     <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="actor" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
                 </Match>
                 <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
-                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${recipe}</AttributeValue>
+                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">(?i)${recipe}</AttributeValue>
                     <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="recipe" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
                 </Match>
                 <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
index ed5b27b..6dee0cb 100644 (file)
                     <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="ONAPName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
                 </Match>
                 <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
-                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${actor}</AttributeValue>
+                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">(?i)${actor}</AttributeValue>
                     <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="actor" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
                 </Match>
                 <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
-                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${recipe}</AttributeValue>
+                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">(?i)${recipe}</AttributeValue>
                     <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="recipe" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
                 </Match>
                 <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
index c8d3d74..690e94a 100644 (file)
@@ -82,12 +82,12 @@ public class ConfigPolicyService {
                        message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.";
                        return false;
                }
-               message = PolicyUtils.emptyPolicyValidator(onapName);
+               message = PolicyUtils.policySpecialCharValidator(onapName);
         if(!message.contains("success")){
             message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
             return false;
         }
-        message = PolicyUtils.emptyPolicyValidator(configName);
+        message = PolicyUtils.policySpecialCharValidator(configName);
         if(!message.contains("success")){
             message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
             return false;
index 945cdba..528e5cd 100644 (file)
@@ -234,12 +234,12 @@ public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService
             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
             return false;
         }
-        message = PolicyUtils.emptyPolicyValidator(policyScope);
+        message = PolicyUtils.policySpecialCharValidator(policyScope);
         if(!message.contains("success")){
             message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
             return false;
         }
-        message = PolicyUtils.emptyPolicyValidator(policyName);
+        message = PolicyUtils.policySpecialCharValidator(policyName);
         if(!message.contains("success")){
             message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
             return false;
index 6ca52ca..bba5196 100644 (file)
@@ -99,7 +99,7 @@ public class NotificationService {
                        dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
                        aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN");
                        aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD");
-                       interval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY, Integer.toString(interval)));
+            interval = Integer.parseInt(XACMLProperties.getProperty("CLIENT_INTERVAL", Integer.toString(interval)));
                        if(dmaapServers==null || aafLogin==null || aafPassword==null){
                                logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
                                return;
@@ -269,7 +269,7 @@ public class NotificationService {
                                        Date currentTime = new Date();
                                        long timeDiff = 0;
                                        timeDiff = currentTime.getTime()-map.getValue().getTime();
-                                       if(timeDiff < (interval+1500)){
+                                       if(timeDiff > (interval+1500)){
                                                removeTopic(map.getKey());
                                        }
                                }
index b88c935..6cf2e94 100644 (file)
@@ -118,6 +118,10 @@ xacml.rest.pap.password=alpha123
 
 # Delay for Notifications Don't change this. Value in milliSec.  
 xacml.rest.notification.delay=30
+
+# Client interval to ping notification service. 
+CLIENT_INTERVAL=15000
+
 # Buffer Size. 
 REQUEST_BUFFER_SIZE=15
 
index 5525379..a99d23e 100644 (file)
@@ -1458,7 +1458,7 @@ public class PolicyManagerServlet extends HttpServlet {
                                validateName = name;
                        }
                        if(!name.isEmpty()){
-                               String validate = PolicyUtils.emptyPolicyValidator(validateName);
+                               String validate = PolicyUtils.policySpecialCharValidator(validateName);
                                if(!validate.contains("success")){
                                        return error(validate);
                                } 
index 45369ce..fc77c93 100644 (file)
@@ -120,6 +120,9 @@ public class DecisionPolicyController extends RestrictedBaseController {
                                                                                //
                                                                                AttributeValueType attributeValue = match.getAttributeValue();
                                                                                String value = (String) attributeValue.getContent().get(0);
+                                        if(value!=null){
+                                            value = value.replaceAll("\\(\\?i\\)", "");
+                                        }
                                                                                AttributeDesignatorType designator = match.getAttributeDesignator();
                                                                                String attributeId = designator.getAttributeId();
                                                                                // First match in the target is OnapName, so set that value.
@@ -203,13 +206,13 @@ public class DecisionPolicyController extends RestrictedBaseController {
                                                                        YAMLParams yamlParams = new YAMLParams();
                                                                        for(int i=0; i<attributeList.size() ; i++){
                                                                                Map<String, String> map = (Map<String,String>)attributeList.get(i);
-                                                                               if(map.get("key").equals("actor")){
+                                                                               if("actor".equals(map.get("key"))){
                                                                                        yamlParams.setActor(map.get("value"));
-                                                                               }else if(map.get("key").equals("recipe")){
+                                                                               }else if("recipe".equals(map.get("key"))){
                                                                                        yamlParams.setRecipe(map.get("value"));
-                                                                               }else if(map.get("key").equals("targets")){
+                                                                               }else if("target".equals(map.get("key"))){
                                                                                        yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
-                                                                               }else if(map.get("key").equals("clname")){
+                                                                               }else if("clname".equals(map.get("key"))){
                                                                                        yamlParams.setClname(map.get("value"));
                                                                                }
                                                                        }
index d1fba38..050455a 100644 (file)
 package org.onap.policy.controller;
 
 
-import java.io.ByteArrayInputStream;
 import java.io.IOException;
-import java.io.InputStream;
 import java.io.PrintWriter;
-import java.io.StringReader;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
-import java.util.Scanner;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
 
-import javax.json.Json;
-import javax.json.JsonReader;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
 
 import org.apache.commons.lang.StringUtils;
-import org.dom4j.util.XMLErrorHandler;
 import org.json.JSONObject;
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 import org.onap.policy.common.logging.flexlogger.Logger;
@@ -63,13 +50,10 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.servlet.ModelAndView;
-import org.xml.sax.InputSource;
-import org.xml.sax.XMLReader;
 
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.CharMatcher;
 import com.google.common.base.Splitter;
 import com.google.common.base.Strings;
 
@@ -86,14 +70,8 @@ public class PolicyValidationController extends RestrictedBaseController {
        public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
        public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
        public static final String MICROSERVICES="Micro Service";
-       private Pattern pattern;
-       private Matcher matcher;
        private static Map<String, String> mapAttribute = new HashMap<>();
 
-       private static final String EMAIL_PATTERN = 
-                       "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
-                                       + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
-
        @Autowired
        CommonClassDao commonClassDao;
 
@@ -107,7 +85,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                        JsonNode root = mapper.readTree(request.getReader());
                        PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
                        if(policyData.getPolicyName() != null){
-                               String policyNameValidate = emptyValidator(policyData.getPolicyName());
+                               String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
                                if(!policyNameValidate.contains("success")){
                                        responseString.append("PolicyName:" +  policyNameValidate + "<br>");
                                        valid = false;
@@ -117,7 +95,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                valid = false;
                        }
                        if(policyData.getPolicyDescription() != null){
-                               String descriptionValidate = descriptionValidator(policyData.getPolicyDescription());
+                               String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
                                if(!descriptionValidate.contains("success")){
                                        responseString.append("Description:" +  descriptionValidate + "<br>");
                                        valid = false;
@@ -128,7 +106,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) 
                                                ||  policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) {
                                        if(policyData.getOnapName() != null){
-                                               String onapNameValidate = emptyValidator(policyData.getOnapName());
+                                               String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
                                                if(!onapNameValidate.contains("success")){
                                                        responseString.append("OnapName:" +  onapNameValidate + "<br>");
                                                        valid = false;
@@ -140,7 +118,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                }
 
                                if(policyData.getRiskType() != null){
-                                       String riskTypeValidate = emptyValidator(policyData.getRiskType());
+                                       String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
                                        if(!riskTypeValidate.contains("success")){
                                                responseString.append("RiskType:" +  riskTypeValidate + "<br>");
                                                valid = false;
@@ -151,7 +129,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                }
 
                                if(policyData.getRiskLevel() != null){
-                                       String validateRiskLevel = emptyValidator(policyData.getRiskLevel());
+                                       String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
                                        if(!validateRiskLevel.contains("success")){
                                                responseString.append("RiskLevel:" +  validateRiskLevel + "<br>");
                                                valid = false;
@@ -162,7 +140,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                }
 
                                if(policyData.getGuard() != null){
-                                       String validateGuard = emptyValidator(policyData.getGuard());
+                                       String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
                                        if(!validateGuard.contains("success")){
                                                responseString.append("Guard:" +  validateGuard + "<br>");
                                                valid = false;
@@ -174,7 +152,7 @@ public class PolicyValidationController extends RestrictedBaseController {
 
                                if(policyData.getConfigPolicyType().equals("Base")){
                                        if(policyData.getConfigName() != null){
-                                               String configNameValidate = emptyValidator(policyData.getConfigName());
+                                               String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
                                                if(!configNameValidate.contains("success")){
                                                        responseString.append("ConfigName:" +  configNameValidate + "<br>");
                                                        valid = false;
@@ -184,7 +162,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                                valid = false;
                                        }
                                        if(policyData.getConfigType() != null){
-                                               String configTypeValidate = emptyValidator(policyData.getConfigType());
+                                               String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
                                                if(!configTypeValidate.contains("success")){
                                                        responseString.append("ConfigType:" +  configTypeValidate + "<br>");
                                                        valid = false;
@@ -198,17 +176,17 @@ public class PolicyValidationController extends RestrictedBaseController {
                                                String policyType = policyData.getConfigType();
                                                if (policyType != null) {
                                                        if (policyType.equals("JSON")) {
-                                                               if (!isJSONValid(configBodyData)) {
+                                                               if (!PolicyUtils.isJSONValid(configBodyData)) {
                                                                        responseString.append("Config Body: JSON Content is not valid" + "<br>");
                                                                        valid = false;
                                                                }
                                                        } else if (policyType.equals("XML")) {
-                                                               if (!isXMLValid(configBodyData)) {
+                                                               if (!PolicyUtils.isXMLValid(configBodyData)) {
                                                                        responseString.append("Config Body: XML Content data is not valid" + "<br>");
                                                                        valid = false;
                                                                }
                                                        } else if (policyType.equals("PROPERTIES")) {
-                                                               if (!isPropValid(configBodyData)||configBodyData.equals("")) {
+                                                               if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
                                                                        responseString.append("Config Body: Property data is not valid" + "<br>");
                                                                        valid = false;
                                                                } 
@@ -227,7 +205,7 @@ public class PolicyValidationController extends RestrictedBaseController {
 
                                if(policyData.getConfigPolicyType().equals("Firewall Config")){
                                        if(policyData.getConfigName() != null){
-                                               String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName());
+                                               String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
                                                if(!configNameValidate.contains("success")){
                                                        responseString.append("<b>ConfigName</b>:<i>" +  configNameValidate + "</i><br>");
                                                        valid = false;
@@ -282,7 +260,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                                        }
                                                }
                                                if(pmBody.getGeoLink() != null){
-                                                       String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink());
+                                                       String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
                                                        if(!result.contains("success")){
                                                                responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
                                                                valid = false;
@@ -293,7 +271,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                                                String key = entry.getKey();
                                                                String value = entry.getValue();
                                                                if(!key.contains("Message")){
-                                                                       String attributeValidate = PolicyUtils.emptyPolicyValidator(value);
+                                                                       String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
                                                                        if(!attributeValidate.contains("success")){
                                                                                responseString.append("<b>Attributes</b>:<i>" +  key + " : value has spaces</i><br>");
                                                                                valid = false;
@@ -308,7 +286,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                }
                                if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){
                                        if(root.get("policyData").get("jsonBodyData") != null){
-                                               ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
+                                               ClosedLoopFaultBody faultBody = mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
                                                if(faultBody.getEmailAddress() != null){
                                                        String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
                                                        if(result != "success"){
@@ -333,11 +311,11 @@ public class PolicyValidationController extends RestrictedBaseController {
                                                        valid = false;
                                                }
                                                if(faultBody.getGeoLink() != null){
-                                                       String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink());
+                                                       String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
                                                        if(!result.contains("success")){
                                                                responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
                                                                valid = false;
-                                                       };
+                                                       }
                                                }
 
                                                if(faultBody.getTimeInterval() == 0){
@@ -429,7 +407,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                        }
                        if (policyData.getPolicyType().equals(DECISION_POLICY)){
                                if(policyData.getOnapName() != null){
-                                       String onapNameValidate = emptyValidator(policyData.getOnapName());
+                                       String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
                                        if(!onapNameValidate.contains("success")){
                                                responseString.append("OnapName:" +  onapNameValidate + "<br>");
                                                valid = false;
@@ -513,7 +491,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                                                valid = false;
                                                        }else{
                                                                for(String blackList: policyData.getYamlparams().getBlackList()){
-                                                                       if(blackList==null || !("success".equals(emptyValidator(blackList)))){
+                                                                       if(blackList==null || !("success".equals(PolicyUtils.policySpecialCharValidator(blackList)))){
                                                                                responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
                                                                                valid = false;
                                                                                break;
@@ -527,11 +505,11 @@ public class PolicyValidationController extends RestrictedBaseController {
 
                        if(policyData.getPolicyType().equals(ACTION_POLICY)){
                                if(policyData.getActionPerformer() != null){
-                                       String actionPerformer = emptyValidator(policyData.getActionPerformer());
+                                       String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
                                        if(!actionPerformer.contains("success")){
                                                responseString.append("ActionPerformer:" +  actionPerformer + "<br>");
                                                valid = false;
-                                       };
+                                       }
                                }else{
                                        responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
                                        valid = false;
@@ -561,7 +539,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                                        valid = false;
                                }
                                if(policyData.getActionAttributeValue() != null){
-                                       String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
+                                       String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
                                        if(!actionAttribute.contains("success")){
                                                responseString.append("ActionAttribute:" +  actionAttribute + "<br>");
                                                valid = false;
@@ -630,49 +608,6 @@ public class PolicyValidationController extends RestrictedBaseController {
                return null;
        }
 
-       protected String  emptyValidator(String field){
-               String error;
-               if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
-                       error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
-                       return error;
-               } else {
-                       if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
-                               error = "success";
-                       }else{
-                               error = "The Value Contains Non ASCII Characters";
-                               return error;
-                       }       
-               }
-               return error;   
-       }
-
-       protected String descriptionValidator(String field) {
-               String error;
-               if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
-                       error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
-                       return error;
-               } else {
-                       error = "success";
-               }
-               return error;   
-       }
-
-       public String validateEmailAddress(String emailAddressValue) {
-               String error = "success";
-               List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
-               for(int i =0 ; i < emailList.size() ; i++){
-                       pattern = Pattern.compile(EMAIL_PATTERN);
-                       matcher = pattern.matcher(emailList.get(i).trim());
-                       if(!matcher.matches()){
-                               error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i).toString();
-                               return error;
-                       }else{
-                               error = "success";
-                       }
-               }
-               return error;           
-       }
-
        protected String emailValidation(String email, String response){
                if(email != null){
                        String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
@@ -713,66 +648,4 @@ public class PolicyValidationController extends RestrictedBaseController {
                        }
                }
        }
-
-       // Validation for json.
-       protected static boolean isJSONValid(String data) {
-               JsonReader jsonReader = null;
-               try {
-                       new JSONObject(data);
-                       InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
-                       jsonReader = Json.createReader(stream);
-                       LOGGER.info("Json Value is: " + jsonReader.read().toString() );
-               } catch (Exception e) {
-                       LOGGER.error("Exception Occured While Validating"+e);
-                       return false;
-               }finally{
-                       if(jsonReader != null){
-                               jsonReader.close();
-                       }
-               }
-               return true;
-       }
-
-       // Validation for XML.
-       private boolean isXMLValid(String data) {
-               SAXParserFactory factory = SAXParserFactory.newInstance();
-               factory.setValidating(false);
-               factory.setNamespaceAware(true);
-               try {
-                       SAXParser parser = factory.newSAXParser();
-                       XMLReader reader = parser.getXMLReader();
-                       reader.setErrorHandler(new XMLErrorHandler());
-                       reader.parse(new InputSource(new StringReader(data)));
-               } catch (Exception e) {
-                       LOGGER.error("Exception Occured While Validating"+e);
-                       return false;
-               }
-               return true;
-       }
-
-       // Validation for Properties file.
-       public boolean isPropValid(String prop) {
-               Scanner scanner = new Scanner(prop);
-               while (scanner.hasNextLine()) {
-                       String line = scanner.nextLine();
-                       line = line.replaceAll("\\s+", "");
-                       if (line.startsWith("#")) {
-                               continue;
-                       } else {
-                               if (line.contains("=")) {
-                                       String[] parts = line.split("=");
-                                       if (parts.length < 2) {
-                                               scanner.close();
-                                               return false;
-                                       }
-                               } else {
-                                       scanner.close();
-                                       return false;
-                               }
-                       }
-               }
-               scanner.close();
-               return true;
-       }
-
 }
\ No newline at end of file
index e5af8d7..b7f1371 100644 (file)
                                        <groupId>org.powermock</groupId>
                                        <artifactId>powermock-api-mockito</artifactId>
                                </exclusion>
-                               <exclusion>
-                                       <groupId>com.att.aft</groupId>
-                               <artifactId>dme2</artifactId>
-                               </exclusion>
                        </exclusions>
                </dependency>
                <!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
index af26643..c083705 100644 (file)
                <dependency>
                        <groupId>org.onap.policy.common</groupId>
                        <artifactId>integrity-monitor</artifactId>
-                       <version>${common-modules.version}</version> 
+                       <version>${common-modules.version}</version>
                </dependency>
                <dependency>
                        <groupId>org.onap.policy.common</groupId>
                        <artifactId>integrity-audit</artifactId>
-                       <version>${common-modules.version}</version> 
+                       <version>${common-modules.version}</version>
                </dependency>
                <dependency>
                        <groupId>org.onap.policy.common</groupId>
                        <groupId>org.drools</groupId>
                        <artifactId>drools-verifier</artifactId>
                        <version>6.3.0.Final</version>
+                       <exclusions>
+                               <exclusion>
+                                       <groupId>com.google.guava</groupId>
+                                       <artifactId>guava</artifactId>
+                               </exclusion>
+                       </exclusions>
                </dependency>
                <dependency>
                        <groupId>com.att.cadi</groupId>
                        <version>1.3.0</version>
                </dependency>
                <dependency>
-               <groupId>com.att.aft</groupId>
-               <artifactId>dme2</artifactId>
-               <version>3.1.200</version>
-               </dependency>
-               <dependency>
-                       <groupId>com.att.nsa</groupId>
-                       <artifactId>cambriaClient</artifactId>
-                       <version>0.0.1</version>
-                       <exclusions>
-                               <exclusion>
-                                       <groupId>org.slf4j</groupId>
-                                       <artifactId>slf4j-log4j12</artifactId>
-                               </exclusion>
-                       </exclusions>
+                       <groupId>com.att.aft</groupId>
+                       <artifactId>dme2</artifactId>
+                       <version>3.1.200</version>
                </dependency>
                <dependency>
                        <groupId>com.att.nsa</groupId>
index c1f4fed..10268f6 100644 (file)
@@ -34,7 +34,7 @@ public class StdLoadedPolicy implements LoadedPolicy{
        @Override
        public String getPolicyName() {
                if(policyName!=null && policyName.contains(".xml")){
-                       return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf(".")).lastIndexOf(".")));
+                       return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf('.')).lastIndexOf('.')));
                }
                return this.policyName;
        }
index bdce33a..5430e24 100644 (file)
@@ -38,7 +38,7 @@ public class StdRemovedPolicy implements RemovedPolicy{
        @Override
        public String getPolicyName() {
                if(policyName!=null && policyName.contains(".xml")){
-                       return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf(".")).lastIndexOf(".")));
+                       return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf('.')).lastIndexOf('.')));
                }
                return this.policyName;
        }
index 0f48760..ecb51b2 100644 (file)
@@ -65,9 +65,6 @@ public class AAFPolicyClientImpl implements AAFPolicyClient{
        private static Access access = null;
 
        private AAFPolicyClientImpl(Properties properties) throws AAFPolicyException{
-               if(instance == null){
-                       instance = this;
-               }
                setup(properties);
        }
 
@@ -93,7 +90,6 @@ public class AAFPolicyClientImpl implements AAFPolicyClient{
                        props.setProperty("AFT_LATITUDE", properties.getProperty("AFT_LATITUDE", DEFAULT_AFT_LATITUDE));
                        props.setProperty("AFT_LONGITUDE", properties.getProperty("AFT_LONGITUDE", DEFAULT_AFT_LONGITUDE));
                        String aftEnv = TEST_AFT_ENVIRONMENT;
-                       //props.setProperty(Config.CADI_KEYFILE,"keyfile");
                        props.setProperty("aaf_id",properties.getProperty("aaf_id", "aafID"));
                        props.setProperty("aaf_password", properties.getProperty("aaf_password", "aafPass"));
                        if(properties.containsKey(Config.AAF_URL)){
@@ -203,8 +199,8 @@ public class AAFPolicyClientImpl implements AAFPolicyClient{
        private static boolean setUpAAF(){
                try {
                        aafCon = new AAFConDME2(access);
-                       aafLurPerm = aafCon.newLur();//new AAFLurPerm(aafCon);
-                       aafAuthn = aafCon.newAuthn(aafLurPerm);//new AAFAuthn(aafCon, aafLurPerm);
+                       aafLurPerm = aafCon.newLur();
+                       aafAuthn = aafCon.newAuthn(aafLurPerm);
                        return true;
                } catch (Exception e) {
                        logger.error("Error while setting up AAF Connection " + e.getMessage() + e);
index d4f1116..3cdb515 100644 (file)
@@ -53,8 +53,11 @@ import com.github.fge.jsonpatch.diff.JsonDiff;
  */
 public class BackUpMonitor {
     private static final Logger LOGGER = Logger.getLogger(BackUpMonitor.class.getName());
-    private static final int DEFAULT_PING = 15000; // Value is in milliseconds.
-
+    private static final int DEFAULT_PING = 500; // Value is in milliseconds.
+    private static final String PING_INTERVAL = "ping_interval";
+    private static final String MASTER = "MASTER";
+    private static final String SLAVE = "SLAVE";
+    
     private static BackUpMonitor instance = null;
     private static String resourceName = null;
     private static String resourceNodeName = null;
@@ -65,6 +68,8 @@ public class BackUpMonitor {
     private static Object lock = new Object();
     private static Object notificationLock = new Object();
     private static BackUpHandler handler = null;
+    private static Boolean stopFlag = false;
+    private static Thread t = null;
     private EntityManager em;
     private EntityManagerFactory emf;
 
@@ -77,14 +82,11 @@ public class BackUpMonitor {
 
     private BackUpMonitor(String resourceNodeName, String resourceName, Properties properties, BackUpHandler handler)
             throws BackUpMonitorException {
-        if (instance == null) {
-            instance = this;
-        }
-        BackUpMonitor.resourceNodeName = resourceNodeName;
-        BackUpMonitor.resourceName = resourceName;
-        BackUpMonitor.handler = handler;
+        init(resourceName, resourceNodeName, handler);
         // Create Persistence Entity
-        properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePU.xml");
+        if(!properties.containsKey(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML)){
+            properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePU.xml");
+        }
         emf = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties);
         if (emf == null) {
             LOGGER.error("Unable to create Entity Manger Factory ");
@@ -94,12 +96,31 @@ public class BackUpMonitor {
 
         // Check Database if this is Master or Slave.
         checkDataBase();
-
         // Start thread.
-        Thread t = new Thread(new BMonitor());
+        startThread(new BMonitor());
+    }
+    
+    private static void startThread(BMonitor bMonitor) {
+        t = new Thread(bMonitor);
         t.start();
     }
 
+    public static void stop() throws InterruptedException{
+        stopFlag = true;
+        if(t!=null){
+            t.interrupt();
+            t.join();
+        }
+        instance = null;
+    }
+
+    private static void init(String resourceName, String resourceNodeName, BackUpHandler handler) {
+        BackUpMonitor.resourceNodeName = resourceNodeName;
+        BackUpMonitor.resourceName = resourceName;
+        BackUpMonitor.handler = handler;
+        stopFlag = false;
+    }
+
     /**
      * Gets the BackUpMonitor Instance if given proper resourceName and properties. Else returns null.
      * 
@@ -142,17 +163,12 @@ public class BackUpMonitor {
             LOGGER.error("javax.persistence.jdbc.user property is empty");
             return false;
         }
-        if (properties.getProperty("javax.persistence.jdbc.password") == null
-                || properties.getProperty("javax.persistence.jdbc.password").trim().equals("")) {
-            LOGGER.error("javax.persistence.jdbc.password property is empty");
-            return false;
-        }
-        if (properties.getProperty("ping_interval") == null
-                || properties.getProperty("ping_interval").trim().equals("")) {
+        if (properties.getProperty(PING_INTERVAL) == null
+                || properties.getProperty(PING_INTERVAL).trim().equals("")) {
             LOGGER.info("ping_interval property not specified. Taking default value");
         } else {
             try {
-                pingInterval = Integer.parseInt(properties.getProperty("ping_interval").trim());
+                pingInterval = Integer.parseInt(properties.getProperty(PING_INTERVAL).trim());
             } catch (NumberFormatException e) {
                 LOGGER.warn("Ignored invalid proeprty ping_interval. Taking default value: " + pingInterval);
                 pingInterval = DEFAULT_PING;
@@ -185,7 +201,7 @@ public class BackUpMonitor {
         @Override
         public void run() {
             LOGGER.info("Starting BackUpMonitor Thread.. ");
-            while (true) {
+            while (!stopFlag) {
                 try {
                     TimeUnit.MILLISECONDS.sleep(pingInterval);
                     checkDataBase();
@@ -198,26 +214,27 @@ public class BackUpMonitor {
 
     // Set Master
     private static BackUpMonitorEntity setMaster(BackUpMonitorEntity bMEntity) {
-        bMEntity.setFlag("MASTER");
+        bMEntity.setFlag(MASTER);
         setFlag(true);
         return bMEntity;
     }
 
     // Set Slave
     private static BackUpMonitorEntity setSlave(BackUpMonitorEntity bMEntity) {
-        bMEntity.setFlag("SLAVE");
+        bMEntity.setFlag(SLAVE);
         setFlag(false);
         return bMEntity;
     }
 
     // Check Database and set the Flag.
     private void checkDataBase() throws BackUpMonitorException {
-        EntityTransaction et = em.getTransaction();
-        setNotificationRecord();
-        // Clear Cache.
-        LOGGER.info("Clearing Cache");
-        em.getEntityManagerFactory().getCache().evictAll();
+        EntityTransaction et = null;
         try {
+            et = em.getTransaction();
+            setNotificationRecord();
+            // Clear Cache.
+            LOGGER.info("Clearing Cache");
+            em.getEntityManagerFactory().getCache().evictAll();
             LOGGER.info("Checking Datatbase for BackUpMonitor.. ");
             et.begin();
             Query query = em.createQuery("select b from BackUpMonitorEntity b where b.resourceNodeName = :nn");
@@ -247,7 +264,7 @@ public class BackUpMonitor {
                     BackUpMonitorEntity bMEntity = (BackUpMonitorEntity) bMList.get(i);
                     LOGGER.info("Refreshing Entity. ");
                     em.refresh(bMEntity);
-                    if (bMEntity.getFlag().equalsIgnoreCase("MASTER")) {
+                    if (bMEntity.getFlag().equalsIgnoreCase(MASTER)) {
                         masterEntities.add(bMEntity);
                     }
                     if (bMEntity.getResourceName().equals(resourceName)) {
@@ -256,7 +273,7 @@ public class BackUpMonitor {
                 }
                 if (selfEntity != null) {
                     LOGGER.info("Resource Name already Exists: " + resourceName);
-                    if (selfEntity.getFlag().equalsIgnoreCase("MASTER")) {
+                    if (selfEntity.getFlag().equalsIgnoreCase(MASTER)) {
                         // Already Master Mode.
                         setFlag(true);
                         LOGGER.info(resourceName + " is on Master Mode");
@@ -306,19 +323,19 @@ public class BackUpMonitor {
                             // Slave.
                             BackUpMonitorEntity masterEntity = null;
                             for (BackUpMonitorEntity currentEntity : masterEntities) {
-                                if (currentEntity.getFlag().equalsIgnoreCase("MASTER")) {
+                                if (currentEntity.getFlag().equalsIgnoreCase(MASTER)) {
                                     if (masterEntity == null) {
                                         masterEntity = currentEntity;
                                     } else if (currentEntity.getTimeStamp().getTime() > masterEntity.getTimeStamp()
                                             .getTime()) {
                                         // False Master, Update master to slave and take currentMaster as Master.
-                                        masterEntity.setFlag("SLAVE");
+                                        masterEntity.setFlag(SLAVE);
                                         masterEntity.setTimeStamp(new Date());
                                         em.persist(masterEntity);
                                         em.flush();
                                         masterEntity = currentEntity;
                                     } else {
-                                        currentEntity.setFlag("SLAVE");
+                                        currentEntity.setFlag(SLAVE);
                                         currentEntity.setTimeStamp(new Date());
                                         em.persist(currentEntity);
                                         em.flush();
@@ -339,7 +356,7 @@ public class BackUpMonitor {
                                 if (timeDiff > (pingInterval + 1500)) {
                                     // This is down or has an issue and we need to become Master while turning the
                                     // Master to slave.
-                                    masterEntity.setFlag("SLAVE");
+                                    masterEntity.setFlag(SLAVE);
                                     String lastNotification = null;
                                     if (masterEntity.getNotificationRecord() != null) {
                                         lastNotification = calculatePatch(masterEntity.getNotificationRecord());
@@ -366,7 +383,7 @@ public class BackUpMonitor {
             et.commit();
         } catch (Exception e) {
             LOGGER.error("failed Database Operation " + e.getMessage(), e);
-            if (et.isActive()) {
+            if (et!=null && et.isActive()) {
                 et.rollback();
             }
             throw new BackUpMonitorException(e);
index 1b31394..2c867a3 100644 (file)
@@ -70,7 +70,7 @@ public interface BusConsumer {
                public DmaapConsumerWrapper(List<String> servers, String topic, 
                                                                String aafLogin, String aafPassword,
                                                                String consumerGroup, String consumerInstance,
-                                                               int fetchTimeout, int fetchLimit)  throws MalformedURLException{
+                                                               int fetchTimeout, int fetchLimit) throws MalformedURLException{
                                        
                        this.consumer = new MRConsumerImpl(servers, topic, 
                                                                                           consumerGroup, consumerInstance, 
index 3190aa0..3a12122 100644 (file)
@@ -42,7 +42,7 @@ public interface BusPublisher {
         * @return true if success, false otherwise
         * @throws IllegalArgumentException if no message provided
         */
-       public boolean send(String partitionId, String message) throws IllegalArgumentException;
+       public boolean send(String partitionId, String message);
        
        /**
         * closes the publisher
@@ -114,8 +114,7 @@ public interface BusPublisher {
                 * {@inheritDoc}
                 */
                @Override
-               public boolean send(String partitionId, String message) 
-                               throws IllegalArgumentException {
+               public boolean send(String partitionId, String message){
                        if (message == null)
                                throw new IllegalArgumentException("No message provided");
                        
index 8bc83dc..b74bd28 100644 (file)
@@ -26,96 +26,142 @@ import java.io.UnsupportedEncodingException;
 import java.util.Arrays;
 import java.util.Base64;
 import java.util.List;
+import java.util.Scanner;
 import java.util.StringTokenizer;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
 import org.drools.core.io.impl.ReaderResource;
 import org.drools.verifier.Verifier;
 import org.drools.verifier.VerifierError;
 import org.drools.verifier.builder.VerifierBuilder;
 import org.drools.verifier.builder.VerifierBuilderFactory;
 import org.kie.api.io.ResourceType;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.xml.sax.InputSource;
+import org.xml.sax.XMLReader;
 
+import com.att.aft.dme2.internal.gson.JsonParser;
+import com.att.aft.dme2.internal.gson.JsonSyntaxException;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.common.base.CharMatcher;
 
 public class PolicyUtils {
-       
-       public static final String EMAIL_PATTERN =
+    private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class);
+    
+    public static final String EMAIL_PATTERN =
             "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
             + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
-       private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
-       private static final String SUCCESS = "success";
-       
-       private PolicyUtils(){
-               // Private Constructor
-       }
-       public static String objectToJsonString(Object o) throws JsonProcessingException{
-               ObjectMapper mapper = new ObjectMapper();
-               return mapper.writeValueAsString(o);
-       }
-       
-       public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
-               ObjectMapper mapper = new ObjectMapper();
-               return mapper.readValue(jsonString, className);
-       }
-       
-       public static String decode(String encodedString) throws UnsupportedEncodingException { 
-               if(encodedString!=null && !encodedString.isEmpty()){ 
-                       return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); 
-               }else{ 
-                       return null; 
-               } 
-       }
-       
-       public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException {
-               if(encodedValue!=null && encodedValue.contains("Basic ")){
-                       String encodedUserPassword = encodedValue.replaceFirst("Basic"  + " ", "");
-                       String usernameAndPassword = null;
-                       byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
-                       usernameAndPassword = new String(decodedBytes, "UTF-8");
-                       StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
-                       String username = tokenizer.nextToken();
-                       String password = tokenizer.nextToken();
-                       return new String[]{username, password};
-               }else{
-                       return new String[]{};
-               }
-       }
-       
-       public static String  emptyPolicyValidator(String field){
+    private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
+    private static final String SUCCESS = "success";
+    
+    private PolicyUtils(){
+        // Private Constructor
+    }
+    
+    /**
+     * Converts an Object to JSON String 
+     * 
+     * @param o Object 
+     * @return String format of Object JSON. 
+     * @throws JsonProcessingException
+     */
+    public static String objectToJsonString(Object o) throws JsonProcessingException{
+        ObjectMapper mapper = new ObjectMapper();
+        return mapper.writeValueAsString(o);
+    }
+    
+    /**
+     * Converts JSON string into Object
+     * 
+     * @param jsonString 
+     * @param className equivalent Class of the given JSON string 
+     * @return T instance of the class given. 
+     * @throws IOException
+     */
+    public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
+        ObjectMapper mapper = new ObjectMapper();
+        return mapper.readValue(jsonString, className);
+    }
+    
+    /**
+     * Decode a base64 string 
+     * 
+     * @param encodedString
+     * @return String
+     * @throws UnsupportedEncodingException
+     */
+    public static String decode(String encodedString) throws UnsupportedEncodingException { 
+        if(encodedString!=null && !encodedString.isEmpty()){ 
+            return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); 
+        }else{ 
+            return null; 
+        } 
+    }
+    
+    /**
+     * Decodes Basic Authentication 
+     * 
+     * @param encodedValue
+     * @return
+     * @throws UnsupportedEncodingException
+     */
+    public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException {
+        if(encodedValue!=null && encodedValue.contains("Basic ")){
+            String encodedUserPassword = encodedValue.replaceFirst("Basic"  + " ", "");
+            String usernameAndPassword = null;
+            byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
+            usernameAndPassword = new String(decodedBytes, "UTF-8");
+            StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
+            String username = tokenizer.nextToken();
+            String password = tokenizer.nextToken();
+            return new String[]{username, password};
+        }else{
+            return new String[]{};
+        }
+    }
+    
+    /**
+     * Validate a field if contains space or unacceptable policy input and return "success" if good. 
+     * 
+     * @param field
+     * @return
+     */
+    public static String  policySpecialCharValidator(String field){
         String error;
         if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
             error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
-            return error;
-        } else {
-            if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
-                 error = SUCCESS;
-            }else{
-                error = "The Value Contains Non ASCII Characters";
-                return error;
-            }   
+            return error; 
         }
-        return error;   
+        return SUCCESS;   
     } 
     
-       public static String  emptyPolicyValidatorWithSpaceAllowed(String field){
+    /**
+     * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good. 
+     * 
+     * @param field
+     * @return
+     */
+    public static String  policySpecialCharWithSpaceValidator(String field){
         String error;
         if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) {
             error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
             return error;
-        } else {
-            if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
-                 error = SUCCESS;
-            }else{
-                error = "The Value Contains Non ASCII Characters";
-                return error;
-            }   
         }
-        return error;   
+        return SUCCESS;   
     } 
+    
+    /**
+     * Validate the XACML description tag and return "success" if good. 
+     * 
+     * @param field
+     * @return
+     */
     public static String descriptionValidator(String field) {
         String error;
         if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
@@ -127,15 +173,38 @@ public class PolicyUtils {
         return error;   
     }
     
+    /**
+     * Validate if string contains non ASCII characters 
+     * 
+     * @param value
+     * @return
+     */
+    public static boolean containsNonAsciiEmptyChars(String value) {
+        return (value == null|| value.contains(" ") || "".equals(value.trim())|| !CharMatcher.ASCII.matchesAllOf((CharSequence) value))? true:false;
+    }
+    
+    /**
+     * Validate if given string is an integer. 
+     * 
+     * @param number
+     * @return
+     */
     public static Boolean isInteger(String number){
-       try{
-               Integer.parseInt(number);
-       }catch(NumberFormatException e){
-               return false;
-       }
-       return true;
+        if(number==null) {
+            return false;
+        }
+        for (char c : number.toCharArray()){
+            if (!Character.isDigit(c)) return false;
+        }
+        return true;
     }
     
+    /**
+     * Validate Email Address and return "success" if good. 
+     * 
+     * @param emailAddressValue
+     * @return
+     */
     public static String validateEmailAddress(String emailAddressValue) {
         String error = SUCCESS;
         List<String> emailList = Arrays.asList(emailAddressValue.split(","));
@@ -152,8 +221,11 @@ public class PolicyUtils {
         return error;       
     }
     
-    /*
-     * Check for "[ERR" to see if there are any errors. 
+    /**
+     * Validates BRMS rule as per Policy Platform and return string contains "[ERR" if there are any errors.
+     * 
+     * @param rule
+     * @return String error message
      */
     public static String brmsRawValidate(String rule){
         VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
@@ -161,19 +233,19 @@ public class PolicyUtils {
         verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
         // Check if there are any Errors in Verification. 
         if(!verifier.getErrors().isEmpty()){
-               boolean ignore = false;
+            boolean ignore = false;
             StringBuilder message = new StringBuilder("Not a Valid DRL rule"); 
             for(VerifierError error: verifier.getErrors()){
                 // Ignore annotations Error Messages
                 if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){
-                       ignore= true;
+                    ignore= true;
                     message.append("\n" + error.getMessage());
                 }
             }
-            // Ignore new package names with {
+            // Ignore new package names with '{'
             // More checks for message to check if its a package error.
             if(ignore && !message.toString().contains("Parser returned a null Package")){
-               message.append("[ERR 107]");
+                message.append("[ERR 107]");
             }
             return message.toString();
         }
@@ -181,21 +253,90 @@ public class PolicyUtils {
     }
     
     /**
-        * Given a version string consisting of integers with dots between them, convert it into an array of ints.
-        * 
-        * @param version
-        * @return
-        * @throws NumberFormatException
-        */
-       public static int[] versionStringToArray(String version) throws NumberFormatException {
-               if (version == null || version.length() == 0) {
-                       return new int[0];
-               }
-               String[] stringArray = version.split("\\.");
-               int[] resultArray = new int[stringArray.length];
-               for (int i = 0; i < stringArray.length; i++) {
-                       resultArray[i] = Integer.parseInt(stringArray[i]);
-               }
-               return resultArray;
-       }
-}
+     * Validates if the given string is proper JSON format. 
+     * 
+     * @param data
+     * @return
+     */
+    public static boolean isJSONValid(String data) {
+        try{
+            JsonParser parser = new JsonParser();
+            parser.parse(data);
+        }catch(JsonSyntaxException e){
+            LOGGER.error("Exception Occurred While Validating"+e);
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Validates if the given string is proper XML format. 
+     * 
+     * @param data
+     * @return
+     */
+    public static boolean isXMLValid(String data) {
+        SAXParserFactory factory = SAXParserFactory.newInstance();
+        factory.setValidating(false);
+        factory.setNamespaceAware(true);
+        try {
+            SAXParser parser = factory.newSAXParser();
+            XMLReader reader = parser.getXMLReader();
+            reader.setErrorHandler(new XMLErrorHandler());
+            reader.parse(new InputSource(new StringReader(data)));
+        } catch (Exception e) {
+            LOGGER.error("Exception Occured While Validating"+e);
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Validates if given string is valid Properties format. 
+     * 
+     * @param prop
+     * @return
+     */
+    public static boolean isPropValid(String prop) {
+        Scanner scanner = new Scanner(prop);
+        while (scanner.hasNextLine()) {
+            String line = scanner.nextLine();
+            line = line.replaceAll("\\s+", "");
+            if (line.startsWith("#")) {
+                continue;
+            } else {
+                if (line.contains("=")) {
+                    String[] parts = line.split("=");
+                    if (parts.length < 2) {
+                        scanner.close();
+                        return false;
+                    }
+                } else if(!line.trim().isEmpty()){
+                    scanner.close();
+                    return false;
+                }
+            }
+        }
+        scanner.close();
+        return true;
+    }
+    
+    /**
+     * Given a version string consisting of integers with dots between them, convert it into an array of integers.
+     * 
+     * @param version
+     * @return 
+     * @throws NumberFormatException
+     */
+    public static int[] versionStringToArray(String version){
+        if (version == null || version.length() == 0) {
+            return new int[0];
+        }
+        String[] stringArray = version.split("\\.");
+        int[] resultArray = new int[stringArray.length];
+        for (int i = 0; i < stringArray.length; i++) {
+            resultArray[i] = Integer.parseInt(stringArray[i].trim());
+        }
+        return resultArray;
+    }
+}
\ No newline at end of file
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java
new file mode 100644 (file)
index 0000000..3037a42
--- /dev/null
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PolicyEngineUtils
+ * ================================================================================
+ * Copyright (C) 2017 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.utils;
+
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+public class XMLErrorHandler implements ErrorHandler {
+    private static final Logger LOGGER = FlexLogger.getLogger(XMLErrorHandler.class);
+    
+    @Override
+    public void warning(SAXParseException exception) throws SAXException {
+        LOGGER.debug(exception);
+    }
+
+    @Override
+    public void error(SAXParseException exception) throws SAXException {
+        LOGGER.error(exception);
+    }
+
+    @Override
+    public void fatalError(SAXParseException exception) throws SAXException {
+        LOGGER.error(exception);
+    }
+
+}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/test/PolicyUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/test/PolicyUtilsTest.java
deleted file mode 100644 (file)
index 50ae3fe..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PolicyEngineUtils
- * ================================================================================
- * Copyright (C) 2017 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.test;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.junit.Test;
-import org.onap.policy.api.NotificationType;
-import org.onap.policy.api.PDPNotification;
-import org.onap.policy.api.UpdateType;
-import org.onap.policy.std.StdLoadedPolicy;
-import org.onap.policy.std.StdPDPNotification;
-import org.onap.policy.std.StdRemovedPolicy;
-import org.onap.policy.utils.PolicyUtils;
-
-public class PolicyUtilsTest {
-       
-       @Test
-       public void testJsonConversions() throws Exception{
-               StdPDPNotification notification = new StdPDPNotification();
-               notification.setNotificationType(NotificationType.BOTH);
-               Collection<StdRemovedPolicy> removedPolicies = new ArrayList<>();
-               Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
-               StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
-               StdLoadedPolicy updatedPolicy = new StdLoadedPolicy();
-               removedPolicy.setPolicyName("Test");
-               removedPolicy.setVersionNo("1");
-               removedPolicies.add(removedPolicy);
-               updatedPolicy.setPolicyName("Testing");
-               updatedPolicy.setVersionNo("1");
-               updatedPolicy.setUpdateType(UpdateType.NEW);
-               Map<String, String> matches = new HashMap<>();
-               matches.put("key", "value");
-               updatedPolicy.setMatches(matches);
-               loadedPolicies.add(updatedPolicy);
-               notification.setRemovedPolicies(removedPolicies);
-               notification.setLoadedPolicies(loadedPolicies);
-               
-               String json = PolicyUtils.objectToJsonString(notification);
-               PDPNotification getBackObject = PolicyUtils.jsonStringToObject(json, StdPDPNotification.class);
-               assertEquals(0,getBackObject.getNotificationType().compareTo(notification.getNotificationType()));
-               
-       }
-}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/test/testBackUpMonitor.java b/PolicyEngineUtils/src/test/java/org/onap/policy/test/testBackUpMonitor.java
deleted file mode 100644 (file)
index 4cdb818..0000000
+++ /dev/null
@@ -1,121 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PolicyEngineUtils
- * ================================================================================
- * Copyright (C) 2017 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.test;
-
-import static org.junit.Assert.assertNull;
-import java.util.Properties;
-
-import org.junit.Test;
-import org.onap.policy.utils.BackUpMonitor;
-
-
-public class testBackUpMonitor {
-
-       @Test
-       public void backUpMonitorTestFail() throws Exception{
-               Properties properties = new Properties();
-               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
-               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
-               properties.setProperty("javax.persistence.jdbc.user", "policy_user");
-               properties.setProperty("javax.persistence.jdbc.password", "");
-               //properties.setProperty("ping_interval", "500000");
-               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
-               assertNull(bum);
-       }
-       
-       @Test
-       public void backUpMonitorTestFailNoUser() throws Exception{
-               Properties properties = new Properties();
-               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
-               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
-               properties.setProperty("javax.persistence.jdbc.user", "");
-               properties.setProperty("javax.persistence.jdbc.password", "password");
-               //properties.setProperty("ping_interval", "500000");
-               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
-               assertNull(bum);
-       }
-       
-       @Test
-       public void backUpMonitorTestFailNoURL() throws Exception{
-               Properties properties = new Properties();
-               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
-               properties.setProperty("javax.persistence.jdbc.url", "");
-               properties.setProperty("javax.persistence.jdbc.user", "test");
-               properties.setProperty("javax.persistence.jdbc.password", "password");
-               //properties.setProperty("ping_interval", "500000");
-               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
-               assertNull(bum);
-       }
-       
-       @Test
-       public void backUpMonitorTestFailNoDriver() throws Exception{
-               Properties properties = new Properties();
-               properties.setProperty("javax.persistence.jdbc.driver", "");
-               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
-               properties.setProperty("javax.persistence.jdbc.user", "test");
-               properties.setProperty("javax.persistence.jdbc.password", "password");
-               //properties.setProperty("ping_interval", "500000");
-               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
-               assertNull(bum);
-       }
-       
-       @Test
-       public void backUpMonitorTestFailNoNode() throws Exception{
-               Properties properties = new Properties();
-               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
-               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
-               properties.setProperty("javax.persistence.jdbc.user", "test");
-               properties.setProperty("javax.persistence.jdbc.password", "password");
-               //properties.setProperty("ping_interval", "500000");
-               BackUpMonitor bum = BackUpMonitor.getInstance(null, "brms_test" , properties, new Handler());
-               assertNull(bum);
-       }
-       
-       @Test
-       public void backUpMonitorTestFailNoResource() throws Exception{
-               Properties properties = new Properties();
-               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
-               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
-               properties.setProperty("javax.persistence.jdbc.user", "test");
-               properties.setProperty("javax.persistence.jdbc.password", "password");
-               //properties.setProperty("ping_interval", "500000");
-               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), null , properties, new Handler());
-               assertNull(bum);
-       }
-       
-       @Test
-       public void backUpMonitorTestFailNoProperties() throws Exception{
-               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , null, new Handler());
-               assertNull(bum);
-       }
-       
-       @Test
-       public void backUpMonitorTestFailNoHandler() throws Exception{
-               Properties properties = new Properties();
-               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
-               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
-               properties.setProperty("javax.persistence.jdbc.user", "test");
-               properties.setProperty("javax.persistence.jdbc.password", "password");
-               //properties.setProperty("ping_interval", "500000");
-               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, null);
-               assertNull(bum);
-       }
-}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java
new file mode 100644 (file)
index 0000000..2fa822a
--- /dev/null
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PolicyEngineUtils
+ * ================================================================================
+ * Copyright (C) 2017 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.utils.test;
+
+import static org.junit.Assert.assertFalse;
+
+import java.util.Properties;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.utils.AAFPolicyClient;
+import org.onap.policy.utils.AAFPolicyClientImpl;
+import org.onap.policy.utils.AAFPolicyException;
+
+public class AAFClientTest {
+    AAFPolicyClient afClient;
+    String pass = "test";
+    
+    @Before
+    public void setUp() throws AAFPolicyException{
+        Properties props = new Properties();
+        props.setProperty("ENVIRONMENT", "TEST");
+        props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName());
+        afClient  = AAFPolicyClient.getInstance(props);
+    }
+    
+    @Test
+    public void invalidClientTest() throws AAFPolicyException{
+        assertFalse(afClient.checkAuth("test", pass));
+        assertFalse(afClient.checkPerm("test", pass, "policy-engine.config", "*", "*"));
+        Properties props = new Properties();
+        props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName());
+        afClient  = AAFPolicyClient.getInstance(props);
+        assertFalse(afClient.checkAuth("test", pass));
+        props.setProperty("ENVIRONMENT", "PROD");
+        props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName());
+        afClient.updateProperties(props);
+        assertFalse(afClient.checkAuth("test", pass));
+        props.setProperty("aaf_url", "test");
+        afClient.updateProperties(props);
+        assertFalse(afClient.checkAuth("test", pass));
+        props = new Properties();
+        props.setProperty("ENVIRONMENT", "123");
+        afClient.updateProperties(props);
+        assertFalse(afClient.checkAuth("test", pass));
+        assertFalse(afClient.checkAuthPerm("test", pass, "decision", "*", "read"));
+    }
+    
+    @Test(expected = AAFPolicyException.class)
+    public void invalidAAFInstance() throws AAFPolicyException{
+        Properties props = new Properties();
+        props.setProperty("aafClient.impl.className", "errorClass");
+        afClient  = AAFPolicyClient.getInstance(props);
+    }
+    
+    @Test(expected = AAFPolicyException.class)
+    public void testPropNullException() throws AAFPolicyException {
+        afClient.updateProperties(null);
+    }
+
+    @Test(expected = AAFPolicyException.class)
+    public void testPropEmptyException() throws AAFPolicyException {
+        afClient.updateProperties(new Properties());
+    }
+    
+    @Test(expected = AAFPolicyException.class)
+    public void testAAFException() throws AAFPolicyException{
+        new AAFPolicyException();
+        new AAFPolicyException("error", new Exception());
+        throw new AAFPolicyException("error", new Exception(), false, false);
+    }
+}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java
new file mode 100644 (file)
index 0000000..37170f0
--- /dev/null
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PolicyEngineUtils
+ * ================================================================================
+ * Copyright (C) 2017 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.utils.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.net.MalformedURLException;
+import java.util.Arrays;
+
+import org.junit.Test;
+import org.onap.policy.utils.BusConsumer;
+import org.onap.policy.utils.BusPublisher;
+
+import com.att.nsa.mr.client.MRClient.MRApiException;
+
+public class BusTest {
+    
+    @Test 
+    public void busPublisherTest(){
+        BusPublisher bus = new BusPublisher.DmaapPublisherWrapper(Arrays.asList("test"), "test", "test", "test");
+        assertTrue(bus.send("test123", "Hello World!"));
+        assertEquals("DmaapPublisherWrapper [publisher.getAuthDate()=null, publisher.getAuthKey()=null, publisher.getHost()=test, publisher.getProtocolFlag()=HTTPAAF, publisher.getUsername()=test, publisher.getPendingMessageCount()=1]",bus.toString());
+        bus.close();
+    }
+    
+    @Test (expected = MRApiException.class)
+    public void busConsumerFailTest() throws MalformedURLException, MRApiException{
+        new BusConsumer.DmaapConsumerWrapper(Arrays.asList("test"), "test", "test", "test", "test", "test", 1, 1).fetch();
+    }
+    
+    @Test
+    public void busConsumerTest() throws MalformedURLException, MRApiException{
+        BusConsumer bus = new BusConsumer.DmaapConsumerWrapper(Arrays.asList("test"), "test", "test", "test", "test", "test", 1, 1);
+        assertEquals(bus.toString(),"DmaapConsumerWrapper [consumer.getAuthDate()=null, consumer.getAuthKey()=null, consumer.getHost()=test:3904, consumer.getProtocolFlag()=HTTPAAF, consumer.getUsername()=test]");
+        bus.close();
+    }
+
+}
@@ -18,7 +18,7 @@
  * ============LICENSE_END=========================================================
  */
 
-package org.onap.policy.test;
+package org.onap.policy.utils.test;
 
 import org.onap.policy.api.PDPNotification;
 import org.onap.policy.utils.BackUpHandler;
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java
new file mode 100644 (file)
index 0000000..8ec646a
--- /dev/null
@@ -0,0 +1,99 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PolicyEngineUtils
+ * ================================================================================
+ * Copyright (C) 2017 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.utils.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+import org.onap.policy.api.NotificationType;
+import org.onap.policy.api.UpdateType;
+import org.onap.policy.std.NotificationStore;
+import org.onap.policy.std.StdLoadedPolicy;
+import org.onap.policy.std.StdPDPNotification;
+import org.onap.policy.std.StdRemovedPolicy;
+
+public class NotificationStoreTest {
+    
+    @Test
+    public void notificationTest(){
+        StdPDPNotification notification = new StdPDPNotification();
+        notification.setNotificationType(NotificationType.UPDATE);
+        List<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
+        StdLoadedPolicy loadedPolicy = new StdLoadedPolicy();
+        loadedPolicy.setPolicyName("com.testing");
+        loadedPolicy.setUpdateType(UpdateType.NEW);
+        loadedPolicy.setVersionNo("1");
+        Map<String, String> matches = new HashMap<>();
+        matches.put("test", "test");
+        loadedPolicy.setMatches(matches);
+        loadedPolicies.add(loadedPolicy);
+        notification.setLoadedPolicies(loadedPolicies);
+        NotificationStore.recordNotification(notification);
+        assertEquals(notification, NotificationStore.getNotificationRecord());
+        // Add new Notifications. 
+        notification = new StdPDPNotification();
+        notification.setNotificationType(NotificationType.BOTH);
+        loadedPolicies = new ArrayList<>();
+        loadedPolicy = new StdLoadedPolicy();
+        loadedPolicy.setPolicyName("com.testing");
+        loadedPolicy.setUpdateType(UpdateType.UPDATE);
+        loadedPolicy.setVersionNo("2");
+        matches = new HashMap<>();
+        matches.put("test", "test");
+        loadedPolicy.setMatches(matches);
+        loadedPolicies.add(loadedPolicy);
+        notification.setLoadedPolicies(loadedPolicies);
+        List<StdRemovedPolicy> removedPolicies = new ArrayList<>();
+        StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
+        removedPolicy.setPolicyName("com.testing");
+        removedPolicy.setVersionNo("1");
+        notification.setRemovedPolicies(removedPolicies);
+        NotificationStore.recordNotification(notification);
+        assertNotNull(NotificationStore.getNotificationRecord());
+        // Add new Notifications. 
+        notification = new StdPDPNotification();
+        notification.setNotificationType(NotificationType.BOTH);
+        loadedPolicies = new ArrayList<>();
+        loadedPolicy = new StdLoadedPolicy();
+        loadedPolicy.setPolicyName("com.test.xml");
+        loadedPolicy.setUpdateType(UpdateType.NEW);
+        loadedPolicy.setVersionNo("2");
+        matches = new HashMap<>();
+        matches.put("test", "test");
+        loadedPolicy.setMatches(matches);
+        loadedPolicies.add(loadedPolicy);
+        notification.setLoadedPolicies(loadedPolicies);
+        removedPolicies = new ArrayList<>();
+        removedPolicy = new StdRemovedPolicy();
+        removedPolicy.setPolicyName("com.testing.xml");
+        removedPolicy.setVersionNo("2");
+        notification.setRemovedPolicies(removedPolicies);
+        NotificationStore.recordNotification(notification);
+        assertNotNull(NotificationStore.getNotificationRecord());
+    }
+
+}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java
new file mode 100644 (file)
index 0000000..4cc6c90
--- /dev/null
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PolicyEngineUtils
+ * ================================================================================
+ * Copyright (C) 2017 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.utils.test;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.maven.model.Exclusion;
+import org.junit.Test;
+import org.onap.policy.api.PEDependency;
+
+public class PEDependencyTest {
+    
+    @Test
+    public void pojoTests(){
+        PEDependency pe = new PEDependency();
+        pe.setArtifactId("test");
+        pe.setGroupId("test");
+        pe.setVersion("1");
+        pe.setType("jar");
+        pe.setScope("test");
+        pe.setClassifier("pom");
+        List<Exclusion> exclusions = new ArrayList<>();
+        Exclusion e = new Exclusion();
+        e.setArtifactId("ex1");
+        e.setGroupId("eG");
+        exclusions.add(e);
+        pe.setExclusions(exclusions);
+        pe.getDependency();
+        assertEquals(exclusions, pe.getExclusions());
+        assertEquals("pom", pe.getClassifier());
+        assertEquals("test", pe.getScope());
+        assertEquals("jar", pe.getType());
+        assertEquals("1", pe.getVersion());
+        assertEquals("test", pe.getGroupId());
+        assertEquals("test", pe.getArtifactId());
+    }
+
+}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java
new file mode 100644 (file)
index 0000000..586ab35
--- /dev/null
@@ -0,0 +1,209 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PolicyEngineUtils
+ * ================================================================================
+ * Copyright (C) 2017 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.utils.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Test;
+import org.onap.policy.api.NotificationType;
+import org.onap.policy.api.PDPNotification;
+import org.onap.policy.api.UpdateType;
+import org.onap.policy.std.StdLoadedPolicy;
+import org.onap.policy.std.StdPDPNotification;
+import org.onap.policy.std.StdRemovedPolicy;
+import org.onap.policy.utils.PolicyUtils;
+import org.onap.policy.utils.XMLErrorHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+public class PolicyUtilsTest {
+       
+       private static final String ERROR = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
+       private static final String SUCCESS = "success";
+       
+       @Test
+       public void testJsonConversions() throws Exception{
+               StdPDPNotification notification = new StdPDPNotification();
+               notification.setNotificationType(NotificationType.BOTH);
+               Collection<StdRemovedPolicy> removedPolicies = new ArrayList<>();
+               Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
+               StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
+               StdLoadedPolicy updatedPolicy = new StdLoadedPolicy();
+               removedPolicy.setPolicyName("Test");
+               removedPolicy.setVersionNo("1");
+               removedPolicies.add(removedPolicy);
+               updatedPolicy.setPolicyName("Testing");
+               updatedPolicy.setVersionNo("1");
+               updatedPolicy.setUpdateType(UpdateType.NEW);
+               Map<String, String> matches = new HashMap<>();
+               matches.put("key", "value");
+               updatedPolicy.setMatches(matches);
+               loadedPolicies.add(updatedPolicy);
+               notification.setRemovedPolicies(removedPolicies);
+               notification.setLoadedPolicies(loadedPolicies);
+               
+               String json = PolicyUtils.objectToJsonString(notification);
+               PDPNotification getBackObject = PolicyUtils.jsonStringToObject(json, StdPDPNotification.class);
+               assertEquals(0,getBackObject.getNotificationType().compareTo(notification.getNotificationType()));
+               
+       }
+       
+       private String encodedValue(String input){
+               return new String(Base64.getEncoder().encode(input.getBytes()));
+       }
+       
+       @Test
+       public void testDecode() throws Exception{
+               String value = "test";
+               assertEquals(value, PolicyUtils.decode(encodedValue(value)));
+               assertNull(PolicyUtils.decode(null));
+               assertNull(PolicyUtils.decode(""));
+       }
+       
+       @Test
+       public void testBasicEncoding() throws Exception{
+               String userName = "test";
+               String key = "pass";
+               String[] decodedValue = PolicyUtils.decodeBasicEncoding("Basic "+encodedValue(userName+":"+key));
+               assertEquals(userName,decodedValue[0]);
+               assertEquals(key,decodedValue[1]);
+               assertEquals(0, PolicyUtils.decodeBasicEncoding(encodedValue(userName+":"+key)).length);
+               assertEquals(0, PolicyUtils.decodeBasicEncoding(null).length);
+       }
+       
+       @Test
+       public void testSpecialCharValidator(){
+               assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("$TEST_"));
+               assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("$TEST _"));
+               assertEquals(ERROR, PolicyUtils.policySpecialCharValidator(""));
+               assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("TæST"));
+               assertEquals(SUCCESS, PolicyUtils.policySpecialCharValidator("TEST"));
+       }
+       
+       @Test
+       public void testSpecialCharWithSpaceValidator(){
+               assertEquals(ERROR, PolicyUtils.policySpecialCharWithSpaceValidator(""));
+               assertEquals(ERROR, PolicyUtils.policySpecialCharWithSpaceValidator("$TEST _"));
+               assertEquals(SUCCESS, PolicyUtils.policySpecialCharWithSpaceValidator("TE ST"));
+       }
+       
+       @Test
+       public void testDescription() {
+               assertEquals(SUCCESS, PolicyUtils.descriptionValidator("Test"));
+               assertNotEquals(SUCCESS, PolicyUtils.descriptionValidator("@ModifiedBy:TesterB"));
+               assertNotEquals(SUCCESS, PolicyUtils.descriptionValidator("@CreatedBy:TesterA"));
+       }
+       
+       @Test
+       public void testNonAscii(){
+               assertTrue(PolicyUtils.containsNonAsciiEmptyChars(null));
+               assertTrue(PolicyUtils.containsNonAsciiEmptyChars(""));
+               assertTrue(PolicyUtils.containsNonAsciiEmptyChars("T æST"));
+               assertTrue(PolicyUtils.containsNonAsciiEmptyChars("TæST"));
+               assertFalse(PolicyUtils.containsNonAsciiEmptyChars("TEST"));
+       }
+       
+       @Test
+       public void testInteger(){
+           assertFalse(PolicyUtils.isInteger(null));
+               assertTrue(PolicyUtils.isInteger("123"));
+               assertFalse(PolicyUtils.isInteger("1a23"));
+       }
+       
+       @Test
+       public void testEmailAddress(){
+               assertEquals(SUCCESS, PolicyUtils.validateEmailAddress("test@onap.org"));
+               assertNotEquals(SUCCESS, PolicyUtils.validateEmailAddress("test@onap"));
+       }
+       
+       @Test
+       public void testBRMSValidate(){
+           String rule = "package com.sample;\n"
+                   + "import com.sample.DroolsTest.Message;\n"
+                   + "declare Params\n"
+                   + "samPoll : int\n"
+                   + "value : String\n"
+                   + "end\n"
+                   + "///This Rule will be generated by the UI.\n"
+                   + "rule \"Create parameters structure\"\n"
+                   + "salience 1000  \n"
+                   + "when\n"
+                   + "then\n"
+                   + "Params params = new Params();\n"
+                   + "params.setSamPoll(76);\n"
+                   + "params.setValue(\"test\");\n"
+                   + "insertLogical(params);\n"
+                   + "end\n"
+                   + "rule \"Rule 1: Check parameter structure access from when/then\"\n"
+                   + "when\n"
+                   + "$param: Params()\n"
+                   + "Params($param.samPoll > 50)\n"
+                   + "then\n"
+                   + "System.out.println(\"Firing rule 1\");\n"
+                   + "System.out.println($param);\n"
+                   + "end\n";
+           assertEquals(PolicyUtils.brmsRawValidate(rule),"");
+           assertTrue(PolicyUtils.brmsRawValidate("error").contains("[ERR"));
+        assertFalse(PolicyUtils.brmsRawValidate("package com.att.ecomp.policy.controlloop.p_${unique};").contains("[ERR"));
+       }
+       
+       @Test
+       public void testiIsJsonValid(){
+           assertTrue(PolicyUtils.isJSONValid("{\"test\":\"test\"}"));
+           String value = "{\"test\":\"test\", \"t1\": {\"test\": 12 , \"t2\":\"34\"},\"t2\":[{\"test\":\"val\"}]}";
+           assertTrue(PolicyUtils.isJSONValid(value));
+           assertFalse(PolicyUtils.isJSONValid("{\"test\":\"test"));
+       }
+       
+       @Test
+       public void testIsXMLValid() throws SAXException{
+           XMLErrorHandler error = new XMLErrorHandler();
+        error.error(new SAXParseException(null, null));
+        error.warning(new SAXParseException(null, null));
+           assertTrue(PolicyUtils.isXMLValid("<test>123</test>"));
+           assertFalse(PolicyUtils.isXMLValid("<test>123</test"));
+       }
+       
+       @Test
+       public void testIsPropValid(){
+        assertTrue(PolicyUtils.isPropValid("test=123\n\tval=123"));
+        assertFalse(PolicyUtils.isPropValid("test"));
+        assertFalse(PolicyUtils.isPropValid("test="));
+        assertTrue(PolicyUtils.isPropValid("#test\n\nval=123"));
+       }
+       
+       @Test
+       public void testVersionStringToArray(){
+           assertTrue(PolicyUtils.versionStringToArray(null).length==0);
+           assertTrue(PolicyUtils.versionStringToArray("").length==0);
+           assertTrue(PolicyUtils.versionStringToArray("1.2.3").length==3);
+       }
+}
\ No newline at end of file
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/testBackUpMonitor.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/testBackUpMonitor.java
new file mode 100644 (file)
index 0000000..afc3d0d
--- /dev/null
@@ -0,0 +1,292 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PolicyEngineUtils
+ * ================================================================================
+ * Copyright (C) 2017 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.utils.test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+import javax.persistence.PersistenceException;
+import javax.persistence.Query;
+
+import org.eclipse.persistence.config.PersistenceUnitProperties;
+import org.junit.After;
+import org.junit.Test;
+import org.onap.policy.api.NotificationType;
+import org.onap.policy.api.UpdateType;
+import org.onap.policy.jpa.BackUpMonitorEntity;
+import org.onap.policy.std.NotificationStore;
+import org.onap.policy.std.StdLoadedPolicy;
+import org.onap.policy.std.StdPDPNotification;
+import org.onap.policy.std.StdRemovedPolicy;
+import org.onap.policy.utils.BackUpMonitor;
+import org.onap.policy.utils.BackUpMonitor.ResourceNode;
+import org.onap.policy.utils.BackUpMonitorException;
+import org.onap.policy.utils.PolicyUtils;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+
+
+public class testBackUpMonitor {
+
+       @Test (expected = PersistenceException.class)
+       public void backUpMonitorTestFail() throws Exception{
+               Properties properties = new Properties();
+               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
+               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
+               properties.setProperty("javax.persistence.jdbc.user", "policy_user");
+               properties.setProperty("javax.persistence.jdbc.password", "");
+               BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
+       }
+       
+       @Test
+       public void backUpMonitorTestFailNoUser() throws Exception{
+               Properties properties = new Properties();
+               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
+               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
+               properties.setProperty("javax.persistence.jdbc.user", "");
+               properties.setProperty("javax.persistence.jdbc.password", "password");
+               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
+               assertNull(bum);
+       }
+       
+       @Test
+       public void backUpMonitorTestFailNoURL() throws Exception{
+               Properties properties = new Properties();
+               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
+               properties.setProperty("javax.persistence.jdbc.url", "");
+               properties.setProperty("javax.persistence.jdbc.user", "test");
+               properties.setProperty("javax.persistence.jdbc.password", "password");
+               properties.setProperty("ping_interval", "500");
+               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
+               assertNull(bum);
+       }
+       
+       @Test
+       public void backUpMonitorTestFailNoDriver() throws Exception{
+               Properties properties = new Properties();
+               properties.setProperty("javax.persistence.jdbc.driver", "");
+               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
+               properties.setProperty("javax.persistence.jdbc.user", "test");
+               properties.setProperty("javax.persistence.jdbc.password", "password");
+               properties.setProperty("ping_interval", "500");
+               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
+               assertNull(bum);
+       }
+       
+       @Test
+       public void backUpMonitorTestFailNoNode() throws Exception{
+               Properties properties = new Properties();
+               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
+               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
+               properties.setProperty("javax.persistence.jdbc.user", "test");
+               properties.setProperty("javax.persistence.jdbc.password", "password");
+               properties.setProperty("ping_interval", "");
+               BackUpMonitor bum = BackUpMonitor.getInstance(null, "brms_test" , properties, new Handler());
+               assertNull(bum);
+       }
+       
+       @Test
+       public void backUpMonitorTestFailNoResource() throws Exception{
+               Properties properties = new Properties();
+               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
+               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
+               properties.setProperty("javax.persistence.jdbc.user", "test");
+               properties.setProperty("javax.persistence.jdbc.password", "password");
+               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), null , properties, new Handler());
+               assertNull(bum);
+       }
+       
+       @Test
+       public void backUpMonitorTestFailNoProperties() throws Exception{
+               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , null, new Handler());
+               assertNull(bum);
+       }
+       
+       @Test
+       public void backUpMonitorTestFailNoHandler() throws Exception{
+               Properties properties = new Properties();
+               properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
+               properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml");
+               properties.setProperty("javax.persistence.jdbc.user", "test");
+               properties.setProperty("javax.persistence.jdbc.password", "password");
+               properties.setProperty("ping_interval", "500");
+               BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, null);
+               assertNull(bum);
+       }
+       
+       @Test
+       public void backUpMonitorPingError() throws BackUpMonitorException {
+           Properties properties = new Properties();
+           properties.setProperty("javax.persistence.jdbc.driver", "org.h2.Driver");
+        properties.setProperty("javax.persistence.jdbc.url", "jdbc:h2:file:./sql/xacmlTest");
+        properties.setProperty("javax.persistence.jdbc.user", "sa");
+        properties.setProperty("javax.persistence.jdbc.password", "");
+        properties.setProperty("ping_interval", "123a");
+        properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePUtest.xml");
+        BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
+        assertTrue(bum.getFlag());
+       }
+       
+       @Test
+       public void backUpMonitorMasterTest() throws BackUpMonitorException, InterruptedException, JsonProcessingException {
+           Properties properties = new Properties();
+           // Master Check. Initial Run. 
+           properties.setProperty("javax.persistence.jdbc.driver", "org.h2.Driver");
+        properties.setProperty("javax.persistence.jdbc.url", "jdbc:h2:file:./sql/xacmlTest");
+        properties.setProperty("javax.persistence.jdbc.user", "sa");
+        properties.setProperty("javax.persistence.jdbc.password", "");
+        properties.setProperty("ping_interval", "500");
+        properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePUtest.xml");
+        BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler());
+        createPolicyNotification();
+        assertTrue(bum.getFlag());
+        // Start a slave check.
+        startSlave(properties);
+        updatePolicyNotification();
+        TimeUnit.MILLISECONDS.sleep(1500);
+        assertFalse(bum.getFlag());
+        // Get Back to Master test
+        TimeUnit.MILLISECONDS.sleep(2000);
+        assertTrue(bum.getFlag());
+        // No Master check. 
+        changeALL(properties, "SLAVE");
+        TimeUnit.MILLISECONDS.sleep(2000);
+        assertTrue(bum.getFlag());
+        // No Master check. 
+        changeALL(properties, "MASTER");
+        TimeUnit.MILLISECONDS.sleep(2000);
+        assertTrue(bum.getFlag());
+        
+       }
+       
+       private void updatePolicyNotification() {
+           StdPDPNotification notification = new StdPDPNotification();
+        notification.setNotificationType(NotificationType.BOTH);
+        List<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
+        StdLoadedPolicy loadedPolicy = new StdLoadedPolicy();
+        loadedPolicy.setPolicyName("com.testing");
+        loadedPolicy.setUpdateType(UpdateType.UPDATE);
+        loadedPolicy.setVersionNo("2");
+        Map<String, String> matches = new HashMap<>();
+        matches.put("test", "test");
+        loadedPolicy.setMatches(matches);
+        loadedPolicies.add(loadedPolicy);
+        notification.setLoadedPolicies(loadedPolicies);
+        List<StdRemovedPolicy> removedPolicies = new ArrayList<>();
+        StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
+        removedPolicy.setPolicyName("com.testing");
+        removedPolicy.setVersionNo("1");
+        notification.setRemovedPolicies(removedPolicies);
+        NotificationStore.recordNotification(notification);
+    }
+
+    private void createPolicyNotification() {
+        StdPDPNotification notification = new StdPDPNotification();
+        notification.setNotificationType(NotificationType.UPDATE);
+        List<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
+        StdLoadedPolicy loadedPolicy = new StdLoadedPolicy();
+        loadedPolicy.setPolicyName("com.testing");
+        loadedPolicy.setUpdateType(UpdateType.NEW);
+        loadedPolicy.setVersionNo("1");
+        Map<String, String> matches = new HashMap<>();
+        matches.put("test", "test");
+        loadedPolicy.setMatches(matches);
+        loadedPolicies.add(loadedPolicy);
+        notification.setLoadedPolicies(loadedPolicies);
+        NotificationStore.recordNotification(notification);
+    }
+
+    private void changeALL(Properties properties, String flag) {
+           EntityManager em = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties).createEntityManager();
+        EntityTransaction et = em.getTransaction();
+        et.begin();
+        Query query = em.createQuery("select b from BackUpMonitorEntity b where b.resourceNodeName = :nn");
+        query.setParameter("nn", ResourceNode.BRMS.toString());
+        for(Object bMValue: query.getResultList()){
+            BackUpMonitorEntity bmEntity = (BackUpMonitorEntity) bMValue;
+            bmEntity.setFlag(flag);
+            bmEntity.setTimeStamp(new Date());
+        }
+        em.flush();
+        et.commit();
+    }
+
+    private void startSlave(Properties properties) throws JsonProcessingException {
+           EntityManager em = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties).createEntityManager();
+           EntityTransaction et = em.getTransaction();
+           et.begin();
+           Query query = em.createQuery("select b from BackUpMonitorEntity b where b.resourceNodeName = :nn");
+           query.setParameter("nn", ResourceNode.BRMS.toString());
+           List<?> bMList = query.getResultList();
+           BackUpMonitorEntity origBM = (BackUpMonitorEntity) bMList.get(0);
+           origBM.setFlag("SLAVE");
+           origBM.setTimeStamp(new Date());
+           BackUpMonitorEntity bMEntity = new BackUpMonitorEntity();
+        bMEntity.setResoruceNodeName(ResourceNode.BRMS.toString());
+        bMEntity.setResourceName("brms_test2");
+        bMEntity.setFlag("MASTER");
+        bMEntity.setTimeStamp(new Date());        
+        StdPDPNotification notification = new StdPDPNotification();
+        notification.setNotificationType(NotificationType.UPDATE);
+        List<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
+        StdLoadedPolicy loadedPolicy = new StdLoadedPolicy();
+        loadedPolicy.setPolicyName("com.test");
+        loadedPolicy.setUpdateType(UpdateType.NEW);
+        loadedPolicy.setVersionNo("1");
+        Map<String, String> matches = new HashMap<>();
+        matches.put("test", "test");
+        loadedPolicy.setMatches(matches);
+        loadedPolicies.add(loadedPolicy);
+        notification.setLoadedPolicies(loadedPolicies);
+        bMEntity.setNotificationRecord(PolicyUtils.objectToJsonString(notification));
+        em.persist(bMEntity);
+        em.persist(origBM);
+        em.flush();
+        et.commit();
+    }
+    
+    @Test(expected = BackUpMonitorException.class)
+    public void testException() throws InterruptedException, BackUpMonitorException{
+        BackUpMonitor.stop();
+        new BackUpMonitorException();
+        new BackUpMonitorException(new Exception());
+        new BackUpMonitorException("error");
+        new BackUpMonitorException("error", new Exception());
+        throw new BackUpMonitorException("error", new Exception(), false, false);
+    }
+
+    @After
+       public void setup() throws InterruptedException{
+           BackUpMonitor.stop();
+       }
+}
diff --git a/PolicyEngineUtils/src/test/resources/META-INF/drop.ddl b/PolicyEngineUtils/src/test/resources/META-INF/drop.ddl
new file mode 100644 (file)
index 0000000..345f258
--- /dev/null
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS BackUpMonitorEntity
\ No newline at end of file
diff --git a/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml b/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml
new file mode 100644 (file)
index 0000000..a73e6b3
--- /dev/null
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- ============LICENSE_START======================================================= 
+       PolicyEngineUtils ================================================================================ 
+       Copyright (C) 2017 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========================================================= -->
+
+<persistence version="2.1"
+       xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
+       <persistence-unit name="PolicyEngineUtils"
+               transaction-type="RESOURCE_LOCAL">
+               <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+               <class>org.onap.policy.jpa.BackUpMonitorEntity</class>
+               <property name="javax.persistence.schema-generation.scripts.action"
+                       value="drop-and-create" />
+               <property name="javax.persistence.schema-generation.scripts.create-target"
+                       value="./src/test/resources/META-INF/generatedCreate.ddl" />
+               <property name="javax.persistence.schema-generation.scripts.drop-target"
+                       value="./src/test/resources/META-INF/generatedDrop.ddl" />
+               <property name="javax.persistence.schema-generation.database.action"
+                       value="drop-and-create" />
+               <property name="javax.persistence.schema-generation.create-source"
+                       value="metadata-then-script" />
+               <property name="javax.persistence.schema-generation.drop-source"
+                       value="script" />
+               <property name="javax.persistence.schema-generation.drop-script-source"
+                       value="META-INF/drop.ddl" />
+       </persistence-unit>
+</persistence>
index ac7a5bb..c9a73f6 100644 (file)
@@ -108,6 +108,8 @@ xacml.rest.pap.userid=${{PDP_PAP_PDP_HTTP_USER_ID}}
 xacml.rest.pap.password=${{PDP_PAP_PDP_HTTP_PASSWORD}}
 # Delay for Notifications Don't change this. Value in milliSec.  
 xacml.rest.notification.delay=30  
+# Client interval to ping notification service. 
+CLIENT_INTERVAL=15000
 # Request Buffer Size. 
 REQUEST_BUFFER_SIZE=5
 #***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java***