2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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.SafePolicyWarning;
48 import org.onap.policy.utils.PolicyUtils;
49 import org.onap.policy.xacml.api.XACMLErrorConstants;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.stereotype.Service;
53 import com.fasterxml.jackson.databind.JsonNode;
54 import com.fasterxml.jackson.databind.ObjectMapper;
55 import com.google.common.base.Splitter;
56 import com.google.common.base.Strings;
59 public class PolicyValidation {
61 private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidation.class);
63 public static final String CONFIG_POLICY = "Config";
64 public static final String ACTION_POLICY = "Action";
65 public static final String DECISION_POLICY = "Decision";
66 public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
67 public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
68 public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
69 public static final String MICROSERVICES="Micro Service";
70 public static final String FIREWALL="Firewall Config";
71 public static final String HTML_ITALICS_LNBREAK = "</i><br>";
72 public static final String SUCCESS = "success";
73 public static final String EMPTY_COMPONENT_ATTR = "Component Attributes: One or more Fields in Component Attributes is Empty.";
75 private static Map<String, String> mapAttribute = new HashMap<>();
76 private static Map<String, String> jsonRequestMap = new HashMap<>();
77 private static List<String> modelRequiredFieldsList = new ArrayList<>();
79 private static CommonClassDao commonClassDao;
82 public PolicyValidation(CommonClassDao commonClassDao){
83 PolicyValidation.commonClassDao = commonClassDao;
87 * This is an empty constructor
89 public PolicyValidation(){
94 public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException{
97 StringBuilder responseString = new StringBuilder();
98 ObjectMapper mapper = new ObjectMapper();
100 if(policyData.getPolicyName() != null){
101 String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
102 if(!policyNameValidate.contains(SUCCESS)){
103 responseString.append("<b>PolicyName</b>:<i>" + policyNameValidate + HTML_ITALICS_LNBREAK);
107 responseString.append( "<b>PolicyName</b>: PolicyName Should not be empty" + HTML_ITALICS_LNBREAK);
110 if(policyData.getPolicyDescription() != null){
111 String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
112 if(!descriptionValidate.contains(SUCCESS)){
113 responseString.append("<b>Description</b>:<i>" + descriptionValidate + HTML_ITALICS_LNBREAK);
118 if(!"API".equals(policyData.getApiflag()) && policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()){
119 for(Object attribute : policyData.getAttributes()){
120 if(attribute instanceof LinkedHashMap<?, ?>){
123 if(((LinkedHashMap<?, ?>) attribute).get("key") != null){
124 key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
125 if(!PolicyUtils.policySpecialCharValidator(key).contains("success")){
126 responseString.append("<b>Attributes or Component Attributes</b>:<i>" + value + " : value has spaces or invalid characters</i><br>");
130 if(CONFIG_POLICY.equals(policyData.getPolicyType())){
131 if("Base".equals(policyData.getConfigPolicyType())){
132 responseString.append("<b>Attributes</b>:<i> has one missing Attribute key</i><br>");
134 if("BRMS_Param".equals(policyData.getConfigPolicyType()) || "BRMS_Raw".equals(policyData.getConfigPolicyType())){
135 responseString.append("<b>Rule Attributes</b>:<i> has one missing Attribute key</i><br>");
138 responseString.append("<b>Component Attributes</b>:<i> has one missing Component Attribute key</i><br>");
142 if(((LinkedHashMap<?, ?>) attribute).get("value") != null){
143 value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
144 if(!PolicyUtils.policySpecialCharValidator(value).contains("success")){
145 if(CONFIG_POLICY.equals(policyData.getPolicyType())){
146 if("Base".equals(policyData.getConfigPolicyType())){
147 responseString.append("<b>Attributes</b>:<i>" + value + " : value has spaces or invalid characters</i><br>");
149 if("BRMS_Param".equals(policyData.getConfigPolicyType()) || "BRMS_Raw".equals(policyData.getConfigPolicyType())){
150 responseString.append("<b>Rule Attributes</b>:<i>" + value + " : value has spaces or invalid characters</i><br>");
153 responseString.append("<b>Component Attributes</b>:<i>" + value + " : value has spaces or invalid characters</i><br>");
158 if(CONFIG_POLICY.equals(policyData.getPolicyType())){
159 if("Base".equals(policyData.getConfigPolicyType())){
160 responseString.append("<b>Attributes</b>:<i> has one missing Attribute value</i><br>");
162 if("BRMS_Param".equals(policyData.getConfigPolicyType()) || "BRMS_Raw".equals(policyData.getConfigPolicyType())){
163 responseString.append("<b>Rule Attributes</b>:<i> has one missing Attribute value</i><br>");
166 responseString.append("<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>");
174 //Decision Policy Attributes Validation
175 if(!"API".equals(policyData.getApiflag()) && policyData.getSettings() != null && !policyData.getSettings().isEmpty()){
176 for(Object attribute : policyData.getAttributes()){
177 if(attribute instanceof LinkedHashMap<?, ?>){
179 if(((LinkedHashMap<?, ?>) attribute).get("key") == null){
180 responseString.append("<b>Settings Attributes</b>:<i> has one missing Attribute key</i><br>");
183 if(((LinkedHashMap<?, ?>) attribute).get("value") != null){
184 value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
185 if(!PolicyUtils.policySpecialCharValidator(value).contains("success")){
186 responseString.append("<b>Settings Attributes</b>:<i>" + value + " : value has spaces or invalid characters</i><br>");
190 responseString.append("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>");
197 if(!"API".equals(policyData.getApiflag()) && policyData.getRuleAlgorithmschoices() != null && !policyData.getRuleAlgorithmschoices().isEmpty()){
198 for(Object attribute : policyData.getRuleAlgorithmschoices()){
199 if(attribute instanceof LinkedHashMap<?, ?>){
200 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
201 if(((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1") == null){
202 responseString.append("<b>Rule Algorithms</b>:<i>" + label + " : Field 1 value is not selected</i><br>");
205 if(((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo") == null){
206 responseString.append("<b>Rule Algorithms</b>:<i>" + label + " : Field 2 value is not selected</i><br>");
209 if(((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2") != null){
210 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
211 if(!PolicyUtils.policySpecialCharValidator(value).contains("success")){
212 responseString.append("<b>Rule Algorithms</b>:<i>" + label + " : Field 3 value has special characters</i><br>");
216 responseString.append("<b>Rule Algorithms</b>:<i>" + label + " : Field 3 value is empty</i><br>");
223 if(CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
224 if ("Base".equals(policyData.getConfigPolicyType()) || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
225 || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType()) || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType())
226 || MICROSERVICES.equals(policyData.getConfigPolicyType())) {
228 if(!Strings.isNullOrEmpty(policyData.getOnapName())) {
229 String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
230 if(!onapNameValidate.contains(SUCCESS)){
231 responseString.append("<b>OnapName</b>:<i>" + onapNameValidate + HTML_ITALICS_LNBREAK);
235 responseString.append("<b>Onap Name</b>: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
240 if(!Strings.isNullOrEmpty(policyData.getRiskType())) {
241 String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
242 if(!riskTypeValidate.contains(SUCCESS)){
243 responseString.append("<b>RiskType</b>:<i>" + riskTypeValidate + HTML_ITALICS_LNBREAK);
247 responseString.append("<b>RiskType</b>: Risk Type Should not be Empty" + HTML_ITALICS_LNBREAK);
251 if(!Strings.isNullOrEmpty(policyData.getRiskLevel())) {
252 String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
253 if(!validateRiskLevel.contains(SUCCESS)){
254 responseString.append("<b>RiskLevel</b>:<i>" + validateRiskLevel + HTML_ITALICS_LNBREAK);
258 responseString.append("<b>RiskLevel</b>: Risk Level Should not be Empty" + HTML_ITALICS_LNBREAK);
262 if(!Strings.isNullOrEmpty(policyData.getGuard())) {
263 String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
264 if(!validateGuard.contains(SUCCESS)){
265 responseString.append("<b>Guard</b>:<i>" + validateGuard + HTML_ITALICS_LNBREAK);
269 responseString.append("<b>Guard</b>: Guard Value Should not be Empty" + HTML_ITALICS_LNBREAK);
273 if("Base".equalsIgnoreCase(policyData.getConfigPolicyType())){
274 if(!Strings.isNullOrEmpty(policyData.getConfigName())) {
275 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
276 if(!configNameValidate.contains(SUCCESS)){
277 responseString.append("ConfigName:" + configNameValidate + HTML_ITALICS_LNBREAK);
281 responseString.append("Config Name: Config Name Should not be Empty" + HTML_ITALICS_LNBREAK);
284 if(!Strings.isNullOrEmpty(policyData.getConfigType())) {
285 String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
286 if(!configTypeValidate.contains(SUCCESS)){
287 responseString.append("ConfigType:" + configTypeValidate + HTML_ITALICS_LNBREAK);
291 responseString.append("Config Type: Config Type Should not be Empty" + HTML_ITALICS_LNBREAK);
294 if(!Strings.isNullOrEmpty(policyData.getConfigBodyData())) {
295 String configBodyData = policyData.getConfigBodyData();
296 String configType = policyData.getConfigType();
297 if (configType != null) {
298 if ("JSON".equals(configType)) {
299 if (!PolicyUtils.isJSONValid(configBodyData)) {
300 responseString.append("Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK);
303 } else if ("XML".equals(configType)) {
304 if (!PolicyUtils.isXMLValid(configBodyData)) {
305 responseString.append("Config Body: XML Content data is not valid" + HTML_ITALICS_LNBREAK);
308 } else if ("PROPERTIES".equals(configType)) {
309 if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
310 responseString.append("Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK);
313 } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) {
314 responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
319 responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
324 if(FIREWALL.equalsIgnoreCase(policyData.getConfigPolicyType())){
325 if(policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()){
326 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
327 if(!configNameValidate.contains(SUCCESS)){
328 responseString.append("<b>ConfigName</b>:<i>" + configNameValidate + HTML_ITALICS_LNBREAK);
332 responseString.append("<b>Config Name</b>:<i> Config Name is required" + HTML_ITALICS_LNBREAK);
335 if(policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()){
336 responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + HTML_ITALICS_LNBREAK);
340 if("BRMS_Param".equalsIgnoreCase(policyData.getConfigPolicyType()) && Strings.isNullOrEmpty(policyData.getRuleName())){
341 responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required" + HTML_ITALICS_LNBREAK);
344 if("BRMS_Raw".equalsIgnoreCase(policyData.getConfigPolicyType())){
345 if(policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()){
346 String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
348 // If there are any error other than Annotations then this is not Valid
349 if(message.contains("[ERR")){
350 responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message + HTML_ITALICS_LNBREAK);
354 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required" + HTML_ITALICS_LNBREAK);
358 if(CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())){
360 if(Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())){
361 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK);
366 LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
367 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK);
371 if(policyData.getJsonBody() != null){
373 ClosedLoopPMBody pmBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class);
374 if(pmBody.getEmailAddress() != null){
375 String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
376 if(result != SUCCESS){
377 responseString.append(result + HTML_ITALICS_LNBREAK);
381 if((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS() || pmBody.isvUSP()) != true){
382 responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
385 if(pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()){
386 String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
387 if(!result.contains(SUCCESS)){
388 responseString.append("<b>GeoLink</b>:<i>" + result + HTML_ITALICS_LNBREAK);
392 if(pmBody.getAttributes() != null && !pmBody.getAttributes().isEmpty()){
393 for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
394 String key = entry.getKey();
395 String value = entry.getValue();
396 if(!key.contains("Message")){
397 String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
398 if(!attributeValidate.contains(SUCCESS)){
399 responseString.append("<b>Attributes</b>:<i>" + key + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK);
406 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
410 if(CLOSEDLOOP_POLICY.equalsIgnoreCase(policyData.getConfigPolicyType())){
411 if(policyData.getJsonBody() != null){
413 // For API we need to get the conditions key from the Json request and check it before deserializing to POJO due to the enum
414 if("API".equals(policyData.getApiflag())){
415 JSONObject json = new JSONObject(policyData.getJsonBody());
416 if(!json.isNull("conditions")){
417 String apiCondition = (String) json.get("conditions");
418 if(Strings.isNullOrEmpty(apiCondition)){
419 responseString.append("<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
420 return responseString;
423 responseString.append("<b>Conditions</b>: <i>There were no conditions provided in configBody json" + HTML_ITALICS_LNBREAK);
424 return responseString;
427 if(policyData.getTrapDatas().getTrap1() != null){
428 if(policyData.getClearTimeOut() == null){
429 responseString.append("<b>Trigger Clear TimeOut</b>: <i>Trigger Clear TimeOut is required when atleast One Trigger Signature is enabled</i><br>");
432 if(policyData.getTrapMaxAge() == null){
433 responseString.append("<b>Trap Max Age</b>: <i>Trap Max Age is required when atleast One Trigger Signature is enabled</i><br>");
437 if(policyData.getFaultDatas().getTrap1() != null && policyData.getVerificationclearTimeOut() == null){
438 responseString.append("<b>Fault Clear TimeOut</b>: <i>Fault Clear TimeOut is required when atleast One Fault Signature is enabled</i><br>");
443 ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class);
444 if(faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()){
445 String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
446 if(!SUCCESS.equals(result)){
447 responseString.append(result+ HTML_ITALICS_LNBREAK);
451 if((faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
452 responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
455 if(faultBody.getActions() == null || faultBody.getActions().isEmpty()){
456 responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
459 if(faultBody.getClosedLoopPolicyStatus() == null || faultBody.getClosedLoopPolicyStatus().isEmpty()){
460 responseString.append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
463 if(faultBody.getConditions() == null){
464 responseString.append("<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
467 if(faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()){
468 String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
469 if(!result.contains(SUCCESS)){
470 responseString.append("<b>GeoLink</b>:<i>" + result + HTML_ITALICS_LNBREAK);
474 if(faultBody.getAgingWindow() == 0){
475 responseString.append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
478 if(faultBody.getTimeInterval() == 0){
479 responseString.append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
482 if(faultBody.getRetrys() == 0){
483 responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
486 if(faultBody.getTimeOutvPRO() == 0){
487 responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
490 if(faultBody.getTimeOutRuby() == 0){
491 responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
494 if(faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()){
495 responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
499 responseString.append("<b>D2/Virtualized Services</b>: <i>Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
500 responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
501 responseString.append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
502 responseString.append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
503 responseString.append("<b>Conditions</b>: <i>Select Atleast one Condition" + HTML_ITALICS_LNBREAK);
504 responseString.append("<b>PEP Name</b>: <i>PEP Name is required" + HTML_ITALICS_LNBREAK);
505 responseString.append("<b>PEP Action</b>: <i>PEP Action is required" + HTML_ITALICS_LNBREAK);
506 responseString.append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
507 responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
508 responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
509 responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
510 responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
515 if (MICROSERVICES.equals(policyData.getConfigPolicyType())){
516 if(!Strings.isNullOrEmpty(policyData.getServiceType())){
518 modelRequiredFieldsList = new ArrayList<>();
519 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
523 if (policyData.getServiceType().contains("-v")){
524 service = policyData.getServiceType().split("-v")[0];
525 version = policyData.getServiceType().split("-v")[1];
527 service = policyData.getServiceType();
528 version = policyData.getVersion();
531 if(!Strings.isNullOrEmpty(version)) {
532 MicroServiceModels returnModel = getAttributeObject(service, version);
534 if(returnModel != null) {
536 String annotation = returnModel.getAnnotation();
537 String refAttributes = returnModel.getRef_attributes();
538 String subAttributes = returnModel.getSub_attributes();
539 String modelAttributes = returnModel.getAttributes();
541 if (!Strings.isNullOrEmpty(annotation)){
542 Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
543 for (Entry<String, String> rMap : rangeMap.entrySet()){
544 if (rMap.getValue().contains("range::")){
545 String value = mapAttribute.get(rMap.getKey().trim());
546 String[] tempString = rMap.getValue().split("::")[1].split("-");
547 int startNum = Integer.parseInt(tempString[0]);
548 int endNum = Integer.parseInt(tempString[1]);
549 String returnString = "InvalidreturnModel Range:" + rMap.getKey() + " must be between "
550 + startNum + " - " + endNum + ",";
553 if (PolicyUtils.isInteger(value.replace("\"", ""))){
554 int result = Integer.parseInt(value.replace("\"", ""));
555 if (result < startNum || result > endNum){
556 responseString.append(returnString);
560 responseString.append(returnString);
564 responseString.append("<b>"+rMap.getKey()+"</b>:<i>" + rMap.getKey()
565 + " is required for the MicroService model " + service + HTML_ITALICS_LNBREAK);
572 // Validate for configName, location, uuid, and policyScope if no annotations exist for this model
573 if(Strings.isNullOrEmpty(policyData.getMsLocation())){
574 responseString.append("<b>Micro Service Model</b>:<i> location is required for this model" + HTML_ITALICS_LNBREAK);
578 if(Strings.isNullOrEmpty(policyData.getConfigName())){
579 responseString.append("<b>Micro Service Model</b>:<i> configName is required for this model" + HTML_ITALICS_LNBREAK);
583 if(Strings.isNullOrEmpty(policyData.getUuid())){
584 responseString.append("<b>Micro Service Model</b>:<i> uuid is required for this model" + HTML_ITALICS_LNBREAK);
588 if(Strings.isNullOrEmpty(policyData.getPolicyScope())){
589 responseString.append("<b>Micro Service Model</b>:<i> policyScope is required for this model" + HTML_ITALICS_LNBREAK);
594 // get list of required fields from the sub_Attributes of the Model
595 if(!Strings.isNullOrEmpty(subAttributes)) {
596 JsonObject subAttributesJson = stringToJsonObject(subAttributes);
597 findRequiredFields(subAttributesJson);
600 // get list of required fields from the attributes of the Model
601 if (!Strings.isNullOrEmpty(modelAttributes)) {
602 Map<String, String> modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
603 String json = new ObjectMapper().writeValueAsString(modelAttributesMap);
604 findRequiredFields(stringToJsonObject(json));
607 // get list of required fields from the ref_Attributes of the Model
608 if (!Strings.isNullOrEmpty(refAttributes)) {
609 Map<String, String> refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(refAttributes);
610 String json = new ObjectMapper().writeValueAsString(refAttributesMap);
611 findRequiredFields(stringToJsonObject(json));
614 // Validate Required Fields in the Micro Service Model
615 if (modelRequiredFieldsList!=null || !modelRequiredFieldsList.isEmpty()) {
616 // create jsonRequestMap with all json keys and values from request
617 JsonNode rootNode = (JsonNode) policyData.getPolicyJSON();
618 pullModelJsonKeyPairs(rootNode);
620 // validate if the requiredFields are in the request
621 for(String requiredField : modelRequiredFieldsList) {
622 if (jsonRequestMap.containsKey(requiredField)) {
623 String value = jsonRequestMap.get(requiredField);
624 if(Strings.isNullOrEmpty(jsonRequestMap.get(requiredField)) ||
625 "\"\"".equals(value) ||
626 "".equals(jsonRequestMap.get(requiredField))){
627 responseString.append("<b>Micro Service Model</b>:<i> " + requiredField + " is required" + HTML_ITALICS_LNBREAK);
631 responseString.append("<b>Micro Service Model</b>:<i> " + requiredField + " is required" + HTML_ITALICS_LNBREAK);
640 responseString.append("<b>Micro Service Model</b>:<i> Invalid Model. The model name, " + service +
641 " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
645 responseString.append("<b>Micro Service Version</b>:<i> Micro Service Version is required" + HTML_ITALICS_LNBREAK);
649 responseString.append("<b>Micro Service</b>:<i> Micro Service Model is required" + HTML_ITALICS_LNBREAK);
653 if(Strings.isNullOrEmpty(policyData.getPriority())){
654 responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
659 if (DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
660 if(!Strings.isNullOrEmpty(policyData.getOnapName())){
661 String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
662 if(!onapNameValidate.contains(SUCCESS)){
663 responseString.append("OnapName:" + onapNameValidate + HTML_ITALICS_LNBREAK);
667 responseString.append("Onap Name: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
671 if("Rainy_Day".equals(policyData.getRuleProvider())){
672 if(policyData.getRainyday()==null){
673 responseString.append("<b> Rainy Day Parameters are Required </b><br>");
676 if(Strings.isNullOrEmpty(policyData.getRainyday().getServiceType())){
677 responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
680 if(Strings.isNullOrEmpty(policyData.getRainyday().getVnfType())){
681 responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
684 if(Strings.isNullOrEmpty(policyData.getRainyday().getBbid())){
685 responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
688 if(Strings.isNullOrEmpty(policyData.getRainyday().getWorkstep())){
689 responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
692 if(!policyData.getRainyday().getTreatmentTableChoices().isEmpty() &&
693 policyData.getRainyday().getTreatmentTableChoices() != null){
695 for(Object treatmentMap: policyData.getRainyday().getTreatmentTableChoices()){
696 String errorCode = null;
697 String treatment = null;
698 if(treatmentMap instanceof LinkedHashMap<?, ?>){
700 if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("errorcode")){
701 errorCode = ((LinkedHashMap<?, ?>) treatmentMap).get("errorcode").toString();
703 if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("treatment")){
704 treatment = ((LinkedHashMap<?, ?>) treatmentMap).get("treatment").toString();
708 if(Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)){
709 responseString.append("Rainy Day <b>Error Code</b> and <b>Desired Treatment</b> cannot be empty<br>");
713 if(Strings.isNullOrEmpty(errorCode)){
714 responseString.append("Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
718 if(Strings.isNullOrEmpty(treatment)){
719 responseString.append("Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
726 responseString.append("Rainy Day <b>Desired Automated Treatments</b> are Required<br>");
732 if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
733 if(policyData.getYamlparams()==null){
734 responseString.append("<b> Guard Params are Required </b>" + HTML_ITALICS_LNBREAK);
737 if(Strings.isNullOrEmpty(policyData.getYamlparams().getActor())){
738 responseString.append("Guard Params <b>Actor</b> is Required " + HTML_ITALICS_LNBREAK);
741 if(Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())){
742 responseString.append("Guard Params <b>Recipe</b> is Required " + HTML_ITALICS_LNBREAK);
745 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())){
746 responseString.append("Guard Params <b>Guard Active Start</b> is Required " + HTML_ITALICS_LNBREAK);
749 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())){
750 responseString.append("Guard Params <b>Guard Active End</b> is Required " + HTML_ITALICS_LNBREAK);
753 if("GUARD_YAML".equals(policyData.getRuleProvider())){
754 if(Strings.isNullOrEmpty(policyData.getYamlparams().getLimit())){
755 responseString.append(" Guard Params <b>Limit</b> is Required " + HTML_ITALICS_LNBREAK);
757 }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
758 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + HTML_ITALICS_LNBREAK);
761 if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())){
762 responseString.append("Guard Params <b>Time Window</b> is Required" + HTML_ITALICS_LNBREAK);
764 }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
765 responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + HTML_ITALICS_LNBREAK);
768 if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())){
769 responseString.append("Guard Params <b>Time Units</b> is Required" + HTML_ITALICS_LNBREAK);
772 }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
773 if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
774 responseString.append(" Guard Params <b>BlackList</b> is Required " + HTML_ITALICS_LNBREAK);
777 for(String blackList: policyData.getYamlparams().getBlackList()){
778 if(blackList==null || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))){
779 responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + HTML_ITALICS_LNBREAK);
790 if(ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
791 if(!Strings.isNullOrEmpty(policyData.getActionPerformer())){
792 String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
793 if(!actionPerformer.contains(SUCCESS)){
794 responseString.append("<b>ActionPerformer</b>:<i>" + actionPerformer + HTML_ITALICS_LNBREAK);
798 responseString.append("<b>ActionPerformer</b>:<i> ActionPerformer Should not be empty" + HTML_ITALICS_LNBREAK);
802 if(!Strings.isNullOrEmpty(policyData.getActionAttributeValue())){
803 String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
804 if(!actionAttribute.contains(SUCCESS)){
805 responseString.append("<b>ActionAttribute</b>:<i>" + actionAttribute + HTML_ITALICS_LNBREAK);
809 responseString.append("<b>ActionAttribute</b>:<i> ActionAttribute Should not be empty" + HTML_ITALICS_LNBREAK);
814 if(CONFIG_POLICY.equals(policyData.getPolicyType())){
817 if(commonClassDao!=null){
818 List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
819 if (!spData.isEmpty()){
820 SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
821 value = "<b>Message</b>:<i>" + safePolicyWarningData.getMessage() +"</i>";
824 responseString.append(SUCCESS + "@#"+ value);
828 responseString.append(SUCCESS);
832 return responseString;
835 LOGGER.error("Exception Occured during Policy Validation" +e);
840 protected String emailValidation(String email, String response){
841 String res = response;
843 String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
844 if(!validateEmail.contains(SUCCESS)){
845 res += "<b>Email</b>:<i>" + validateEmail + HTML_ITALICS_LNBREAK;
854 private MicroServiceModels getAttributeObject(String name, String version) {
855 MicroServiceModels workingModel = null;
857 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
858 if(microServiceModelsData != null){
859 workingModel = (MicroServiceModels) microServiceModelsData.get(0);
862 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, "
863 + name + " was not found in the dictionary: ";
864 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
871 private void pullJsonKeyPairs(JsonNode rootNode) {
872 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
874 while (fieldsIterator.hasNext()) {
875 Map.Entry<String, JsonNode> field = fieldsIterator.next();
876 final String key = field.getKey();
877 final JsonNode value = field.getValue();
878 if (value.isContainerNode() && !value.isArray()) {
879 pullJsonKeyPairs(value); // RECURSIVE CALL
881 if (value.isArray()){
882 String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
883 mapAttribute.put(key, newValue);
885 mapAttribute.put(key, value.toString().trim());
891 private void pullModelJsonKeyPairs(JsonNode rootNode) {
892 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
894 while (fieldsIterator.hasNext()) {
895 Map.Entry<String, JsonNode> field = fieldsIterator.next();
896 final String key = field.getKey();
897 final JsonNode value = field.getValue();
899 if (value.isContainerNode() && !value.isArray()) {
900 pullModelJsonKeyPairs(value); // RECURSIVE CALL
901 } else if (value.isArray()) {
903 String stringValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]"}, new String[]{"",""});
904 ObjectMapper mapper = new ObjectMapper();
905 JsonNode newValue = mapper.readTree(stringValue);
906 pullModelJsonKeyPairs(newValue);
907 } catch (IOException e) {
908 LOGGER.info("PolicyValidation: Exception occurred while mapping string to JsonNode " + e);
911 jsonRequestMap.put(key, value.toString().trim());
917 private JsonObject stringToJsonObject(String value) {
918 try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
919 return jsonReader.readObject();
920 } catch(JsonException| IllegalStateException e){
921 LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
926 private void findRequiredFields(JsonObject json) {
928 for(Entry<String, JsonValue> keyMap : json.entrySet()){
929 Object obj = keyMap.getValue();
930 if(obj instanceof JsonObject){
931 JsonObject jsonObj = (JsonObject)obj;
932 for(Entry<String, JsonValue> jsonMap : jsonObj.entrySet()){
933 if(jsonMap.getValue().toString().contains("required-true")){
934 modelRequiredFieldsList.add(jsonMap.getKey());
938 if(keyMap.getValue().toString().contains("required-true")){
939 modelRequiredFieldsList.add(keyMap.getKey());