Merge "Copy policy-endpoints from drools-pdp to common"
[policy/engine.git] / ONAP-REST / src / main / java / org / onap / policy / rest / util / PolicyValidation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20 package org.onap.policy.rest.util;
21
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;
29 import java.util.Map;
30 import java.util.Map.Entry;
31
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;
37
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;
53
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;
58
59 @Service
60 public class PolicyValidation {
61         
62         private static final Logger LOGGER      = FlexLogger.getLogger(PolicyValidation.class);
63         
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";
82         
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<>();
86         
87         private static CommonClassDao commonClassDao;
88         
89         @Autowired
90         public PolicyValidation(CommonClassDao commonClassDao){
91                 PolicyValidation.commonClassDao = commonClassDao;
92         }
93         
94         /*
95          * This is an empty constructor
96          */
97         public PolicyValidation(){
98                 // Empty constructor
99         }
100         
101         
102         public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException{
103                 try{
104                         boolean valid = true;
105                         StringBuilder responseString = new StringBuilder();
106                         ObjectMapper mapper = new ObjectMapper();
107                         
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);
112                                         valid = false;
113                                 }
114                         }else{
115                                 responseString.append( "<b>PolicyName</b>: PolicyName Should not be empty" + HTML_ITALICS_LNBREAK);
116                                 valid = false;
117                         }
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);
122                                         valid = false;
123                                 }       
124                         }
125
126                         if(!"API".equals(policyData.getApiflag()) && policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()){
127                 for(Object attribute : policyData.getAttributes()){
128                     if(attribute instanceof LinkedHashMap<?, ?>){
129                         String value = null;
130                         String key = null;
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);
135                                 valid = false;
136                             }
137                         }else{
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>");
141                                 }
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>");
144                                 }
145                             }else{
146                                 responseString.append("<b>Component Attributes</b>:<i> has one missing Component Attribute key</i><br>");
147                             }
148                             valid = false;
149                         }
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);
156                                     }
157                                     if(BRMSPARAM.equals(policyData.getConfigPolicyType()) || BRMSRAW.equals(policyData.getConfigPolicyType())){
158                                         responseString.append("<b>Rule Attributes</b>:<i>" +  value + SPACESINVALIDCHARS);
159                                     }
160                                 }else{
161                                     responseString.append("<b>Component Attributes</b>:<i>" +  value + SPACESINVALIDCHARS);
162                                 }
163                                 valid = false;
164                             }
165                         }else{
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>");
169                                 }
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>");
172                                 }
173                             }else{
174                                 responseString.append("<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>");
175                             }
176                             valid = false;
177                         }
178                     }
179                 }
180             }
181                         
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<?, ?>){
186                         String value = null;
187                         if(((LinkedHashMap<?, ?>) attribute).get("key") == null){
188                             responseString.append("<b>Settings Attributes</b>:<i> has one missing Attribute key</i><br>");
189                             valid = false;
190                         }
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);
195                                 valid = false;
196                             }
197                         }else{
198                             responseString.append("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>");
199                             valid = false;
200                         }
201                     }
202                 }
203             }
204             
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>");
211                             valid = false;
212                         }
213                         if(((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo") == null){
214                             responseString.append(RULEALGORITHMS +  label + " : Field 2 value is not selected</i><br>");
215                             valid = false;
216                         }
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>");
221                                 valid = false;
222                             }
223                         }else{
224                             responseString.append(RULEALGORITHMS +  label + " : Field 3 value is empty</i><br>");
225                             valid = false;
226                         }
227                     }
228                 }
229             }
230             
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())) {
235                                         
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);
240                                                         valid = false;
241                                                 }
242                                         }else{
243                                                 responseString.append("<b>Onap Name</b>: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
244                                                 valid = false;
245                                         }
246                                 }
247
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);
252                                                 valid = false;
253                                         }
254                                 }else {
255                                         responseString.append("<b>RiskType</b>: Risk Type Should not be Empty" + HTML_ITALICS_LNBREAK);
256                                         valid = false;
257                                 }
258
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);
263                                                 valid = false;
264                                         }
265                                 }else {
266                                         responseString.append("<b>RiskLevel</b>: Risk Level Should not be Empty" + HTML_ITALICS_LNBREAK);
267                                         valid = false;
268                                 }
269
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);
274                                                 valid = false;
275                                         }
276                                 }else {
277                                         responseString.append("<b>Guard</b>: Guard Value Should not be Empty" + HTML_ITALICS_LNBREAK);
278                                         valid = false;
279                                 }
280                                 
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);
287                                                         valid = false;
288                                                 }
289                                         }else{
290                                                 responseString.append("Config Name: Config Name Should not be Empty" + HTML_ITALICS_LNBREAK);
291                                                 valid = false;
292                                         }
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);
297                                                         valid = false;
298                                                 }
299                                         }else{
300                                                 responseString.append("Config Type: Config Type Should not be Empty" + HTML_ITALICS_LNBREAK);
301                                                 valid = false;
302                                         }
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);
310                                                                         valid = false;
311                                                                 }
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);
315                                                                         valid = false;
316                                                                 }
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);
320                                                                         valid = false;
321                                                                 } 
322                                                         } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) {
323                                                                 responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
324                                                                 valid = false;
325                                                         }
326                                                 }
327                                         }else{
328                                                 responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
329                                                 valid = false;
330                                         }
331                                 }
332                                 
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);
339                                                         valid = false;
340                                                 }
341                                         }else{
342                                                 responseString.append("<b>Config Name</b>:<i> Config Name is required" + HTML_ITALICS_LNBREAK);
343                                                 valid = false;
344                                         }
345                                         if(policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()){
346                                                 responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + HTML_ITALICS_LNBREAK);
347                                                 valid = false;
348                                         }
349                                 }
350                                 
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);
354                                         valid = false;
355                                 }
356                                 
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());
361                                                 
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);
365                                                         valid = false;
366                                                 }
367                                         }else{
368                                                 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required" + HTML_ITALICS_LNBREAK);
369                                                 valid = false;
370                                         }
371                                 }
372                                 
373                                 // Validate ClosedLoop_PM Policy Data
374                                 if(CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())){
375                                         try{
376                                                 if(Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())){
377                                                         responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK);
378                                                         valid = false; 
379                                                 }
380                                                 
381                                         }catch(Exception e){
382                                             LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
383                                                 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK);
384                                                 valid = false;
385                                         }
386
387                                         if(policyData.getJsonBody() != null){
388                                                 
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);
394                                                                 valid = false;
395                                                         }
396                                                 }
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);
399                                                         valid = false; 
400                                                 }
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);
405                                                                 valid = false;
406                                                         }
407                                                 }
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);
416                                                                                 valid = false;
417                                                                         }
418                                                                 }
419                                                         }       
420                                                 }
421                                         }else{
422                                                 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
423                                                 valid = false;
424                                         }
425                                 }
426                                 
427                                 // Validate ClosedLoop_Fault Policy Data
428                                 if(CLOSEDLOOP_POLICY.equalsIgnoreCase(policyData.getConfigPolicyType())){
429                                         if(policyData.getJsonBody() != null){
430
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;
439                                                                 }
440                                                         } else {
441                                                                 responseString.append("<b>Conditions</b>: <i>There were no conditions provided in configBody json" + HTML_ITALICS_LNBREAK);
442                                                                 return responseString;
443                                                         }
444                                                 }else{
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>");
448                                                                         valid = false;
449                                                                 }
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>");
452                                                                         valid = false;
453                                                                 }
454                                                         }
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>");
457                                                                 valid = false;
458                                                         }
459                                                 }
460
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);
466                                                                 valid = false;
467                                                         }
468                                                 }
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);
471                                                         valid = false; 
472                                                 }
473                                                 if(faultBody.getActions() == null || faultBody.getActions().isEmpty()){
474                                                         responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
475                                                         valid = false;
476                                                 }
477                                                 if(faultBody.getClosedLoopPolicyStatus() == null || faultBody.getClosedLoopPolicyStatus().isEmpty()){
478                                                         responseString.append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
479                                                         valid = false;
480                                                 }
481                                                 if(faultBody.getConditions() == null){
482                                                         responseString.append("<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
483                                                         valid = false;
484                                                 }
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);
489                                                                 valid = false;
490                                                         }
491                                                 }
492                                                 if(faultBody.getAgingWindow() == 0){
493                                                         responseString.append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
494                                                         valid = false;
495                                                 }
496                                                 if(faultBody.getTimeInterval() == 0){
497                                                         responseString.append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
498                                                         valid = false;
499                                                 }
500                                                 if(faultBody.getRetrys() == 0){
501                                                         responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
502                                                         valid = false;
503                                                 }
504                                                 if(faultBody.getTimeOutvPRO() == 0){
505                                                         responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
506                                                         valid = false;
507                                                 }
508                                                 if(faultBody.getTimeOutRuby() == 0){
509                                                         responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
510                                                         valid = false;
511                                                 }
512                                                 if(faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()){
513                                                         responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
514                                                         valid = false;
515                                                 }
516                                         }else{
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);
529                                                 valid = false; 
530                                         }
531                                 }
532                                 
533                                 // Validate MicroServices Policy Data
534                                 if (MICROSERVICES.equals(policyData.getConfigPolicyType())){
535                                         
536                                         if(!Strings.isNullOrEmpty(policyData.getServiceType())){
537                                                 
538                                                 modelRequiredFieldsList.clear();
539                                                 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
540
541                                                 String service;
542                                                 String version;
543                                                 if (policyData.getServiceType().contains("-v")){
544                                                         service = policyData.getServiceType().split("-v")[0];
545                                                         version = policyData.getServiceType().split("-v")[1];
546                                                 }else {
547                                                         service = policyData.getServiceType();
548                                                         version = policyData.getVersion();
549                                                 }
550                                                 
551                                                 if(!Strings.isNullOrEmpty(version)) {
552                                                         MicroServiceModels returnModel = getMSModelData(service, version);
553                                                         
554                                                         if(returnModel != null) {
555                                                                 
556                                                                 String annotation = returnModel.getAnnotation();
557                                                                 String refAttributes = returnModel.getRef_attributes();
558                                                                 String subAttributes = returnModel.getSub_attributes();
559                                                                 String modelAttributes = returnModel.getAttributes();
560                                                                 
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 + ",";
571                                                                                         
572                                                                                         if(value != null) {
573                                                                                                 if (PolicyUtils.isInteger(value.replace("\"", ""))){
574                                                                                                         int result = Integer.parseInt(value.replace("\"", ""));
575                                                                                                         if (result < startNum || result > endNum){
576                                                                                                                 responseString.append(returnString);                                                                    
577                                                                                                                 valid = false;
578                                                                                                         }
579                                                                                                 }else {
580                                                                                                         responseString.append(returnString);
581                                                                                                         valid = false;
582                                                                                                 }
583                                                                                         } else {
584                                                                                                 responseString.append("<b>"+rMap.getKey()+"</b>:<i>" + rMap.getKey() 
585                                                                                                 + " is required for the MicroService model " + service + HTML_ITALICS_LNBREAK);
586                                                                                                 valid = false;
587                                                                                         }
588
589                                                                                 }
590                                                                         }
591                                                                 } else {
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);
595                                                                                 valid = false;
596                                                                         }
597                                                                         
598                                                                         if(Strings.isNullOrEmpty(policyData.getConfigName())){
599                                                                                 responseString.append("<b>Micro Service Model</b>:<i> configName is required for this model" + HTML_ITALICS_LNBREAK);
600                                                                                 valid = false;
601                                                                         }       
602                                                                         
603                                                                         if(Strings.isNullOrEmpty(policyData.getUuid())){
604                                                                                 responseString.append("<b>Micro Service Model</b>:<i> uuid is required for this model" + HTML_ITALICS_LNBREAK);
605                                                                                 valid = false;
606                                                                         }       
607                                                                         
608                                                                         if(Strings.isNullOrEmpty(policyData.getPolicyScope())){
609                                                                                 responseString.append("<b>Micro Service Model</b>:<i> policyScope is required for this model" + HTML_ITALICS_LNBREAK);
610                                                                                 valid = false;
611                                                                         }       
612                                                                 }
613                                                                 
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);
621                                                                         }
622                                                                         
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);
629                                                                                 } else {
630                                                                                         modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
631                                                                                 }
632                                                                                 String json = new ObjectMapper().writeValueAsString(modelAttributesMap);
633                                                                                 findRequiredFields(stringToJsonObject(json));
634                                                                         }
635                                                                         
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);
642                                                                                 } else {
643                                                                                         refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
644                                                                                 }
645                                                                                 String json = new ObjectMapper().writeValueAsString(refAttributesMap);
646                                                                                 findRequiredFields(stringToJsonObject(json));
647                                                                         }
648                                                                         
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);
654                                                                                 
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);
663                                                                                                         valid = false; 
664                                                                                                 }
665                                                                                         } else {
666                                                                                                 responseString.append("<b>Micro Service Model</b>:<i> " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
667                                                                                                 valid = false; 
668                                                                                         }
669                                                                                 }
670                                                                         }
671                                                                 }                                                               
672                                                         } else {
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);
675                                                                 valid = false;
676                                                         }
677                                                 } else {
678                                                         responseString.append("<b>Micro Service Version</b>:<i> Micro Service Version is required" + HTML_ITALICS_LNBREAK);
679                                                         valid = false;
680                                                 }
681                                         } else {
682                                                 responseString.append("<b>Micro Service</b>:<i> Micro Service Model is required" + HTML_ITALICS_LNBREAK);
683                                                 valid = false;
684                                         }
685
686                                         if(Strings.isNullOrEmpty(policyData.getPriority())){
687                                                 responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
688                                                 valid = false;
689                                         }
690                                 }
691                                 
692                                 // Validate Optimization Policy Data
693                                 if (OPTIMIZATION.equals(policyData.getConfigPolicyType())){
694                                         
695                                         if(!Strings.isNullOrEmpty(policyData.getServiceType())){
696                                                 
697                                                 modelRequiredFieldsList.clear();
698                                                 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
699
700                                                 String service;
701                                                 String version;
702                                                 if (policyData.getServiceType().contains("-v")){
703                                                         service = policyData.getServiceType().split("-v")[0];
704                                                         version = policyData.getServiceType().split("-v")[1];
705                                                 }else {
706                                                         service = policyData.getServiceType();
707                                                         version = policyData.getVersion();
708                                                 }
709                                                 
710                                                 if(!Strings.isNullOrEmpty(version)) {
711                                                         OptimizationModels returnModel = getOptimizationModelData(service, version);
712                                                         
713                                                         if(returnModel != null) {
714                                                                 
715                                                                 String annotation = returnModel.getAnnotation();
716                                                                 String refAttributes = returnModel.getRefattributes();
717                                                                 String subAttributes = returnModel.getSubattributes();
718                                                                 String modelAttributes = returnModel.getAttributes();
719                                                                 
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 + ",";
730                                                                                         
731                                                                                         if(value != null) {
732                                                                                                 if (PolicyUtils.isInteger(value.replace("\"", ""))){
733                                                                                                         int result = Integer.parseInt(value.replace("\"", ""));
734                                                                                                         if (result < startNum || result > endNum){
735                                                                                                                 responseString.append(returnString);                                                                    
736                                                                                                                 valid = false;
737                                                                                                         }
738                                                                                                 }else {
739                                                                                                         responseString.append(returnString);
740                                                                                                         valid = false;
741                                                                                                 }
742                                                                                         } else {
743                                                                                                 responseString.append("<b>"+rMap.getKey()+"</b>:<i>" + rMap.getKey() 
744                                                                                                 + " is required for the Optimization model " + service + HTML_ITALICS_LNBREAK);
745                                                                                                 valid = false;
746                                                                                         }
747
748                                                                                 }
749                                                                         }
750                                                                 }
751                                                                 
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);
759                                                                         }
760                                                                         
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);
767                                                                                 } else {
768                                                                                         modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
769                                                                                 }
770                                                                                 String json = new ObjectMapper().writeValueAsString(modelAttributesMap);
771                                                                                 findRequiredFields(stringToJsonObject(json));
772                                                                         }
773                                                                         
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);
780                                                                                 } else {
781                                                                                         refAttributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
782                                                                                 }
783                                                                                 String json = new ObjectMapper().writeValueAsString(refAttributesMap);
784                                                                                 findRequiredFields(stringToJsonObject(json));
785                                                                         }
786                                                                         
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);
792                                                                                 
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);
801                                                                                                         valid = false; 
802                                                                                                 }
803                                                                                         } else {
804                                                                                                 responseString.append("<b>Optimization Service Model</b>:<i> " + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
805                                                                                                 valid = false; 
806                                                                                         }
807                                                                                 }
808                                                                         }
809                                                                 }                                                               
810                                                         } else {
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);
813                                                                 valid = false;
814                                                         }
815                                                 } else {
816                                                         responseString.append("<b>Optimization Service Version</b>:<i> Optimization Service Version is required" + HTML_ITALICS_LNBREAK);
817                                                         valid = false;
818                                                 }
819                                         } else {
820                                                 responseString.append("<b>Optimization Service</b>:<i> Optimization Service Model is required" + HTML_ITALICS_LNBREAK);
821                                                 valid = false;
822                                         }
823
824                                         if(Strings.isNullOrEmpty(policyData.getPriority())){
825                                                 responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
826                                                 valid = false;
827                                         }
828                                 }       
829                         }
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);
835                                                 valid = false;
836                                         }
837                                 }else{
838                                         responseString.append("Onap Name: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
839                                         valid = false;
840                                 }
841
842                                 if("Rainy_Day".equals(policyData.getRuleProvider())){
843                                         if(policyData.getRainyday()==null){
844                                                 responseString.append("<b> Rainy Day Parameters are Required </b><br>");
845                                                 valid = false;
846                                         }else{
847                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getServiceType())){
848                                                         responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
849                                                         valid = false;
850                                                 }
851                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getVnfType())){
852                                                         responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
853                                                         valid = false;
854                                                 }                                               
855                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getBbid())){
856                                                         responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
857                                                         valid = false;
858                                                 }
859                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getWorkstep())){
860                                                         responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
861                                                         valid = false;
862                                                 }
863                                                 if(!policyData.getRainyday().getTreatmentTableChoices().isEmpty() &&
864                                                                 policyData.getRainyday().getTreatmentTableChoices() != null){
865                                                         
866                                                         for(Object treatmentMap: policyData.getRainyday().getTreatmentTableChoices()){
867                                                                 String errorCode = null;
868                                                                 String treatment = null;
869                                                                 if(treatmentMap instanceof LinkedHashMap<?, ?>){
870                                                                         
871                                                                         if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("errorcode")){
872                                                                                 errorCode = ((LinkedHashMap<?, ?>) treatmentMap).get("errorcode").toString();
873                                                                         }
874                                                                         if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("treatment")){
875                                                                                 treatment = ((LinkedHashMap<?, ?>) treatmentMap).get("treatment").toString();
876                                                                         }
877                                                                         
878                                                                 }
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>");
881                                                                         valid = false;
882                                                                         break;
883                                                                 }
884                                                                 if(Strings.isNullOrEmpty(errorCode)){
885                                                                         responseString.append("Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
886                                                                         valid = false;
887                                                                         break;
888                                                                 }
889                                                                 if(Strings.isNullOrEmpty(treatment)){
890                                                                         responseString.append("Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
891                                                                         valid = false;
892                                                                         break;
893                                                                 }
894                                                         }
895                                                         
896                                                 } else {
897                                                         responseString.append("Rainy Day <b>Desired Automated Treatments</b> are Required<br>");
898                                                         valid = false;
899                                                 }
900                                         }
901                                 }
902                                 
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);
906                                                 valid = false;
907                                         }else{
908                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getActor())){
909                                                         responseString.append("Guard Params <b>Actor</b> is Required " + HTML_ITALICS_LNBREAK);
910                                                         valid = false;
911                                                 }
912                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())){
913                                                         responseString.append("Guard Params <b>Recipe</b> is Required " + HTML_ITALICS_LNBREAK);
914                                                         valid = false;
915                                                 }
916                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())){
917                                                         responseString.append("Guard Params <b>Guard Active Start</b> is Required " + HTML_ITALICS_LNBREAK);
918                                                         valid = false;
919                                                 }
920                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())){
921                                                         responseString.append("Guard Params <b>Guard Active End</b> is Required " + HTML_ITALICS_LNBREAK);
922                                                         valid = false;
923                                                 }
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);
927                                                                 valid = false;
928                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
929                                                                 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + HTML_ITALICS_LNBREAK);
930                                                                 valid = false;
931                                                         }
932                                                         if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())){
933                                                                 responseString.append("Guard Params <b>Time Window</b> is Required" + HTML_ITALICS_LNBREAK);
934                                                                 valid = false;
935                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
936                                                                 responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + HTML_ITALICS_LNBREAK);
937                                                                 valid = false;
938                                                         }
939                                                         if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())){
940                                                                 responseString.append("Guard Params <b>Time Units</b> is Required" + HTML_ITALICS_LNBREAK);
941                                                                 valid = false;
942                                                         }
943                                                 } else if ("GUARD_BL_YAML".equals(policyData.getRuleProvider())
944                                 && "Use Manual Entry".equals(policyData.getBlackListEntryType())) {
945                             if (policyData.getYamlparams().getBlackList() == null
946                                     || policyData.getYamlparams().getBlackList().isEmpty()) {
947                                 responseString
948                                         .append(" Guard Params <b>BlackList</b> is Required " + HTML_ITALICS_LNBREAK);
949                                 valid = false;
950                             } else {
951                                 for (String blackList : policyData.getYamlparams().getBlackList()) {
952                                     if (blackList == null
953                                             || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))) {
954                                         responseString.append(" Guard Params <b>BlackList</b> Should be valid String"
955                                                 + HTML_ITALICS_LNBREAK);
956                                         valid = false;
957                                         break;
958                                     }
959                                 }
960                             }
961                         }
962                                         }
963                                 }
964                         }
965
966                         if(ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
967                                 if(!Strings.isNullOrEmpty(policyData.getActionPerformer())){
968                                         String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
969                                         if(!actionPerformer.contains(SUCCESS)){
970                                                 responseString.append("<b>ActionPerformer</b>:<i>" +  actionPerformer + HTML_ITALICS_LNBREAK);
971                                                 valid = false;
972                                         }
973                                 }else{
974                                         responseString.append("<b>ActionPerformer</b>:<i> ActionPerformer Should not be empty" + HTML_ITALICS_LNBREAK);
975                                         valid = false;
976                                 }
977         
978                                 if(!Strings.isNullOrEmpty(policyData.getActionAttributeValue())){
979                                         String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
980                                         if(!actionAttribute.contains(SUCCESS)){
981                                                 responseString.append("<b>ActionAttribute</b>:<i>" +  actionAttribute + HTML_ITALICS_LNBREAK);
982                                                 valid = false;
983                                         }
984                                 }else{
985                                         responseString.append("<b>ActionAttribute</b>:<i> ActionAttribute Should not be empty" + HTML_ITALICS_LNBREAK);
986                                         valid = false;
987                                 }
988                         }
989
990                         if(CONFIG_POLICY.equals(policyData.getPolicyType())){
991                                 String value = "";
992                                 if(valid){
993                                         if(commonClassDao!=null){
994                                                 List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
995                                                 if (!spData.isEmpty()){
996                                                         SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
997                                                         value = "<b>Message</b>:<i>" +  safePolicyWarningData.getMessage() +"</i>";
998                                                 }
999                                         }
1000                                         responseString.append(SUCCESS + "@#"+ value);
1001                                 }
1002                         }else{
1003                                 if(valid){
1004                                         responseString.append(SUCCESS);
1005                                 }
1006                         }
1007
1008                         return responseString;
1009                 }
1010                 catch (Exception e){
1011                         LOGGER.error("Exception Occured during Policy Validation" +e);
1012                         return null;
1013                 }
1014         }
1015
1016         protected String emailValidation(String email, String response){
1017                 String res = response;
1018                 if(email != null){
1019                         String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
1020                         if(!validateEmail.contains(SUCCESS)){
1021                                 res  += "<b>Email</b>:<i>" +  validateEmail + HTML_ITALICS_LNBREAK;
1022                         }
1023                         else {
1024                                 return SUCCESS;
1025                         }
1026                 }
1027                 return res;
1028         }
1029
1030         private MicroServiceModels getMSModelData(String name, String version) {        
1031                 MicroServiceModels workingModel = null;
1032                 try{
1033                         List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
1034                         if(microServiceModelsData != null){
1035                                 workingModel = (MicroServiceModels) microServiceModelsData.get(0);
1036                         }
1037                 }catch(Exception e){
1038                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template.  The template name, " 
1039                     + name + " was not found in the dictionary: ";
1040                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
1041                         return null;
1042                 }
1043
1044                 return workingModel;
1045         }
1046         
1047         private OptimizationModels getOptimizationModelData(String name, String version) {      
1048                 OptimizationModels workingModel = null;
1049                 try{
1050                         List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, "modelName:version", name+":"+version);
1051                         if(optimizationModelsData != null){
1052                                 workingModel = (OptimizationModels) optimizationModelsData.get(0);
1053                         }
1054                 }catch(Exception e){
1055                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template.  The template name, " 
1056                     + name + " was not found in the dictionary: ";
1057                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
1058                         return null;
1059                 }
1060
1061                 return workingModel;
1062         }
1063
1064         private void pullJsonKeyPairs(JsonNode rootNode) {
1065                 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
1066
1067                 while (fieldsIterator.hasNext()) {
1068                         Map.Entry<String, JsonNode> field = fieldsIterator.next();
1069                         final String key = field.getKey();
1070                         final JsonNode value = field.getValue();
1071                         if (value.isContainerNode() && !value.isArray()) {
1072                                 pullJsonKeyPairs(value); // RECURSIVE CALL
1073                         } else {
1074                                 if (value.isArray()){
1075                                         String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
1076                                         mapAttribute.put(key, newValue);
1077                                 }else {
1078                                         mapAttribute.put(key, value.toString().trim());
1079                                 }
1080                         }
1081                 }
1082         }
1083         
1084         private void pullModelJsonKeyPairs(JsonNode rootNode) {
1085                 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
1086                 
1087                 while (fieldsIterator.hasNext()) {
1088                         Map.Entry<String, JsonNode> field = fieldsIterator.next();
1089                         final String key = field.getKey();
1090                         final JsonNode value = field.getValue();
1091                         
1092                         if (value.isContainerNode() && !value.isArray()) {
1093                                 jsonRequestMap.put(key, "containerNode");
1094                                 pullModelJsonKeyPairs(value); // RECURSIVE CALL
1095                         } else if (value.isArray()) {
1096                                 try {
1097                                         jsonRequestMap.put(key, "array");
1098                                         String stringValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]"}, new String[]{"",""});
1099                                         ObjectMapper mapper = new ObjectMapper();
1100                                         JsonNode newValue = mapper.readTree(stringValue);
1101                                         pullModelJsonKeyPairs(newValue);
1102                                 } catch (IOException e) {
1103                                         LOGGER.info("PolicyValidation: Exception occurred while mapping string to JsonNode " + e);
1104                                 }
1105                         } else {
1106                                 jsonRequestMap.put(key, value.toString().trim());
1107                         }
1108                 }                               
1109         }
1110         
1111     private JsonObject stringToJsonObject(String value) {
1112         try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
1113             return jsonReader.readObject();
1114         } catch(JsonException| IllegalStateException e){
1115             LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
1116             return null;
1117         }
1118     }
1119     
1120     private void findRequiredFields(JsonObject json) {
1121
1122         for(Entry<String, JsonValue> keyMap : json.entrySet()){
1123                 Object obj = keyMap.getValue();
1124                 if(obj instanceof JsonObject){
1125                         JsonObject jsonObj = (JsonObject)obj;
1126                         for(Entry<String, JsonValue> jsonMap : jsonObj.entrySet()){
1127                                 if(jsonMap.getValue().toString().contains("required-true")){
1128                                         modelRequiredFieldsList.add(jsonMap.getKey());
1129                                 }
1130                         }
1131                 } else {
1132                         if(keyMap.getValue().toString().contains("required-true")){
1133                                 modelRequiredFieldsList.add(keyMap.getKey());
1134                         }
1135                 }
1136         }
1137                 
1138     }
1139
1140 }