X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=ONAP-REST%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fpolicy%2Frest%2Futil%2FPolicyValidation.java;h=2e685d423027146510961342de682e22ae7dbc91;hb=a65d684a684105c39a64181bbd44f1debb80fb06;hp=e98a41f9e0fcd68bd05558f9db8847d53f17d504;hpb=989ae85e3a25e059cb963a9bc293526be51273ca;p=policy%2Fengine.git diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java index e98a41f9e..2e685d423 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -20,6 +20,8 @@ package org.onap.policy.rest.util; import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; @@ -27,6 +29,12 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import javax.json.Json; +import javax.json.JsonException; +import javax.json.JsonObject; +import javax.json.JsonReader; +import javax.json.JsonValue; + import org.apache.commons.lang.StringUtils; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -36,6 +44,7 @@ import org.onap.policy.rest.adapter.ClosedLoopPMBody; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.SafePolicyWarning; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -57,14 +66,23 @@ public class PolicyValidation { public static final String DECISION_POLICY = "Decision"; public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault"; public static final String CLOSEDLOOP_PM = "ClosedLoop_PM"; - public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config"; - public static final String MICROSERVICES="Micro Service"; - public static final String FIREWALL="Firewall Config"; + public static final String ENFORCER_CONFIG_POLICY = "Enforcer Config"; + public static final String MICROSERVICES = "Micro Service"; + public static final String FIREWALL = "Firewall Config"; + public static final String OPTIMIZATION="Optimization"; + public static final String BRMSPARAM = "BRMS_Param"; + public static final String BRMSRAW = "BRMS_Raw"; public static final String HTML_ITALICS_LNBREAK = "
"; public static final String SUCCESS = "success"; public static final String EMPTY_COMPONENT_ATTR = "Component Attributes: One or more Fields in Component Attributes is Empty."; + public static final String ISREQUIRED = " is required"; + public static final String SPACESINVALIDCHARS = " : value has spaces or invalid characters
"; + public static final String RULEALGORITHMS = "Rule Algorithms:"; + public static final String VALUE = "value"; private static Map mapAttribute = new HashMap<>(); + private static Map jsonRequestMap = new HashMap<>(); + private static List modelRequiredFieldsList = new ArrayList<>(); private static CommonClassDao commonClassDao; @@ -76,7 +94,9 @@ public class PolicyValidation { /* * This is an empty constructor */ - public PolicyValidation(){} + public PolicyValidation(){ + // Empty constructor + } public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException{ @@ -88,34 +108,139 @@ public class PolicyValidation { if(policyData.getPolicyName() != null){ String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName()); if(!policyNameValidate.contains(SUCCESS)){ - responseString.append("PolicyName:" + policyNameValidate + "
"); + responseString.append("PolicyName:" + policyNameValidate + HTML_ITALICS_LNBREAK); valid = false; - }; + } }else{ - responseString.append( "PolicyName: PolicyName Should not be empty" + "
"); + responseString.append( "PolicyName: PolicyName Should not be empty" + HTML_ITALICS_LNBREAK); valid = false; } if(policyData.getPolicyDescription() != null){ String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription()); if(!descriptionValidate.contains(SUCCESS)){ - responseString.append("Description:" + descriptionValidate + "
"); + responseString.append("Description:" + descriptionValidate + HTML_ITALICS_LNBREAK); valid = false; } } + if(!"API".equals(policyData.getApiflag()) && policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String value = null; + String key = null; + if(((LinkedHashMap) attribute).get("key") != null){ + key = ((LinkedHashMap) attribute).get("key").toString(); + if(!PolicyUtils.policySpecialCharValidator(key).contains(SUCCESS)){ + responseString.append("Attributes or Component Attributes:" + value + SPACESINVALIDCHARS); + valid = false; + } + }else{ + if(CONFIG_POLICY.equals(policyData.getPolicyType())){ + if("Base".equals(policyData.getConfigPolicyType())){ + responseString.append("Attributes: has one missing Attribute key
"); + } + if(BRMSPARAM.equals(policyData.getConfigPolicyType()) || BRMSRAW.equals(policyData.getConfigPolicyType())){ + responseString.append("Rule Attributes: has one missing Attribute key
"); + } + }else{ + responseString.append("Component Attributes: has one missing Component Attribute key
"); + } + valid = false; + } + if(((LinkedHashMap) attribute).get(VALUE) != null){ + value = ((LinkedHashMap) attribute).get(VALUE).toString(); + if(!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)){ + if(CONFIG_POLICY.equals(policyData.getPolicyType())){ + if("Base".equals(policyData.getConfigPolicyType())){ + responseString.append("Attributes:" + value + SPACESINVALIDCHARS); + } + if(BRMSPARAM.equals(policyData.getConfigPolicyType()) || BRMSRAW.equals(policyData.getConfigPolicyType())){ + responseString.append("Rule Attributes:" + value + SPACESINVALIDCHARS); + } + }else{ + responseString.append("Component Attributes:" + value + SPACESINVALIDCHARS); + } + valid = false; + } + }else{ + if(CONFIG_POLICY.equals(policyData.getPolicyType())){ + if("Base".equals(policyData.getConfigPolicyType())){ + responseString.append("Attributes: has one missing Attribute value
"); + } + if(BRMSPARAM.equals(policyData.getConfigPolicyType()) || BRMSRAW.equals(policyData.getConfigPolicyType())){ + responseString.append("Rule Attributes: has one missing Attribute value
"); + } + }else{ + responseString.append("Component Attributes: has one missing Component Attribute value
"); + } + valid = false; + } + } + } + } + + //Decision Policy Attributes Validation + if(!"API".equals(policyData.getApiflag()) && policyData.getSettings() != null && !policyData.getSettings().isEmpty()){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String value = null; + if(((LinkedHashMap) attribute).get("key") == null){ + responseString.append("Settings Attributes: has one missing Attribute key
"); + valid = false; + } + if(((LinkedHashMap) attribute).get(VALUE) != null){ + value = ((LinkedHashMap) attribute).get(VALUE).toString(); + if(!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)){ + responseString.append("Settings Attributes:" + value + SPACESINVALIDCHARS); + valid = false; + } + }else{ + responseString.append("Settings Attributes: has one missing Attribute Value
"); + valid = false; + } + } + } + } + + if(!"API".equals(policyData.getApiflag()) && policyData.getRuleAlgorithmschoices() != null && !policyData.getRuleAlgorithmschoices().isEmpty()){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap){ + String label = ((LinkedHashMap) attribute).get("id").toString(); + if(((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1") == null){ + responseString.append(RULEALGORITHMS + label + " : Field 1 value is not selected

"); + valid = false; + } + if(((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo") == null){ + responseString.append(RULEALGORITHMS + label + " : Field 2 value is not selected

"); + valid = false; + } + if(((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2") != null){ + String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); + if(!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)){ + responseString.append(RULEALGORITHMS + label + " : Field 3 value has special characters

"); + valid = false; + } + }else{ + responseString.append(RULEALGORITHMS + label + " : Field 3 value is empty

"); + valid = false; + } + } + } + } + if(CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())){ if ("Base".equals(policyData.getConfigPolicyType()) || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType()) || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType()) || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType()) - || MICROSERVICES.equals(policyData.getConfigPolicyType())) { + || MICROSERVICES.equals(policyData.getConfigPolicyType()) || OPTIMIZATION.equals(policyData.getConfigPolicyType())) { if(!Strings.isNullOrEmpty(policyData.getOnapName())) { String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName()); if(!onapNameValidate.contains(SUCCESS)){ - responseString.append("OnapName:" + onapNameValidate + "
"); + responseString.append("OnapName:" + onapNameValidate + HTML_ITALICS_LNBREAK); valid = false; } }else{ - responseString.append("Onap Name: Onap Name Should not be empty" + "
"); + responseString.append("Onap Name: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK); valid = false; } } @@ -123,87 +248,89 @@ public class PolicyValidation { if(!Strings.isNullOrEmpty(policyData.getRiskType())) { String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType()); if(!riskTypeValidate.contains(SUCCESS)){ - responseString.append("RiskType:" + riskTypeValidate + "
"); + responseString.append("RiskType:" + riskTypeValidate + HTML_ITALICS_LNBREAK); valid = false; } }else { - responseString.append("Risk Type: Risk Type Should not be Empty" + "
"); + responseString.append("RiskType: Risk Type Should not be Empty" + HTML_ITALICS_LNBREAK); valid = false; } if(!Strings.isNullOrEmpty(policyData.getRiskLevel())) { String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel()); if(!validateRiskLevel.contains(SUCCESS)){ - responseString.append("RiskLevel:" + validateRiskLevel + "
"); + responseString.append("RiskLevel:" + validateRiskLevel + HTML_ITALICS_LNBREAK); valid = false; } }else { - responseString.append("Risk Level: Risk Level Should not be Empty" + "
"); + responseString.append("RiskLevel: Risk Level Should not be Empty" + HTML_ITALICS_LNBREAK); valid = false; } if(!Strings.isNullOrEmpty(policyData.getGuard())) { String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard()); if(!validateGuard.contains(SUCCESS)){ - responseString.append("Guard:" + validateGuard + "
"); + responseString.append("Guard:" + validateGuard + HTML_ITALICS_LNBREAK); valid = false; } }else { - responseString.append("Guard: Guard Value Should not be Empty" + "
"); + responseString.append("Guard: Guard Value Should not be Empty" + HTML_ITALICS_LNBREAK); valid = false; } - + + // Validate Config Base Policy Data if("Base".equalsIgnoreCase(policyData.getConfigPolicyType())){ if(!Strings.isNullOrEmpty(policyData.getConfigName())) { String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName()); if(!configNameValidate.contains(SUCCESS)){ - responseString.append("ConfigName:" + configNameValidate + "
"); + responseString.append("ConfigName:" + configNameValidate + HTML_ITALICS_LNBREAK); valid = false; } }else{ - responseString.append("Config Name: Config Name Should not be Empty" + "
"); + responseString.append("Config Name: Config Name Should not be Empty" + HTML_ITALICS_LNBREAK); valid = false; } if(!Strings.isNullOrEmpty(policyData.getConfigType())) { String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType()); if(!configTypeValidate.contains(SUCCESS)){ - responseString.append("ConfigType:" + configTypeValidate + "
"); + responseString.append("ConfigType:" + configTypeValidate + HTML_ITALICS_LNBREAK); valid = false; } }else{ - responseString.append("Config Type: Config Type Should not be Empty" + "
"); + responseString.append("Config Type: Config Type Should not be Empty" + HTML_ITALICS_LNBREAK); valid = false; } if(!Strings.isNullOrEmpty(policyData.getConfigBodyData())) { String configBodyData = policyData.getConfigBodyData(); String configType = policyData.getConfigType(); if (configType != null) { - if (configType.equals("JSON")) { + if ("JSON".equals(configType)) { if (!PolicyUtils.isJSONValid(configBodyData)) { - responseString.append("Config Body: JSON Content is not valid" + "
"); + responseString.append("Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK); valid = false; } - } else if (configType.equals("XML")) { + } else if ("XML".equals(configType)) { if (!PolicyUtils.isXMLValid(configBodyData)) { - responseString.append("Config Body: XML Content data is not valid" + "
"); + responseString.append("Config Body: XML Content data is not valid" + HTML_ITALICS_LNBREAK); valid = false; } - } else if (configType.equals("PROPERTIES")) { - if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) { - responseString.append("Config Body: Property data is not valid" + "
"); + } else if ("PROPERTIES".equals(configType)) { + if (!PolicyUtils.isPropValid(configBodyData) || "".equals(configBodyData)) { + responseString.append("Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK); valid = false; } } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) { - responseString.append("Config Body: Config Body Should not be Empty" + "
"); + responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK); valid = false; } } }else{ - responseString.append("Config Body: Config Body Should not be Empty" + "
"); + responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK); valid = false; } } - + + // Validate Config Firewall Policy Data if(FIREWALL.equalsIgnoreCase(policyData.getConfigPolicyType())){ if(policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()){ String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName()); @@ -220,11 +347,15 @@ public class PolicyValidation { valid = false; } } - if("BRMS_Param".equalsIgnoreCase(policyData.getConfigPolicyType()) && Strings.isNullOrEmpty(policyData.getRuleName())){ + + // Validate BRMS_Param Policy Data + if(BRMSPARAM.equalsIgnoreCase(policyData.getConfigPolicyType()) && Strings.isNullOrEmpty(policyData.getRuleName())){ responseString.append("BRMS Template:BRMS Template is required" + HTML_ITALICS_LNBREAK); valid = false; } - if("BRMS_Raw".equalsIgnoreCase(policyData.getConfigPolicyType())){ + + // Validate BRMS_Raw Policy Data + if(BRMSRAW.equalsIgnoreCase(policyData.getConfigPolicyType())){ if(policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()){ String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData()); @@ -238,6 +369,8 @@ public class PolicyValidation { valid = false; } } + + // Validate ClosedLoop_PM Policy Data if(CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())){ try{ if(Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())){ @@ -257,7 +390,7 @@ public class PolicyValidation { if(pmBody.getEmailAddress() != null){ String result = emailValidation(pmBody.getEmailAddress(), responseString.toString()); if(result != SUCCESS){ - responseString.append(result + "
"); + responseString.append(result + HTML_ITALICS_LNBREAK); valid = false; } } @@ -270,7 +403,7 @@ public class PolicyValidation { if(!result.contains(SUCCESS)){ responseString.append("GeoLink:" + result + HTML_ITALICS_LNBREAK); valid = false; - }; + } } if(pmBody.getAttributes() != null && !pmBody.getAttributes().isEmpty()){ for(Entry entry : pmBody.getAttributes().entrySet()){ @@ -281,7 +414,7 @@ public class PolicyValidation { if(!attributeValidate.contains(SUCCESS)){ responseString.append("Attributes:" + key + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK); valid = false; - }; + } } } } @@ -290,6 +423,8 @@ public class PolicyValidation { valid = false; } } + + // Validate ClosedLoop_Fault Policy Data if(CLOSEDLOOP_POLICY.equalsIgnoreCase(policyData.getConfigPolicyType())){ if(policyData.getJsonBody() != null){ @@ -306,13 +441,28 @@ public class PolicyValidation { responseString.append("Conditions: There were no conditions provided in configBody json" + HTML_ITALICS_LNBREAK); return responseString; } + }else{ + if(policyData.getTrapDatas().getTrap1() != null){ + if(policyData.getClearTimeOut() == null){ + responseString.append("Trigger Clear TimeOut: Trigger Clear TimeOut is required when atleast One Trigger Signature is enabled
"); + valid = false; + } + if(policyData.getTrapMaxAge() == null){ + responseString.append("Trap Max Age: Trap Max Age is required when atleast One Trigger Signature is enabled
"); + valid = false; + } + } + if(policyData.getFaultDatas().getTrap1() != null && policyData.getVerificationclearTimeOut() == null){ + responseString.append("Fault Clear TimeOut: Fault Clear TimeOut is required when atleast One Fault Signature is enabled
"); + valid = false; + } } ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class); if(faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()){ String result = emailValidation(faultBody.getEmailAddress(), responseString.toString()); - if(result != SUCCESS){ - responseString.append(result+ "
"); + if(!SUCCESS.equals(result)){ + responseString.append(result+ HTML_ITALICS_LNBREAK); valid = false; } } @@ -379,13 +529,17 @@ public class PolicyValidation { valid = false; } } - + + // Validate MicroServices Policy Data if (MICROSERVICES.equals(policyData.getConfigPolicyType())){ + if(!Strings.isNullOrEmpty(policyData.getServiceType())){ + + modelRequiredFieldsList.clear(); pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON()); - String service = null; - String version = null; + String service; + String version; if (policyData.getServiceType().contains("-v")){ service = policyData.getServiceType().split("-v")[0]; version = policyData.getServiceType().split("-v")[1]; @@ -395,10 +549,15 @@ public class PolicyValidation { } if(!Strings.isNullOrEmpty(version)) { - MicroServiceModels returnModel = getAttributeObject(service, version); + MicroServiceModels returnModel = getMSModelData(service, version); if(returnModel != null) { + String annotation = returnModel.getAnnotation(); + String refAttributes = returnModel.getRef_attributes(); + String subAttributes = returnModel.getSub_attributes(); + String modelAttributes = returnModel.getAttributes(); + if (!Strings.isNullOrEmpty(annotation)){ Map rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation); for (Entry rMap : rangeMap.entrySet()){ @@ -429,18 +588,236 @@ public class PolicyValidation { } } + } else { + // Validate for configName, location, uuid, and policyScope if no annotations exist for this model + if(Strings.isNullOrEmpty(policyData.getLocation())){ + responseString.append("Micro Service Model: location is required for this model" + HTML_ITALICS_LNBREAK); + valid = false; + } + + if(Strings.isNullOrEmpty(policyData.getConfigName())){ + responseString.append("Micro Service Model: configName is required for this model" + HTML_ITALICS_LNBREAK); + valid = false; + } + + if(Strings.isNullOrEmpty(policyData.getUuid())){ + responseString.append("Micro Service Model: uuid is required for this model" + HTML_ITALICS_LNBREAK); + valid = false; + } + + if(Strings.isNullOrEmpty(policyData.getPolicyScope())){ + responseString.append("Micro Service Model: policyScope is required for this model" + HTML_ITALICS_LNBREAK); + valid = false; + } } + + // If request comes from the API we need to validate required fields in the Micro Service Model + // GUI request are already validated from the SDK-APP + if("API".equals(policyData.getApiflag())){ + // get list of required fields from the sub_Attributes of the Model + if(!Strings.isNullOrEmpty(subAttributes)) { + JsonObject subAttributesJson = stringToJsonObject(subAttributes); + findRequiredFields(subAttributesJson); + } + + // get list of required fields from the attributes of the Model + if (!Strings.isNullOrEmpty(modelAttributes)) { + Map modelAttributesMap = null; + if (",".equals(modelAttributes.substring(modelAttributes.length()-1))) { + String attributeString = modelAttributes.substring(0, modelAttributes.length()-1); + modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributeString); + } else { + modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes); + } + String json = new ObjectMapper().writeValueAsString(modelAttributesMap); + findRequiredFields(stringToJsonObject(json)); + } + + // get list of required fields from the ref_Attributes of the Model + if (!Strings.isNullOrEmpty(refAttributes)) { + Map refAttributesMap = null; + if (",".equals(refAttributes.substring(refAttributes.length()-1))) { + String attributesString = refAttributes.substring(0, refAttributes.length()-1); + refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributesString); + } else { + refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes); + } + String json = new ObjectMapper().writeValueAsString(refAttributesMap); + findRequiredFields(stringToJsonObject(json)); + } + + if (modelRequiredFieldsList!=null || !modelRequiredFieldsList.isEmpty()) { + // create jsonRequestMap with all json keys and values from request + JsonNode rootNode = (JsonNode) policyData.getPolicyJSON(); + jsonRequestMap.clear(); + pullModelJsonKeyPairs(rootNode); + + // validate if the requiredFields are in the request + for(String requiredField : modelRequiredFieldsList) { + if (jsonRequestMap.containsKey(requiredField)) { + String value = jsonRequestMap.get(requiredField); + if(Strings.isNullOrEmpty(jsonRequestMap.get(requiredField)) || + "\"\"".equals(value) || + "".equals(jsonRequestMap.get(requiredField))){ + responseString.append("Micro Service Model: " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK); + valid = false; + } + } else { + responseString.append("Micro Service Model: " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK); + valid = false; + } + } + } + } } else { responseString.append("Micro Service Model: Invalid Model. The model name, " + service + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK); valid = false; } } else { - responseString.append("Micro Version: Micro Service Version is required" + HTML_ITALICS_LNBREAK); + responseString.append("Micro Service Version: Micro Service Version is required" + HTML_ITALICS_LNBREAK); + valid = false; + } + } else { + responseString.append("Micro Service: Micro Service Model is required" + HTML_ITALICS_LNBREAK); + valid = false; + } + + if(Strings.isNullOrEmpty(policyData.getPriority())){ + responseString.append("Priority: Priority is required" + HTML_ITALICS_LNBREAK); + valid = false; + } + } + + // Validate Optimization Policy Data + if (OPTIMIZATION.equals(policyData.getConfigPolicyType())){ + + if(!Strings.isNullOrEmpty(policyData.getServiceType())){ + + modelRequiredFieldsList.clear(); + pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON()); + + String service; + String version; + if (policyData.getServiceType().contains("-v")){ + service = policyData.getServiceType().split("-v")[0]; + version = policyData.getServiceType().split("-v")[1]; + }else { + service = policyData.getServiceType(); + version = policyData.getVersion(); + } + + if(!Strings.isNullOrEmpty(version)) { + OptimizationModels returnModel = getOptimizationModelData(service, version); + + if(returnModel != null) { + + String annotation = returnModel.getAnnotation(); + String refAttributes = returnModel.getRefattributes(); + String subAttributes = returnModel.getSubattributes(); + String modelAttributes = returnModel.getAttributes(); + + if (!Strings.isNullOrEmpty(annotation)){ + Map rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation); + for (Entry rMap : rangeMap.entrySet()){ + if (rMap.getValue().contains("range::")){ + String value = mapAttribute.get(rMap.getKey().trim()); + String[] tempString = rMap.getValue().split("::")[1].split("-"); + int startNum = Integer.parseInt(tempString[0]); + int endNum = Integer.parseInt(tempString[1]); + String returnString = "InvalidreturnModel Range:" + rMap.getKey() + " must be between " + + startNum + " - " + endNum + ","; + + if(value != null) { + if (PolicyUtils.isInteger(value.replace("\"", ""))){ + int result = Integer.parseInt(value.replace("\"", "")); + if (result < startNum || result > endNum){ + responseString.append(returnString); + valid = false; + } + }else { + responseString.append(returnString); + valid = false; + } + } else { + responseString.append(""+rMap.getKey()+":" + rMap.getKey() + + " is required for the Optimization model " + service + HTML_ITALICS_LNBREAK); + valid = false; + } + + } + } + } + + // If request comes from the API we need to validate required fields in the Micro Service Model + // GUI request are already validated from the SDK-APP + if("API".equals(policyData.getApiflag())){ + // get list of required fields from the sub_Attributes of the Model + if(!Strings.isNullOrEmpty(subAttributes)) { + JsonObject subAttributesJson = stringToJsonObject(subAttributes); + findRequiredFields(subAttributesJson); + } + + // get list of required fields from the attributes of the Model + if (!Strings.isNullOrEmpty(modelAttributes)) { + Map modelAttributesMap = null; + if (",".equals(modelAttributes.substring(modelAttributes.length()-1))) { + String attributeString = modelAttributes.substring(0, modelAttributes.length()-1); + modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributeString); + } else { + modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes); + } + String json = new ObjectMapper().writeValueAsString(modelAttributesMap); + findRequiredFields(stringToJsonObject(json)); + } + + // get list of required fields from the ref_Attributes of the Model + if (!Strings.isNullOrEmpty(refAttributes)) { + Map refAttributesMap = null; + if (",".equals(refAttributes.substring(refAttributes.length()-1))) { + String attributesString = refAttributes.substring(0, refAttributes.length()-1); + refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributesString); + } else { + refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes); + } + String json = new ObjectMapper().writeValueAsString(refAttributesMap); + findRequiredFields(stringToJsonObject(json)); + } + + if (modelRequiredFieldsList!=null || !modelRequiredFieldsList.isEmpty()) { + // create jsonRequestMap with all json keys and values from request + JsonNode rootNode = (JsonNode) policyData.getPolicyJSON(); + jsonRequestMap.clear(); + pullModelJsonKeyPairs(rootNode); + + // validate if the requiredFields are in the request + for(String requiredField : modelRequiredFieldsList) { + if (jsonRequestMap.containsKey(requiredField)) { + String value = jsonRequestMap.get(requiredField); + if(Strings.isNullOrEmpty(jsonRequestMap.get(requiredField)) || + "\"\"".equals(value) || + "".equals(jsonRequestMap.get(requiredField))){ + responseString.append("Optimization Service Model: " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK); + valid = false; + } + } else { + responseString.append("Optimization Service Model: " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK); + valid = false; + } + } + } + } + } else { + responseString.append("Optimization Service Model: Invalid Model. The model name, " + service + + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK); + valid = false; + } + } else { + responseString.append("Optimization Service Version: Optimization Service Version is required" + HTML_ITALICS_LNBREAK); valid = false; } } else { - responseString.append("Micro Service: Micro Service is required" + HTML_ITALICS_LNBREAK); + responseString.append("Optimization Service: Optimization Service Model is required" + HTML_ITALICS_LNBREAK); valid = false; } @@ -454,11 +831,11 @@ public class PolicyValidation { if(!Strings.isNullOrEmpty(policyData.getOnapName())){ String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName()); if(!onapNameValidate.contains(SUCCESS)){ - responseString.append("OnapName:" + onapNameValidate + "
"); + responseString.append("OnapName:" + onapNameValidate + HTML_ITALICS_LNBREAK); valid = false; } }else{ - responseString.append("Onap Name: Onap Name Should not be empty" + "
"); + responseString.append("Onap Name: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK); valid = false; } @@ -525,52 +902,52 @@ public class PolicyValidation { if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){ if(policyData.getYamlparams()==null){ - responseString.append(" Guard Params are Required " + "
"); + responseString.append(" Guard Params are Required " + HTML_ITALICS_LNBREAK); valid = false; }else{ if(Strings.isNullOrEmpty(policyData.getYamlparams().getActor())){ - responseString.append("Guard Params Actor is Required " + "
"); + responseString.append("Guard Params Actor is Required " + HTML_ITALICS_LNBREAK); valid = false; } if(Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())){ - responseString.append("Guard Params Recipe is Required " + "
"); + responseString.append("Guard Params Recipe is Required " + HTML_ITALICS_LNBREAK); valid = false; } if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())){ - responseString.append("Guard Params Guard Active Start is Required " + "
"); + responseString.append("Guard Params Guard Active Start is Required " + HTML_ITALICS_LNBREAK); valid = false; } if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())){ - responseString.append("Guard Params Guard Active End is Required " + "
"); + responseString.append("Guard Params Guard Active End is Required " + HTML_ITALICS_LNBREAK); valid = false; } if("GUARD_YAML".equals(policyData.getRuleProvider())){ if(Strings.isNullOrEmpty(policyData.getYamlparams().getLimit())){ - responseString.append(" Guard Params Limit is Required " + "
"); + responseString.append(" Guard Params Limit is Required " + HTML_ITALICS_LNBREAK); valid = false; }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){ - responseString.append(" Guard Params Limit Should be Integer " + "
"); + responseString.append(" Guard Params Limit Should be Integer " + HTML_ITALICS_LNBREAK); valid = false; } if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())){ - responseString.append("Guard Params Time Window is Required" + "
"); + responseString.append("Guard Params Time Window is Required" + HTML_ITALICS_LNBREAK); valid = false; }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){ - responseString.append(" Guard Params Time Window Should be Integer " + "
"); + responseString.append(" Guard Params Time Window Should be Integer " + HTML_ITALICS_LNBREAK); valid = false; } if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())){ - responseString.append("Guard Params Time Units is Required" + "
"); + responseString.append("Guard Params Time Units is Required" + HTML_ITALICS_LNBREAK); valid = false; } }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){ if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){ - responseString.append(" Guard Params BlackList is Required " + "
"); + responseString.append(" Guard Params BlackList is Required " + HTML_ITALICS_LNBREAK); valid = false; }else{ for(String blackList: policyData.getYamlparams().getBlackList()){ if(blackList==null || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))){ - responseString.append(" Guard Params BlackList Should be valid String" + "
"); + responseString.append(" Guard Params BlackList Should be valid String" + HTML_ITALICS_LNBREAK); valid = false; break; } @@ -585,70 +962,24 @@ public class PolicyValidation { if(!Strings.isNullOrEmpty(policyData.getActionPerformer())){ String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer()); if(!actionPerformer.contains(SUCCESS)){ - responseString.append("ActionPerformer:" + actionPerformer + "
"); + responseString.append("ActionPerformer:" + actionPerformer + HTML_ITALICS_LNBREAK); valid = false; } }else{ - responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "
"); - valid = false; - } - if(policyData.getAttributes() != null){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - try{ - //This is for validation check if the value exists or not - String key = ((LinkedHashMap) attribute).get("key").toString(); - String value = ((LinkedHashMap) attribute).get("value").toString(); - if("".equals(key) || "".equals(value)){ - responseString.append(EMPTY_COMPONENT_ATTR + "
"); - valid = false; - break; - } - }catch(Exception e){ - LOGGER.error("This is a Policy Validation check" +e); - responseString.append(EMPTY_COMPONENT_ATTR + "
"); - valid = false; - break; - } - } - } - }else{ - responseString.append(EMPTY_COMPONENT_ATTR + "
"); + responseString.append("ActionPerformer: ActionPerformer Should not be empty" + HTML_ITALICS_LNBREAK); valid = false; } + if(!Strings.isNullOrEmpty(policyData.getActionAttributeValue())){ String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue()); if(!actionAttribute.contains(SUCCESS)){ - responseString.append("ActionAttribute:" + actionAttribute + "
"); + responseString.append("ActionAttribute:" + actionAttribute + HTML_ITALICS_LNBREAK); valid = false; - }; + } }else{ - responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "
"); + responseString.append("ActionAttribute: ActionAttribute Should not be empty" + HTML_ITALICS_LNBREAK); valid = false; } - - if(!policyData.getRuleAlgorithmschoices().isEmpty()){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap){ - try{ - String label = ((LinkedHashMap) attribute).get("id").toString(); - String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); - - if(Strings.isNullOrEmpty(label) || Strings.isNullOrEmpty(key) || Strings.isNullOrEmpty(rule) || Strings.isNullOrEmpty(value)){ - responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
"); - valid = false; - } - }catch(Exception e){ - LOGGER.error("This is a Policy Validation check" +e); - responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
"); - valid = false; - break; - } - } - } - } } if(CONFIG_POLICY.equals(policyData.getPolicyType())){ @@ -658,7 +989,7 @@ public class PolicyValidation { List spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType()); if (!spData.isEmpty()){ SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0); - value = "Message:" + safePolicyWarningData.getMessage(); + value = "Message:" + safePolicyWarningData.getMessage() +""; } } responseString.append(SUCCESS + "@#"+ value); @@ -678,18 +1009,20 @@ public class PolicyValidation { } protected String emailValidation(String email, String response){ + String res = response; if(email != null){ String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", "")); if(!validateEmail.contains(SUCCESS)){ - response += "Email:" + validateEmail + HTML_ITALICS_LNBREAK; - }else{ + res += "Email:" + validateEmail + HTML_ITALICS_LNBREAK; + } + else { return SUCCESS; } } - return response; + return res; } - private MicroServiceModels getAttributeObject(String name, String version) { + private MicroServiceModels getMSModelData(String name, String version) { MicroServiceModels workingModel = null; try{ List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version); @@ -705,6 +1038,23 @@ public class PolicyValidation { return workingModel; } + + private OptimizationModels getOptimizationModelData(String name, String version) { + OptimizationModels workingModel = null; + try{ + List optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, "modelName:version", name+":"+version); + if(optimizationModelsData != null){ + workingModel = (OptimizationModels) optimizationModelsData.get(0); + } + }catch(Exception e){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + + name + " was not found in the dictionary: "; + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e); + return null; + } + + return workingModel; + } private void pullJsonKeyPairs(JsonNode rootNode) { Iterator> fieldsIterator = rootNode.fields(); @@ -725,5 +1075,60 @@ public class PolicyValidation { } } } + + private void pullModelJsonKeyPairs(JsonNode rootNode) { + Iterator> fieldsIterator = rootNode.fields(); + + while (fieldsIterator.hasNext()) { + Map.Entry field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + + if (value.isContainerNode() && !value.isArray()) { + pullModelJsonKeyPairs(value); // RECURSIVE CALL + } else if (value.isArray()) { + try { + String stringValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]"}, new String[]{"",""}); + ObjectMapper mapper = new ObjectMapper(); + JsonNode newValue = mapper.readTree(stringValue); + pullModelJsonKeyPairs(newValue); + } catch (IOException e) { + LOGGER.info("PolicyValidation: Exception occurred while mapping string to JsonNode " + e); + } + } else { + jsonRequestMap.put(key, value.toString().trim()); + } + } + + } + + private JsonObject stringToJsonObject(String value) { + try(JsonReader jsonReader = Json.createReader(new StringReader(value))){ + return jsonReader.readObject(); + } catch(JsonException| IllegalStateException e){ + LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e); + return null; + } + } + + private void findRequiredFields(JsonObject json) { + + for(Entry keyMap : json.entrySet()){ + Object obj = keyMap.getValue(); + if(obj instanceof JsonObject){ + JsonObject jsonObj = (JsonObject)obj; + for(Entry jsonMap : jsonObj.entrySet()){ + if(jsonMap.getValue().toString().contains("required-true")){ + modelRequiredFieldsList.add(jsonMap.getKey()); + } + } + } else { + if(keyMap.getValue().toString().contains("required-true")){ + modelRequiredFieldsList.add(keyMap.getKey()); + } + } + } + + } }