223381afe84033dc08225aed1ec3e92cd35c72e5
[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 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.util.HashMap;
24 import java.util.Iterator;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29
30 import org.apache.commons.lang.StringUtils;
31 import org.json.JSONObject;
32 import org.onap.policy.common.logging.flexlogger.FlexLogger;
33 import org.onap.policy.common.logging.flexlogger.Logger;
34 import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
35 import org.onap.policy.rest.adapter.ClosedLoopPMBody;
36 import org.onap.policy.rest.adapter.PolicyRestAdapter;
37 import org.onap.policy.rest.dao.CommonClassDao;
38 import org.onap.policy.rest.jpa.MicroServiceModels;
39 import org.onap.policy.rest.jpa.SafePolicyWarning;
40 import org.onap.policy.utils.PolicyUtils;
41 import org.onap.policy.xacml.api.XACMLErrorConstants;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Service;
44
45 import com.fasterxml.jackson.databind.JsonNode;
46 import com.fasterxml.jackson.databind.ObjectMapper;
47 import com.google.common.base.Splitter;
48 import com.google.common.base.Strings;
49
50 @Service
51 public class PolicyValidation {
52         
53         private static final Logger LOGGER      = FlexLogger.getLogger(PolicyValidation.class);
54         
55         public static final String CONFIG_POLICY = "Config";
56         public static final String ACTION_POLICY = "Action";
57         public static final String DECISION_POLICY = "Decision";
58         public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
59         public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
60         public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
61         public static final String MICROSERVICES="Micro Service";
62         public static final String FIREWALL="Firewall Config";
63         
64         private static Map<String, String> mapAttribute = new HashMap<>();
65         
66         private static CommonClassDao commonClassDao;
67         
68         @Autowired
69         public PolicyValidation(CommonClassDao commonClassDao){
70                 PolicyValidation.commonClassDao = commonClassDao;
71         }
72         
73         /*
74          * This is an empty constructor
75          */
76         public PolicyValidation(){}     
77         
78         
79         public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException{
80                 try{
81                         boolean valid = true;
82                         StringBuilder responseString = new StringBuilder();
83                         ObjectMapper mapper = new ObjectMapper();
84                         
85                         if(policyData.getPolicyName() != null){
86                                 String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
87                                 if(!policyNameValidate.contains("success")){
88                                         responseString.append("PolicyName:" +  policyNameValidate + "<br>");
89                                         valid = false;
90                                 };
91                         }else{
92                                 responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
93                                 valid = false;
94                         }
95                         if(policyData.getPolicyDescription() != null){
96                                 String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
97                                 if(!descriptionValidate.contains("success")){
98                                         responseString.append("Description:" +  descriptionValidate + "<br>");
99                                         valid = false;
100                                 }       
101                         }
102
103                         if(CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
104                                 if ("Base".equals(policyData.getConfigPolicyType()) || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
105                                                 ||  CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType()) || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType()) 
106                                                 || MICROSERVICES.equals(policyData.getConfigPolicyType())) {
107                                         
108                                         if(!Strings.isNullOrEmpty(policyData.getOnapName())) {
109                                                 String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
110                                                 if(!onapNameValidate.contains("success")){
111                                                         responseString.append("OnapName:" +  onapNameValidate + "<br>");
112                                                         valid = false;
113                                                 }
114                                         }else{
115                                                 responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
116                                                 valid = false;
117                                         }
118                                 }
119
120                                 if(!Strings.isNullOrEmpty(policyData.getRiskType())) {
121                                         String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
122                                         if(!riskTypeValidate.contains("success")){
123                                                 responseString.append("RiskType:" +  riskTypeValidate + "<br>");
124                                                 valid = false;
125                                         }
126                                 }else {
127                                         responseString.append("Risk Type: Risk Type Should not be Empty" + "<br>");
128                                         valid = false;
129                                 }
130
131                                 if(!Strings.isNullOrEmpty(policyData.getRiskLevel())) {
132                                         String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
133                                         if(!validateRiskLevel.contains("success")){
134                                                 responseString.append("RiskLevel:" +  validateRiskLevel + "<br>");
135                                                 valid = false;
136                                         }
137                                 }else {
138                                         responseString.append("Risk Level: Risk Level Should not be Empty" + "<br>");
139                                         valid = false;
140                                 }
141
142                                 if(!Strings.isNullOrEmpty(policyData.getGuard())) {
143                                         String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
144                                         if(!validateGuard.contains("success")){
145                                                 responseString.append("Guard:" +  validateGuard + "<br>");
146                                                 valid = false;
147                                         }
148                                 }else {
149                                         responseString.append("Guard: Guard Value Should not be Empty" + "<br>");
150                                         valid = false;
151                                 }
152
153                                 if("Base".equalsIgnoreCase(policyData.getConfigPolicyType())){
154                                         if(!Strings.isNullOrEmpty(policyData.getConfigName())) {
155                                                 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
156                                                 if(!configNameValidate.contains("success")){
157                                                         responseString.append("ConfigName:" +  configNameValidate + "<br>");
158                                                         valid = false;
159                                                 }
160                                         }else{
161                                                 responseString.append("Config Name: Config Name Should not be Empty" + "<br>");
162                                                 valid = false;
163                                         }
164                                         if(!Strings.isNullOrEmpty(policyData.getConfigType())) {
165                                                 String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
166                                                 if(!configTypeValidate.contains("success")){
167                                                         responseString.append("ConfigType:" +  configTypeValidate + "<br>");
168                                                         valid = false;
169                                                 }
170                                         }else{
171                                                 responseString.append("Config Type: Config Type Should not be Empty" + "<br>");
172                                                 valid = false;
173                                         }
174                                         if(!Strings.isNullOrEmpty(policyData.getConfigBodyData())) {
175                                                 String configBodyData = policyData.getConfigBodyData();
176                                                 String configType = policyData.getConfigType();
177                                                 if (configType != null) {
178                                                         if (configType.equals("JSON")) {
179                                                                 if (!PolicyUtils.isJSONValid(configBodyData)) {
180                                                                         responseString.append("Config Body: JSON Content is not valid" + "<br>");
181                                                                         valid = false;
182                                                                 }
183                                                         } else if (configType.equals("XML")) {
184                                                                 if (!PolicyUtils.isXMLValid(configBodyData)) {
185                                                                         responseString.append("Config Body: XML Content data is not valid" + "<br>");
186                                                                         valid = false;
187                                                                 }
188                                                         } else if (configType.equals("PROPERTIES")) {
189                                                                 if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
190                                                                         responseString.append("Config Body: Property data is not valid" + "<br>");
191                                                                         valid = false;
192                                                                 } 
193                                                         } else if (configType.equals("OTHER")) {
194                                                                 if (configBodyData.equals("")) {
195                                                                         responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
196                                                                         valid = false;
197                                                                 }
198                                                         }
199                                                 }
200                                         }else{
201                                                 responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
202                                                 valid = false;
203                                         }
204                                 }
205
206                                 if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
207                                         if(policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()){
208                                                 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
209                                                 if(!configNameValidate.contains("success")){
210                                                         responseString.append("<b>ConfigName</b>:<i>" +  configNameValidate + "</i><br>");
211                                                         valid = false;
212                                                 }
213                                         }else{
214                                                 responseString.append("<b>Config Name</b>:<i> Config Name is required" + "</i><br>");
215                                                 valid = false;
216                                         }
217                                         if(policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()){
218                                                 responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>");
219                                                 valid = false;
220                                         }
221                                 }
222                                 if("BRMS_Param".equalsIgnoreCase(policyData.getConfigPolicyType())){
223                                         if(policyData.getRuleName() == null || policyData.getRuleName().isEmpty()){
224                                                 responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required</i><br>");
225                                                 valid = false;
226                                         }
227                                 }
228                                 if("BRMS_Raw".equalsIgnoreCase(policyData.getConfigPolicyType())){
229                                         if(policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()){
230                                                 String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
231                                                 
232                                                 // If there are any error other than Annotations then this is not Valid
233                                                 if(message.contains("[ERR")){
234                                                         responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>");
235                                                         valid = false;
236                                                 }
237                                         }else{
238                                                 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required</i><br>");
239                                                 valid = false;
240                                         }
241                                 }
242                                 if("ClosedLoop_PM".equalsIgnoreCase(policyData.getConfigPolicyType())){
243                                         try{
244                                                 if(Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())){
245                                                         responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
246                                                         valid = false; 
247                                                 }
248                                                 
249                                         }catch(Exception e){
250                                             LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
251                                                 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
252                                                 valid = false;
253                                         }
254
255                                         if(policyData.getJsonBody() != null){
256                                                 ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class);
257                                                 if(pmBody.getEmailAddress() != null){
258                                                         String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
259                                                         if(result != "success"){
260                                                                 responseString.append(result + "<br>");
261                                                                 valid = false;
262                                                         }
263                                                 }
264                                                 if((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS() || pmBody.isvUSP()) != true){
265                                                         responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services</i><br>");
266                                                         valid = false; 
267                                                 }
268                                                 if(pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()){
269                                                         String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
270                                                         if(!result.contains("success")){
271                                                                 responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
272                                                                 valid = false;
273                                                         };
274                                                 }
275                                                 if(pmBody.getAttributes() != null && !pmBody.getAttributes().isEmpty()){
276                                                         for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
277                                                                 String key = entry.getKey();
278                                                                 String value = entry.getValue();
279                                                                 if(!key.contains("Message")){
280                                                                         String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
281                                                                         if(!attributeValidate.contains("success")){
282                                                                                 responseString.append("<b>Attributes</b>:<i>" +  key + " : value has spaces or invalid characters</i><br>");
283                                                                                 valid = false;
284                                                                         };
285                                                                 }
286                                                         }       
287                                                 }
288                                         }else{
289                                                 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
290                                                 valid = false;
291                                         }
292                                 }
293                                 if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
294                                         if(policyData.getJsonBody() != null){
295
296                                                 // For API we need to get the conditions key from the Json request and check it before deserializing to POJO due to the enum
297                                                 if("API".equals(policyData.getApiflag())){
298                                                         JSONObject json = new JSONObject(policyData.getJsonBody());
299                                                         if(!json.isNull("conditions")){
300                                                                 String apiCondition = (String) json.get("conditions");
301                                                                 if(Strings.isNullOrEmpty(apiCondition)){
302                                                                         responseString.append("<b>Conditions</b>: <i>Select At least one Condition</i><br>");
303                                                                         return responseString;
304                                                                 }
305                                                         } else {
306                                                                 responseString.append("<b>Conditions</b>: <i>There were no conditions provided in configBody json</i><br>");
307                                                                 return responseString;
308                                                         }
309                                                 }
310
311                                                 ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class);
312                                                 if(faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()){
313                                                         String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
314                                                         if(result != "success"){
315                                                                 responseString.append(result+ "<br>");
316                                                                 valid = false;
317                                                         }
318                                                 }
319                                                 if((faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
320                                                         responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services</i><br>");
321                                                         valid = false; 
322                                                 }
323                                                 if(faultBody.getActions() == null || faultBody.getActions().isEmpty()){
324                                                         responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required</i><br>");
325                                                         valid = false;
326                                                 }
327                                                 if(faultBody.getClosedLoopPolicyStatus() == null || faultBody.getClosedLoopPolicyStatus().isEmpty()){
328                                                         responseString.append("<b>Policy Status</b>: <i>Policy Status is required</i><br>");
329                                                         valid = false;
330                                                 }
331                                                 if(faultBody.getConditions() == null){
332                                                         responseString.append("<b>Conditions</b>: <i>Select At least one Condition</i><br>");
333                                                         valid = false;
334                                                 }
335                                                 if(faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()){
336                                                         String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
337                                                         if(!result.contains("success")){
338                                                                 responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
339                                                                 valid = false;
340                                                         }
341                                                 }
342                                                 if(faultBody.getAgingWindow() == 0){
343                                                         responseString.append("<b>Aging Window</b>: <i>Aging Window is required</i><br>");
344                                                         valid = false;
345                                                 }
346                                                 if(faultBody.getTimeInterval() == 0){
347                                                         responseString.append("<b>Time Interval</b>: <i>Time Interval is required</i><br>");
348                                                         valid = false;
349                                                 }
350                                                 if(faultBody.getRetrys() == 0){
351                                                         responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required</i><br>");
352                                                         valid = false;
353                                                 }
354                                                 if(faultBody.getTimeOutvPRO() == 0){
355                                                         responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required</i><br>");
356                                                         valid = false;
357                                                 }
358                                                 if(faultBody.getTimeOutRuby() == 0){
359                                                         responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required</i><br>");
360                                                         valid = false;
361                                                 }
362                                                 if(faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()){
363                                                         responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required</i><br>");
364                                                         valid = false;
365                                                 }
366                                         }else{
367                                                 responseString.append("<b>D2/Virtualized Services</b>: <i>Select atleast one D2/Virtualized Services</i><br>");
368                                                 responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required</i><br>");
369                                                 responseString.append("<b>Aging Window</b>: <i>Aging Window is required</i><br>");
370                                                 responseString.append("<b>Policy Status</b>: <i>Policy Status is required</i><br>");
371                                                 responseString.append("<b>Conditions</b>: <i>Select Atleast one Condition</i><br>");
372                                                 responseString.append("<b>PEP Name</b>: <i>PEP Name is required</i><br>");
373                                                 responseString.append("<b>PEP Action</b>: <i>PEP Action is required</i><br>");
374                                                 responseString.append("<b>Time Interval</b>: <i>Time Interval is required</i><br>");
375                                                 responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required</i><br>");
376                                                 responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required</i><br>");
377                                                 responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required</i><br>");
378                                                 responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required</i><br>");
379                                                 valid = false; 
380                                         }
381                                 }
382
383                                 if ("Micro Service".equals(policyData.getConfigPolicyType())){
384                                         if(!Strings.isNullOrEmpty(policyData.getServiceType())){
385                                                 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
386                                                 MicroServiceModels returnModel = new MicroServiceModels();
387                                                 String service = null;
388                                                 String version = null;
389                                                 if (policyData.getServiceType().contains("-v")){
390                                                         service = policyData.getServiceType().split("-v")[0];
391                                                         version = policyData.getServiceType().split("-v")[1];
392                                                 }else {
393                                                         service = policyData.getServiceType();
394                                                         version = policyData.getVersion();
395                                                 }
396                                                 
397                                                 if(!Strings.isNullOrEmpty(version)) {
398                                                         returnModel = getAttributeObject(service, version);
399                                                         
400                                                         if(returnModel != null) {
401                                                                 String annotation = returnModel.getAnnotation();
402                                                                 if (!Strings.isNullOrEmpty(annotation)){ 
403                                                                         Map<String, String> rangeMap = new HashMap<>();
404                                                                         rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
405                                                                         for (Entry<String, String> rMap : rangeMap.entrySet()){
406                                                                                 if (rMap.getValue().contains("range::")){
407                                                                                         String value = mapAttribute.get(rMap.getKey().trim());
408                                                                                         String[] tempString = rMap.getValue().split("::")[1].split("-");
409                                                                                         int startNum = Integer.parseInt(tempString[0]);
410                                                                                         int endNum = Integer.parseInt(tempString[1]);
411                                                                                         String returnString = "InvalidreturnModel Range:" + rMap.getKey() + " must be between " 
412                                                                                                         + startNum + " - "  + endNum + ",";
413                                                                                         
414                                                                                         if(value != null) {
415                                                                                                 if (PolicyUtils.isInteger(value.replace("\"", ""))){
416                                                                                                         int result = Integer.parseInt(value.replace("\"", ""));
417                                                                                                         if (result < startNum || result > endNum){
418                                                                                                                 responseString.append(returnString);                                                                    
419                                                                                                                 valid = false;
420                                                                                                         }
421                                                                                                 }else {
422                                                                                                         responseString.append(returnString);
423                                                                                                         valid = false;
424                                                                                                 }
425                                                                                         } else {
426                                                                                                 responseString.append("<b>"+rMap.getKey()+"</b>:<i>" + rMap.getKey() 
427                                                                                                 + " is required for the MicroService model " + service + "</i><br>");
428                                                                                                 valid = false;
429                                                                                         }
430
431                                                                                 }
432                                                                         }
433                                                                 }
434                                                         } else {
435                                                                 responseString.append("<b>Micro Service Model</b>:<i> Invalid Model. The model name, " + service + 
436                                                                                 " of version, " + version + " was not found in the dictionary</i><br>");
437                                                                 valid = false;
438                                                         }
439                                                 } else {
440                                                         responseString.append("<b>Micro Version</b>:<i> Micro Service Version is required" + "</i><br>");
441                                                         valid = false;
442                                                 }
443                                         } else {
444                                                 responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
445                                                 valid = false;
446                                         }
447
448                                         if(Strings.isNullOrEmpty(policyData.getPriority())){
449                                                 responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
450                                                 valid = false;
451                                         }
452                                 }       
453                         }
454                         if (DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
455                                 if(!Strings.isNullOrEmpty(policyData.getOnapName())){
456                                         String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
457                                         if(!onapNameValidate.contains("success")){
458                                                 responseString.append("OnapName:" +  onapNameValidate + "<br>");
459                                                 valid = false;
460                                         }
461                                 }else{
462                                         responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
463                                         valid = false;
464                                 }
465
466                                 if("Rainy_Day".equals(policyData.getRuleProvider())){
467                                         if(policyData.getRainyday()==null){
468                                                 responseString.append("<b> Rainy Day Parameters are Required </b><br>");
469                                                 valid = false;
470                                         }else{
471                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getServiceType())){
472                                                         responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
473                                                         valid = false;
474                                                 }
475                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getVnfType())){
476                                                         responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
477                                                         valid = false;
478                                                 }                                               
479                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getBbid())){
480                                                         responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
481                                                         valid = false;
482                                                 }
483                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getWorkstep())){
484                                                         responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
485                                                         valid = false;
486                                                 }
487                                                 if(!policyData.getRainyday().getTreatmentTableChoices().isEmpty() &&
488                                                                 policyData.getRainyday().getTreatmentTableChoices() != null){
489                                                         
490                                                         for(Object treatmentMap: policyData.getRainyday().getTreatmentTableChoices()){
491                                                                 String errorCode = null;
492                                                                 String treatment = null;
493                                                                 if(treatmentMap instanceof LinkedHashMap<?, ?>){
494                                                                         
495                                                                         if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("errorcode")){
496                                                                                 errorCode = ((LinkedHashMap<?, ?>) treatmentMap).get("errorcode").toString();
497                                                                         }
498                                                                         if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("treatment")){
499                                                                                 treatment = ((LinkedHashMap<?, ?>) treatmentMap).get("treatment").toString();
500                                                                         }
501                                                                         
502                                                                 }
503                                                                 if(Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)){
504                                                                         responseString.append("Rainy Day <b>Error Code</b> and <b>Desired Treatment</b> cannot be empty<br>");
505                                                                         valid = false;
506                                                                         break;
507                                                                 }
508                                                                 if(Strings.isNullOrEmpty(errorCode)){
509                                                                         responseString.append("Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
510                                                                         valid = false;
511                                                                         break;
512                                                                 }
513                                                                 if(Strings.isNullOrEmpty(treatment)){
514                                                                         responseString.append("Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
515                                                                         valid = false;
516                                                                         break;
517                                                                 }
518                                                         }
519                                                         
520                                                 } else {
521                                                         responseString.append("Rainy Day <b>Desired Automated Treatments</b> are Required<br>");
522                                                         valid = false;
523                                                 }
524                                         }
525                                 }
526                                 
527                                 if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
528                                         if(policyData.getYamlparams()==null){
529                                                 responseString.append("<b> Guard Params are Required </b>" + "<br>");
530                                                 valid = false;
531                                         }else{
532                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getActor())){
533                                                         responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
534                                                         valid = false;
535                                                 }
536                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())){
537                                                         responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
538                                                         valid = false;
539                                                 }
540                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())){
541                                                         responseString.append("Guard Params <b>Guard Active Start</b> is Required " + "<br>");
542                                                         valid = false;
543                                                 }
544                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())){
545                                                         responseString.append("Guard Params <b>Guard Active End</b> is Required " + "<br>");
546                                                         valid = false;
547                                                 }
548                                                 if("GUARD_YAML".equals(policyData.getRuleProvider())){
549                                                         if(Strings.isNullOrEmpty(policyData.getYamlparams().getLimit())){
550                                                                 responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
551                                                                 valid = false;
552                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
553                                                                 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
554                                                                 valid = false;
555                                                         }
556                                                         if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())){
557                                                                 responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
558                                                                 valid = false;
559                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
560                                                                 responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + "<br>");
561                                                                 valid = false;
562                                                         }
563                                                         if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())){
564                                                                 responseString.append("Guard Params <b>Time Units</b> is Required" + "<br>");
565                                                                 valid = false;
566                                                         }
567                                                 }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
568                                                         if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
569                                                                 responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
570                                                                 valid = false;
571                                                         }else{
572                                                                 for(String blackList: policyData.getYamlparams().getBlackList()){
573                                                                         if(blackList==null || !("success".equals(PolicyUtils.policySpecialCharValidator(blackList)))){
574                                                                                 responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
575                                                                                 valid = false;
576                                                                                 break;
577                                                                         }
578                                                                 }
579                                                         }
580                                                 }
581                                         }
582                                 }
583                         }
584
585                         if(ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
586                                 if(!Strings.isNullOrEmpty(policyData.getActionPerformer())){
587                                         String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
588                                         if(!actionPerformer.contains("success")){
589                                                 responseString.append("ActionPerformer:" +  actionPerformer + "<br>");
590                                                 valid = false;
591                                         }
592                                 }else{
593                                         responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
594                                         valid = false;
595                                 }
596                                 if(policyData.getAttributes() != null){
597                                         for(Object attribute : policyData.getAttributes()){
598                                                 if(attribute instanceof LinkedHashMap<?, ?>){
599                                                         try{
600                                                                 //This is for validation check if the value exists or not
601                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
602                                                                 String value =  ((LinkedHashMap<?, ?>) attribute).get("value").toString();
603                                                                 if("".equals(key) || "".equals(value)){
604                                                                         responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
605                                                                         valid = false;
606                                                                         break;  
607                                                                 }
608                                                         }catch(Exception e){
609                                                                 LOGGER.error("This is a Policy Validation check" +e);
610                                                                 responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
611                                                                 valid = false;
612                                                                 break;
613                                                         }
614                                                 }
615                                         }
616                                 }else{
617                                         responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
618                                         valid = false;
619                                 }
620                                 if(!Strings.isNullOrEmpty(policyData.getActionAttributeValue())){
621                                         String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
622                                         if(!actionAttribute.contains("success")){
623                                                 responseString.append("ActionAttribute:" +  actionAttribute + "<br>");
624                                                 valid = false;
625                                         };
626                                 }else{
627                                         responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
628                                         valid = false;
629                                 }
630                                 
631                                 if(!policyData.getRuleAlgorithmschoices().isEmpty()){
632                                         for(Object attribute : policyData.getRuleAlgorithmschoices()){
633                                                 if(attribute instanceof LinkedHashMap<?, ?>){
634                                                         try{
635                                                                 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
636                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
637                                                                 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
638                                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
639
640                                                                 if(Strings.isNullOrEmpty(label) || Strings.isNullOrEmpty(key) || Strings.isNullOrEmpty(rule) || Strings.isNullOrEmpty(value)){
641                                                                         responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
642                                                                         valid = false;
643                                                                 }
644                                                         }catch(Exception e){
645                                                                 LOGGER.error("This is a Policy Validation check" +e);
646                                                                 responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
647                                                                 valid = false;
648                                                                 break;
649                                                         }
650                                                 }
651                                         }
652                                 }
653                         }
654
655                         if(CONFIG_POLICY.equals(policyData.getPolicyType())){
656                                 String value = "";
657                                 if(valid){
658                                         if(commonClassDao!=null){
659                                                 List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
660                                                 if (!spData.isEmpty()){
661                                                         SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
662                                                         value = "Message:" +  safePolicyWarningData.getMessage();
663                                                 }
664                                         }
665                                         responseString.append("success" + "@#"+ value);
666                                 }
667                         }else{
668                                 if(valid){
669                                         responseString.append("success");
670                                 }
671                         }
672
673                         return responseString;
674                 }
675                 catch (Exception e){
676                         LOGGER.error("Exception Occured during Policy Validation" +e);
677                         return null;
678                 }
679         }
680
681         protected String emailValidation(String email, String response){
682                 if(email != null){
683                         String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
684                         if(!validateEmail.contains("success")){
685                                 response += "<b>Email</b>:<i>" +  validateEmail+ "</i><br>";
686                         }else{
687                                 return "success";
688                         }
689                 }
690                 return response;
691         }
692
693         private MicroServiceModels getAttributeObject(String name, String version) {    
694                 MicroServiceModels workingModel = null;
695                 try{
696                         List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
697                         if(microServiceModelsData != null){
698                                 workingModel = (MicroServiceModels) microServiceModelsData.get(0);
699                         }
700                 }catch(Exception e){
701                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template.  The template name, " 
702                     + name + " was not found in the dictionary: ";
703                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
704                         return null;
705                 }
706
707                 return workingModel;
708         }
709
710         private void pullJsonKeyPairs(JsonNode rootNode) {
711                 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
712
713                 while (fieldsIterator.hasNext()) {
714                         Map.Entry<String, JsonNode> field = fieldsIterator.next();
715                         final String key = field.getKey();
716                         final JsonNode value = field.getValue();
717                         if (value.isContainerNode() && !value.isArray()) {
718                                 pullJsonKeyPairs(value); // RECURSIVE CALL
719                         } else {
720                                 if (value.isArray()){
721                                         String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
722                                         mapAttribute.put(key, newValue);
723                                 }else {
724                                         mapAttribute.put(key, value.toString().trim());
725                                 }
726                         }
727                 }
728         }
729
730 }