2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.onap.policy.rest.util;
22 import java.io.IOException;
23 import java.io.StringReader;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.LinkedHashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import javax.json.Json;
33 import javax.json.JsonException;
34 import javax.json.JsonObject;
35 import javax.json.JsonReader;
36 import javax.json.JsonValue;
38 import org.apache.commons.lang.StringUtils;
39 import org.json.JSONObject;
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
43 import org.onap.policy.rest.adapter.ClosedLoopPMBody;
44 import org.onap.policy.rest.adapter.PolicyRestAdapter;
45 import org.onap.policy.rest.dao.CommonClassDao;
46 import org.onap.policy.rest.jpa.MicroServiceModels;
47 import org.onap.policy.rest.jpa.OptimizationModels;
48 import org.onap.policy.rest.jpa.SafePolicyWarning;
49 import org.onap.policy.utils.PolicyUtils;
50 import org.onap.policy.xacml.api.XACMLErrorConstants;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.stereotype.Service;
54 import com.fasterxml.jackson.databind.JsonNode;
55 import com.fasterxml.jackson.databind.ObjectMapper;
56 import com.google.common.base.Splitter;
57 import com.google.common.base.Strings;
60 public class PolicyValidation {
62 private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidation.class);
64 public static final String CONFIG_POLICY = "Config";
65 public static final String ACTION_POLICY = "Action";
66 public static final String DECISION_POLICY = "Decision";
67 public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
68 public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
69 public static final String ENFORCER_CONFIG_POLICY = "Enforcer Config";
70 public static final String MICROSERVICES = "Micro Service";
71 public static final String FIREWALL = "Firewall Config";
72 public static final String OPTIMIZATION="Optimization";
73 public static final String BRMSPARAM = "BRMS_Param";
74 public static final String BRMSRAW = "BRMS_Raw";
75 public static final String HTML_ITALICS_LNBREAK = "</i><br>";
76 public static final String SUCCESS = "success";
77 public static final String EMPTY_COMPONENT_ATTR = "Component Attributes: One or more Fields in Component Attributes is Empty.";
78 public static final String ISREQUIRED = " is required";
79 public static final String SPACESINVALIDCHARS = " : value has spaces or invalid characters</i><br>";
80 public static final String RULEALGORITHMS = "<b>Rule Algorithms</b>:<i>";
81 public static final String VALUE = "value";
83 private static Map<String, String> mapAttribute = new HashMap<>();
84 private static Map<String, String> jsonRequestMap = new HashMap<>();
85 private static List<String> modelRequiredFieldsList = new ArrayList<>();
87 private static CommonClassDao commonClassDao;
90 public PolicyValidation(CommonClassDao commonClassDao){
91 PolicyValidation.commonClassDao = commonClassDao;
95 * This is an empty constructor
97 public PolicyValidation(){
102 public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException{
104 boolean valid = true;
105 StringBuilder responseString = new StringBuilder();
106 ObjectMapper mapper = new ObjectMapper();
108 if(policyData.getPolicyName() != null){
109 String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
110 if(!policyNameValidate.contains(SUCCESS)){
111 responseString.append("<b>PolicyName</b>:<i>" + policyNameValidate + HTML_ITALICS_LNBREAK);
115 responseString.append( "<b>PolicyName</b>: PolicyName Should not be empty" + HTML_ITALICS_LNBREAK);
118 if(policyData.getPolicyDescription() != null){
119 String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
120 if(!descriptionValidate.contains(SUCCESS)){
121 responseString.append("<b>Description</b>:<i>" + descriptionValidate + HTML_ITALICS_LNBREAK);
126 if(!"API".equals(policyData.getApiflag()) && policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()){
127 for(Object attribute : policyData.getAttributes()){
128 if(attribute instanceof LinkedHashMap<?, ?>){
131 if(((LinkedHashMap<?, ?>) attribute).get("key") != null){
132 key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
133 if(!PolicyUtils.policySpecialCharValidator(key).contains(SUCCESS)){
134 responseString.append("<b>Attributes or Component Attributes</b>:<i>" + value + SPACESINVALIDCHARS);
138 if(CONFIG_POLICY.equals(policyData.getPolicyType())){
139 if("Base".equals(policyData.getConfigPolicyType())){
140 responseString.append("<b>Attributes</b>:<i> has one missing Attribute key</i><br>");
142 if(BRMSPARAM.equals(policyData.getConfigPolicyType()) || BRMSRAW.equals(policyData.getConfigPolicyType())){
143 responseString.append("<b>Rule Attributes</b>:<i> has one missing Attribute key</i><br>");
146 responseString.append("<b>Component Attributes</b>:<i> has one missing Component Attribute key</i><br>");
150 if(((LinkedHashMap<?, ?>) attribute).get(VALUE) != null){
151 value = ((LinkedHashMap<?, ?>) attribute).get(VALUE).toString();
152 if(!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)){
153 if(CONFIG_POLICY.equals(policyData.getPolicyType())){
154 if("Base".equals(policyData.getConfigPolicyType())){
155 responseString.append("<b>Attributes</b>:<i>" + value + SPACESINVALIDCHARS);
157 if(BRMSPARAM.equals(policyData.getConfigPolicyType()) || BRMSRAW.equals(policyData.getConfigPolicyType())){
158 responseString.append("<b>Rule Attributes</b>:<i>" + value + SPACESINVALIDCHARS);
161 responseString.append("<b>Component Attributes</b>:<i>" + value + SPACESINVALIDCHARS);
166 if(CONFIG_POLICY.equals(policyData.getPolicyType())){
167 if("Base".equals(policyData.getConfigPolicyType())){
168 responseString.append("<b>Attributes</b>:<i> has one missing Attribute value</i><br>");
170 if(BRMSPARAM.equals(policyData.getConfigPolicyType()) || BRMSRAW.equals(policyData.getConfigPolicyType())){
171 responseString.append("<b>Rule Attributes</b>:<i> has one missing Attribute value</i><br>");
174 responseString.append("<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>");
182 //Decision Policy Attributes Validation
183 if(!"API".equals(policyData.getApiflag()) && policyData.getSettings() != null && !policyData.getSettings().isEmpty()){
184 for(Object attribute : policyData.getAttributes()){
185 if(attribute instanceof LinkedHashMap<?, ?>){
187 if(((LinkedHashMap<?, ?>) attribute).get("key") == null){
188 responseString.append("<b>Settings Attributes</b>:<i> has one missing Attribute key</i><br>");
191 if(((LinkedHashMap<?, ?>) attribute).get(VALUE) != null){
192 value = ((LinkedHashMap<?, ?>) attribute).get(VALUE).toString();
193 if(!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)){
194 responseString.append("<b>Settings Attributes</b>:<i>" + value + SPACESINVALIDCHARS);
198 responseString.append("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>");
205 if(!"API".equals(policyData.getApiflag()) && policyData.getRuleAlgorithmschoices() != null && !policyData.getRuleAlgorithmschoices().isEmpty()){
206 for(Object attribute : policyData.getRuleAlgorithmschoices()){
207 if(attribute instanceof LinkedHashMap<?, ?>){
208 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
209 if(((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1") == null){
210 responseString.append(RULEALGORITHMS + label + " : Field 1 value is not selected</i><br>");
213 if(((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo") == null){
214 responseString.append(RULEALGORITHMS + label + " : Field 2 value is not selected</i><br>");
217 if(((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2") != null){
218 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
219 if(!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)){
220 responseString.append(RULEALGORITHMS + label + " : Field 3 value has special characters</i><br>");
224 responseString.append(RULEALGORITHMS + label + " : Field 3 value is empty</i><br>");
231 if(CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
232 if ("Base".equals(policyData.getConfigPolicyType()) || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
233 || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType()) || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType())
234 || MICROSERVICES.equals(policyData.getConfigPolicyType()) || OPTIMIZATION.equals(policyData.getConfigPolicyType())) {
236 if(!Strings.isNullOrEmpty(policyData.getOnapName())) {
237 String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
238 if(!onapNameValidate.contains(SUCCESS)){
239 responseString.append("<b>OnapName</b>:<i>" + onapNameValidate + HTML_ITALICS_LNBREAK);
243 responseString.append("<b>Onap Name</b>: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
248 if(!Strings.isNullOrEmpty(policyData.getRiskType())) {
249 String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
250 if(!riskTypeValidate.contains(SUCCESS)){
251 responseString.append("<b>RiskType</b>:<i>" + riskTypeValidate + HTML_ITALICS_LNBREAK);
255 responseString.append("<b>RiskType</b>: Risk Type Should not be Empty" + HTML_ITALICS_LNBREAK);
259 if(!Strings.isNullOrEmpty(policyData.getRiskLevel())) {
260 String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
261 if(!validateRiskLevel.contains(SUCCESS)){
262 responseString.append("<b>RiskLevel</b>:<i>" + validateRiskLevel + HTML_ITALICS_LNBREAK);
266 responseString.append("<b>RiskLevel</b>: Risk Level Should not be Empty" + HTML_ITALICS_LNBREAK);
270 if(!Strings.isNullOrEmpty(policyData.getGuard())) {
271 String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
272 if(!validateGuard.contains(SUCCESS)){
273 responseString.append("<b>Guard</b>:<i>" + validateGuard + HTML_ITALICS_LNBREAK);
277 responseString.append("<b>Guard</b>: Guard Value Should not be Empty" + HTML_ITALICS_LNBREAK);
281 // Validate Config Base Policy Data
282 if("Base".equalsIgnoreCase(policyData.getConfigPolicyType())){
283 if(!Strings.isNullOrEmpty(policyData.getConfigName())) {
284 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
285 if(!configNameValidate.contains(SUCCESS)){
286 responseString.append("ConfigName:" + configNameValidate + HTML_ITALICS_LNBREAK);
290 responseString.append("Config Name: Config Name Should not be Empty" + HTML_ITALICS_LNBREAK);
293 if(!Strings.isNullOrEmpty(policyData.getConfigType())) {
294 String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
295 if(!configTypeValidate.contains(SUCCESS)){
296 responseString.append("ConfigType:" + configTypeValidate + HTML_ITALICS_LNBREAK);
300 responseString.append("Config Type: Config Type Should not be Empty" + HTML_ITALICS_LNBREAK);
303 if(!Strings.isNullOrEmpty(policyData.getConfigBodyData())) {
304 String configBodyData = policyData.getConfigBodyData();
305 String configType = policyData.getConfigType();
306 if (configType != null) {
307 if ("JSON".equals(configType)) {
308 if (!PolicyUtils.isJSONValid(configBodyData)) {
309 responseString.append("Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK);
312 } else if ("XML".equals(configType)) {
313 if (!PolicyUtils.isXMLValid(configBodyData)) {
314 responseString.append("Config Body: XML Content data is not valid" + HTML_ITALICS_LNBREAK);
317 } else if ("PROPERTIES".equals(configType)) {
318 if (!PolicyUtils.isPropValid(configBodyData) || "".equals(configBodyData)) {
319 responseString.append("Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK);
322 } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) {
323 responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
328 responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
333 // Validate Config Firewall Policy Data
334 if(FIREWALL.equalsIgnoreCase(policyData.getConfigPolicyType())){
335 if(policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()){
336 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
337 if(!configNameValidate.contains(SUCCESS)){
338 responseString.append("<b>ConfigName</b>:<i>" + configNameValidate + HTML_ITALICS_LNBREAK);
342 responseString.append("<b>Config Name</b>:<i> Config Name is required" + HTML_ITALICS_LNBREAK);
345 if(policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()){
346 responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + HTML_ITALICS_LNBREAK);
351 // Validate BRMS_Param Policy Data
352 if(BRMSPARAM.equalsIgnoreCase(policyData.getConfigPolicyType()) && Strings.isNullOrEmpty(policyData.getRuleName())){
353 responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required" + HTML_ITALICS_LNBREAK);
357 // Validate BRMS_Raw Policy Data
358 if(BRMSRAW.equalsIgnoreCase(policyData.getConfigPolicyType())){
359 if(policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()){
360 String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
362 // If there are any error other than Annotations then this is not Valid
363 if(message.contains("[ERR")){
364 responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message + HTML_ITALICS_LNBREAK);
368 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required" + HTML_ITALICS_LNBREAK);
373 // Validate ClosedLoop_PM Policy Data
374 if(CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())){
376 if(Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())){
377 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK);
382 LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
383 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK);
387 if(policyData.getJsonBody() != null){
389 ClosedLoopPMBody pmBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class);
390 if(pmBody.getEmailAddress() != null){
391 String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
392 if(result != SUCCESS){
393 responseString.append(result + HTML_ITALICS_LNBREAK);
397 if((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS() || pmBody.isvUSP()) != true){
398 responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
401 if(pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()){
402 String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
403 if(!result.contains(SUCCESS)){
404 responseString.append("<b>GeoLink</b>:<i>" + result + HTML_ITALICS_LNBREAK);
408 if(pmBody.getAttributes() != null && !pmBody.getAttributes().isEmpty()){
409 for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
410 String key = entry.getKey();
411 String value = entry.getValue();
412 if(!key.contains("Message")){
413 String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
414 if(!attributeValidate.contains(SUCCESS)){
415 responseString.append("<b>Attributes</b>:<i>" + key + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK);
422 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
427 // Validate ClosedLoop_Fault Policy Data
428 if(CLOSEDLOOP_POLICY.equalsIgnoreCase(policyData.getConfigPolicyType())){
429 if(policyData.getJsonBody() != null){
431 // For API we need to get the conditions key from the Json request and check it before deserializing to POJO due to the enum
432 if("API".equals(policyData.getApiflag())){
433 JSONObject json = new JSONObject(policyData.getJsonBody());
434 if(!json.isNull("conditions")){
435 String apiCondition = (String) json.get("conditions");
436 if(Strings.isNullOrEmpty(apiCondition)){
437 responseString.append("<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
438 return responseString;
441 responseString.append("<b>Conditions</b>: <i>There were no conditions provided in configBody json" + HTML_ITALICS_LNBREAK);
442 return responseString;
445 if(policyData.getTrapDatas().getTrap1() != null){
446 if(policyData.getClearTimeOut() == null){
447 responseString.append("<b>Trigger Clear TimeOut</b>: <i>Trigger Clear TimeOut is required when atleast One Trigger Signature is enabled</i><br>");
450 if(policyData.getTrapMaxAge() == null){
451 responseString.append("<b>Trap Max Age</b>: <i>Trap Max Age is required when atleast One Trigger Signature is enabled</i><br>");
455 if(policyData.getFaultDatas().getTrap1() != null && policyData.getVerificationclearTimeOut() == null){
456 responseString.append("<b>Fault Clear TimeOut</b>: <i>Fault Clear TimeOut is required when atleast One Fault Signature is enabled</i><br>");
461 ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class);
462 if(faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()){
463 String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
464 if(!SUCCESS.equals(result)){
465 responseString.append(result+ HTML_ITALICS_LNBREAK);
469 if((faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
470 responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
473 if(faultBody.getActions() == null || faultBody.getActions().isEmpty()){
474 responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
477 if(faultBody.getClosedLoopPolicyStatus() == null || faultBody.getClosedLoopPolicyStatus().isEmpty()){
478 responseString.append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
481 if(faultBody.getConditions() == null){
482 responseString.append("<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
485 if(faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()){
486 String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
487 if(!result.contains(SUCCESS)){
488 responseString.append("<b>GeoLink</b>:<i>" + result + HTML_ITALICS_LNBREAK);
492 if(faultBody.getAgingWindow() == 0){
493 responseString.append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
496 if(faultBody.getTimeInterval() == 0){
497 responseString.append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
500 if(faultBody.getRetrys() == 0){
501 responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
504 if(faultBody.getTimeOutvPRO() == 0){
505 responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
508 if(faultBody.getTimeOutRuby() == 0){
509 responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
512 if(faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()){
513 responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
517 responseString.append("<b>D2/Virtualized Services</b>: <i>Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
518 responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
519 responseString.append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
520 responseString.append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
521 responseString.append("<b>Conditions</b>: <i>Select Atleast one Condition" + HTML_ITALICS_LNBREAK);
522 responseString.append("<b>PEP Name</b>: <i>PEP Name is required" + HTML_ITALICS_LNBREAK);
523 responseString.append("<b>PEP Action</b>: <i>PEP Action is required" + HTML_ITALICS_LNBREAK);
524 responseString.append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
525 responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
526 responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
527 responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
528 responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
533 // Validate MicroServices Policy Data
534 if (MICROSERVICES.equals(policyData.getConfigPolicyType())){
536 if(!Strings.isNullOrEmpty(policyData.getServiceType())){
538 modelRequiredFieldsList.clear();
539 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
543 if (policyData.getServiceType().contains("-v")){
544 service = policyData.getServiceType().split("-v")[0];
545 version = policyData.getServiceType().split("-v")[1];
547 service = policyData.getServiceType();
548 version = policyData.getVersion();
551 if(!Strings.isNullOrEmpty(version)) {
552 MicroServiceModels returnModel = getMSModelData(service, version);
554 if(returnModel != null) {
556 String annotation = returnModel.getAnnotation();
557 String refAttributes = returnModel.getRef_attributes();
558 String subAttributes = returnModel.getSub_attributes();
559 String modelAttributes = returnModel.getAttributes();
561 if (!Strings.isNullOrEmpty(annotation)){
562 Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
563 for (Entry<String, String> rMap : rangeMap.entrySet()){
564 if (rMap.getValue().contains("range::")){
565 String value = mapAttribute.get(rMap.getKey().trim());
566 String[] tempString = rMap.getValue().split("::")[1].split("-");
567 int startNum = Integer.parseInt(tempString[0]);
568 int endNum = Integer.parseInt(tempString[1]);
569 String returnString = "InvalidreturnModel Range:" + rMap.getKey() + " must be between "
570 + startNum + " - " + endNum + ",";
573 if (PolicyUtils.isInteger(value.replace("\"", ""))){
574 int result = Integer.parseInt(value.replace("\"", ""));
575 if (result < startNum || result > endNum){
576 responseString.append(returnString);
580 responseString.append(returnString);
584 responseString.append("<b>"+rMap.getKey()+"</b>:<i>" + rMap.getKey()
585 + " is required for the MicroService model " + service + HTML_ITALICS_LNBREAK);
592 // Validate for configName, location, uuid, and policyScope if no annotations exist for this model
593 if(Strings.isNullOrEmpty(policyData.getLocation())){
594 responseString.append("<b>Micro Service Model</b>:<i> location is required for this model" + HTML_ITALICS_LNBREAK);
598 if(Strings.isNullOrEmpty(policyData.getConfigName())){
599 responseString.append("<b>Micro Service Model</b>:<i> configName is required for this model" + HTML_ITALICS_LNBREAK);
603 if(Strings.isNullOrEmpty(policyData.getUuid())){
604 responseString.append("<b>Micro Service Model</b>:<i> uuid is required for this model" + HTML_ITALICS_LNBREAK);
608 if(Strings.isNullOrEmpty(policyData.getPolicyScope())){
609 responseString.append("<b>Micro Service Model</b>:<i> policyScope is required for this model" + HTML_ITALICS_LNBREAK);
614 // If request comes from the API we need to validate required fields in the Micro Service Model
615 // GUI request are already validated from the SDK-APP
616 if("API".equals(policyData.getApiflag())){
617 // get list of required fields from the sub_Attributes of the Model
618 if(!Strings.isNullOrEmpty(subAttributes)) {
619 JsonObject subAttributesJson = stringToJsonObject(subAttributes);
620 findRequiredFields(subAttributesJson);
623 // get list of required fields from the attributes of the Model
624 if (!Strings.isNullOrEmpty(modelAttributes)) {
625 Map<String, String> modelAttributesMap = null;
626 if (",".equals(modelAttributes.substring(modelAttributes.length()-1))) {
627 String attributeString = modelAttributes.substring(0, modelAttributes.length()-1);
628 modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributeString);
630 modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
632 String json = new ObjectMapper().writeValueAsString(modelAttributesMap);
633 findRequiredFields(stringToJsonObject(json));
636 // get list of required fields from the ref_Attributes of the Model
637 if (!Strings.isNullOrEmpty(refAttributes)) {
638 Map<String, String> refAttributesMap = null;
639 if (",".equals(refAttributes.substring(refAttributes.length()-1))) {
640 String attributesString = refAttributes.substring(0, refAttributes.length()-1);
641 refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributesString);
643 refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
645 String json = new ObjectMapper().writeValueAsString(refAttributesMap);
646 findRequiredFields(stringToJsonObject(json));
649 if (modelRequiredFieldsList!=null || !modelRequiredFieldsList.isEmpty()) {
650 // create jsonRequestMap with all json keys and values from request
651 JsonNode rootNode = (JsonNode) policyData.getPolicyJSON();
652 jsonRequestMap.clear();
653 pullModelJsonKeyPairs(rootNode);
655 // validate if the requiredFields are in the request
656 for(String requiredField : modelRequiredFieldsList) {
657 if (jsonRequestMap.containsKey(requiredField)) {
658 String value = jsonRequestMap.get(requiredField);
659 if(Strings.isNullOrEmpty(jsonRequestMap.get(requiredField)) ||
660 "\"\"".equals(value) ||
661 "".equals(jsonRequestMap.get(requiredField))){
662 responseString.append("<b>Micro Service Model</b>:<i> " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
666 responseString.append("<b>Micro Service Model</b>:<i> " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
673 responseString.append("<b>Micro Service Model</b>:<i> Invalid Model. The model name, " + service +
674 " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
678 responseString.append("<b>Micro Service Version</b>:<i> Micro Service Version is required" + HTML_ITALICS_LNBREAK);
682 responseString.append("<b>Micro Service</b>:<i> Micro Service Model is required" + HTML_ITALICS_LNBREAK);
686 if(Strings.isNullOrEmpty(policyData.getPriority())){
687 responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
692 // Validate Optimization Policy Data
693 if (OPTIMIZATION.equals(policyData.getConfigPolicyType())){
695 if(!Strings.isNullOrEmpty(policyData.getServiceType())){
697 modelRequiredFieldsList.clear();
698 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
702 if (policyData.getServiceType().contains("-v")){
703 service = policyData.getServiceType().split("-v")[0];
704 version = policyData.getServiceType().split("-v")[1];
706 service = policyData.getServiceType();
707 version = policyData.getVersion();
710 if(!Strings.isNullOrEmpty(version)) {
711 OptimizationModels returnModel = getOptimizationModelData(service, version);
713 if(returnModel != null) {
715 String annotation = returnModel.getAnnotation();
716 String refAttributes = returnModel.getRefattributes();
717 String subAttributes = returnModel.getSubattributes();
718 String modelAttributes = returnModel.getAttributes();
720 if (!Strings.isNullOrEmpty(annotation)){
721 Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
722 for (Entry<String, String> rMap : rangeMap.entrySet()){
723 if (rMap.getValue().contains("range::")){
724 String value = mapAttribute.get(rMap.getKey().trim());
725 String[] tempString = rMap.getValue().split("::")[1].split("-");
726 int startNum = Integer.parseInt(tempString[0]);
727 int endNum = Integer.parseInt(tempString[1]);
728 String returnString = "InvalidreturnModel Range:" + rMap.getKey() + " must be between "
729 + startNum + " - " + endNum + ",";
732 if (PolicyUtils.isInteger(value.replace("\"", ""))){
733 int result = Integer.parseInt(value.replace("\"", ""));
734 if (result < startNum || result > endNum){
735 responseString.append(returnString);
739 responseString.append(returnString);
743 responseString.append("<b>"+rMap.getKey()+"</b>:<i>" + rMap.getKey()
744 + " is required for the Optimization model " + service + HTML_ITALICS_LNBREAK);
752 // If request comes from the API we need to validate required fields in the Micro Service Model
753 // GUI request are already validated from the SDK-APP
754 if("API".equals(policyData.getApiflag())){
755 // get list of required fields from the sub_Attributes of the Model
756 if(!Strings.isNullOrEmpty(subAttributes)) {
757 JsonObject subAttributesJson = stringToJsonObject(subAttributes);
758 findRequiredFields(subAttributesJson);
761 // get list of required fields from the attributes of the Model
762 if (!Strings.isNullOrEmpty(modelAttributes)) {
763 Map<String, String> modelAttributesMap = null;
764 if (",".equals(modelAttributes.substring(modelAttributes.length()-1))) {
765 String attributeString = modelAttributes.substring(0, modelAttributes.length()-1);
766 modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributeString);
768 modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
770 String json = new ObjectMapper().writeValueAsString(modelAttributesMap);
771 findRequiredFields(stringToJsonObject(json));
774 // get list of required fields from the ref_Attributes of the Model
775 if (!Strings.isNullOrEmpty(refAttributes)) {
776 Map<String, String> refAttributesMap = null;
777 if (",".equals(refAttributes.substring(refAttributes.length()-1))) {
778 String attributesString = refAttributes.substring(0, refAttributes.length()-1);
779 refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributesString);
781 refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
783 String json = new ObjectMapper().writeValueAsString(refAttributesMap);
784 findRequiredFields(stringToJsonObject(json));
787 if (modelRequiredFieldsList!=null || !modelRequiredFieldsList.isEmpty()) {
788 // create jsonRequestMap with all json keys and values from request
789 JsonNode rootNode = (JsonNode) policyData.getPolicyJSON();
790 jsonRequestMap.clear();
791 pullModelJsonKeyPairs(rootNode);
793 // validate if the requiredFields are in the request
794 for(String requiredField : modelRequiredFieldsList) {
795 if (jsonRequestMap.containsKey(requiredField)) {
796 String value = jsonRequestMap.get(requiredField);
797 if(Strings.isNullOrEmpty(jsonRequestMap.get(requiredField)) ||
798 "\"\"".equals(value) ||
799 "".equals(jsonRequestMap.get(requiredField))){
800 responseString.append("<b>Optimization Service Model</b>:<i> " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
804 responseString.append("<b>Optimization Service Model</b>:<i> " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
811 responseString.append("<b>Optimization Service Model</b>:<i> Invalid Model. The model name, " + service +
812 " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
816 responseString.append("<b>Optimization Service Version</b>:<i> Optimization Service Version is required" + HTML_ITALICS_LNBREAK);
820 responseString.append("<b>Optimization Service</b>:<i> Optimization Service Model is required" + HTML_ITALICS_LNBREAK);
824 if(Strings.isNullOrEmpty(policyData.getPriority())){
825 responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
830 if (DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
831 if(!Strings.isNullOrEmpty(policyData.getOnapName())){
832 String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
833 if(!onapNameValidate.contains(SUCCESS)){
834 responseString.append("OnapName:" + onapNameValidate + HTML_ITALICS_LNBREAK);
838 responseString.append("Onap Name: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
842 if("Rainy_Day".equals(policyData.getRuleProvider())){
843 if(policyData.getRainyday()==null){
844 responseString.append("<b> Rainy Day Parameters are Required </b><br>");
847 if(Strings.isNullOrEmpty(policyData.getRainyday().getServiceType())){
848 responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
851 if(Strings.isNullOrEmpty(policyData.getRainyday().getVnfType())){
852 responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
855 if(Strings.isNullOrEmpty(policyData.getRainyday().getBbid())){
856 responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
859 if(Strings.isNullOrEmpty(policyData.getRainyday().getWorkstep())){
860 responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
863 if(!policyData.getRainyday().getTreatmentTableChoices().isEmpty() &&
864 policyData.getRainyday().getTreatmentTableChoices() != null){
866 for(Object treatmentMap: policyData.getRainyday().getTreatmentTableChoices()){
867 String errorCode = null;
868 String treatment = null;
869 if(treatmentMap instanceof LinkedHashMap<?, ?>){
871 if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("errorcode")){
872 errorCode = ((LinkedHashMap<?, ?>) treatmentMap).get("errorcode").toString();
874 if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("treatment")){
875 treatment = ((LinkedHashMap<?, ?>) treatmentMap).get("treatment").toString();
879 if(Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)){
880 responseString.append("Rainy Day <b>Error Code</b> and <b>Desired Treatment</b> cannot be empty<br>");
884 if(Strings.isNullOrEmpty(errorCode)){
885 responseString.append("Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
889 if(Strings.isNullOrEmpty(treatment)){
890 responseString.append("Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
897 responseString.append("Rainy Day <b>Desired Automated Treatments</b> are Required<br>");
903 if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
904 if(policyData.getYamlparams()==null){
905 responseString.append("<b> Guard Params are Required </b>" + HTML_ITALICS_LNBREAK);
908 if(Strings.isNullOrEmpty(policyData.getYamlparams().getActor())){
909 responseString.append("Guard Params <b>Actor</b> is Required " + HTML_ITALICS_LNBREAK);
912 if(Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())){
913 responseString.append("Guard Params <b>Recipe</b> is Required " + HTML_ITALICS_LNBREAK);
916 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())){
917 responseString.append("Guard Params <b>Guard Active Start</b> is Required " + HTML_ITALICS_LNBREAK);
920 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())){
921 responseString.append("Guard Params <b>Guard Active End</b> is Required " + HTML_ITALICS_LNBREAK);
924 if("GUARD_YAML".equals(policyData.getRuleProvider())){
925 if(Strings.isNullOrEmpty(policyData.getYamlparams().getLimit())){
926 responseString.append(" Guard Params <b>Limit</b> is Required " + HTML_ITALICS_LNBREAK);
928 }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
929 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + HTML_ITALICS_LNBREAK);
932 if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())){
933 responseString.append("Guard Params <b>Time Window</b> is Required" + HTML_ITALICS_LNBREAK);
935 }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
936 responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + HTML_ITALICS_LNBREAK);
939 if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())){
940 responseString.append("Guard Params <b>Time Units</b> is Required" + HTML_ITALICS_LNBREAK);
943 }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
944 if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
945 responseString.append(" Guard Params <b>BlackList</b> is Required " + HTML_ITALICS_LNBREAK);
948 for(String blackList: policyData.getYamlparams().getBlackList()){
949 if(blackList==null || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))){
950 responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + HTML_ITALICS_LNBREAK);
961 if(ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
962 if(!Strings.isNullOrEmpty(policyData.getActionPerformer())){
963 String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
964 if(!actionPerformer.contains(SUCCESS)){
965 responseString.append("<b>ActionPerformer</b>:<i>" + actionPerformer + HTML_ITALICS_LNBREAK);
969 responseString.append("<b>ActionPerformer</b>:<i> ActionPerformer Should not be empty" + HTML_ITALICS_LNBREAK);
973 if(!Strings.isNullOrEmpty(policyData.getActionAttributeValue())){
974 String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
975 if(!actionAttribute.contains(SUCCESS)){
976 responseString.append("<b>ActionAttribute</b>:<i>" + actionAttribute + HTML_ITALICS_LNBREAK);
980 responseString.append("<b>ActionAttribute</b>:<i> ActionAttribute Should not be empty" + HTML_ITALICS_LNBREAK);
985 if(CONFIG_POLICY.equals(policyData.getPolicyType())){
988 if(commonClassDao!=null){
989 List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
990 if (!spData.isEmpty()){
991 SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
992 value = "<b>Message</b>:<i>" + safePolicyWarningData.getMessage() +"</i>";
995 responseString.append(SUCCESS + "@#"+ value);
999 responseString.append(SUCCESS);
1003 return responseString;
1005 catch (Exception e){
1006 LOGGER.error("Exception Occured during Policy Validation" +e);
1011 protected String emailValidation(String email, String response){
1012 String res = response;
1014 String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
1015 if(!validateEmail.contains(SUCCESS)){
1016 res += "<b>Email</b>:<i>" + validateEmail + HTML_ITALICS_LNBREAK;
1025 private MicroServiceModels getMSModelData(String name, String version) {
1026 MicroServiceModels workingModel = null;
1028 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
1029 if(microServiceModelsData != null){
1030 workingModel = (MicroServiceModels) microServiceModelsData.get(0);
1032 }catch(Exception e){
1033 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, "
1034 + name + " was not found in the dictionary: ";
1035 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
1039 return workingModel;
1042 private OptimizationModels getOptimizationModelData(String name, String version) {
1043 OptimizationModels workingModel = null;
1045 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, "modelName:version", name+":"+version);
1046 if(optimizationModelsData != null){
1047 workingModel = (OptimizationModels) optimizationModelsData.get(0);
1049 }catch(Exception e){
1050 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, "
1051 + name + " was not found in the dictionary: ";
1052 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
1056 return workingModel;
1059 private void pullJsonKeyPairs(JsonNode rootNode) {
1060 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
1062 while (fieldsIterator.hasNext()) {
1063 Map.Entry<String, JsonNode> field = fieldsIterator.next();
1064 final String key = field.getKey();
1065 final JsonNode value = field.getValue();
1066 if (value.isContainerNode() && !value.isArray()) {
1067 pullJsonKeyPairs(value); // RECURSIVE CALL
1069 if (value.isArray()){
1070 String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
1071 mapAttribute.put(key, newValue);
1073 mapAttribute.put(key, value.toString().trim());
1079 private void pullModelJsonKeyPairs(JsonNode rootNode) {
1080 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
1082 while (fieldsIterator.hasNext()) {
1083 Map.Entry<String, JsonNode> field = fieldsIterator.next();
1084 final String key = field.getKey();
1085 final JsonNode value = field.getValue();
1087 if (value.isContainerNode() && !value.isArray()) {
1088 jsonRequestMap.put(key, "containerNode");
1089 pullModelJsonKeyPairs(value); // RECURSIVE CALL
1090 } else if (value.isArray()) {
1092 jsonRequestMap.put(key, "array");
1093 String stringValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]"}, new String[]{"",""});
1094 ObjectMapper mapper = new ObjectMapper();
1095 JsonNode newValue = mapper.readTree(stringValue);
1096 pullModelJsonKeyPairs(newValue);
1097 } catch (IOException e) {
1098 LOGGER.info("PolicyValidation: Exception occurred while mapping string to JsonNode " + e);
1101 jsonRequestMap.put(key, value.toString().trim());
1106 private JsonObject stringToJsonObject(String value) {
1107 try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
1108 return jsonReader.readObject();
1109 } catch(JsonException| IllegalStateException e){
1110 LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
1115 private void findRequiredFields(JsonObject json) {
1117 for(Entry<String, JsonValue> keyMap : json.entrySet()){
1118 Object obj = keyMap.getValue();
1119 if(obj instanceof JsonObject){
1120 JsonObject jsonObj = (JsonObject)obj;
1121 for(Entry<String, JsonValue> jsonMap : jsonObj.entrySet()){
1122 if(jsonMap.getValue().toString().contains("required-true")){
1123 modelRequiredFieldsList.add(jsonMap.getKey());
1127 if(keyMap.getValue().toString().contains("required-true")){
1128 modelRequiredFieldsList.add(keyMap.getKey());