Merge "Adding Junits for policy engine"
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyValidationController.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
21 package org.onap.policy.controller;
22
23
24 import java.io.IOException;
25 import java.io.PrintWriter;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.LinkedHashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.apache.commons.lang.StringUtils;
37 import org.json.JSONObject;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
41 import org.onap.policy.rest.adapter.ClosedLoopPMBody;
42 import org.onap.policy.rest.adapter.PolicyRestAdapter;
43 import org.onap.policy.rest.dao.CommonClassDao;
44 import org.onap.policy.rest.jpa.MicroServiceModels;
45 import org.onap.policy.rest.jpa.SafePolicyWarning;
46 import org.onap.policy.utils.PolicyUtils;
47 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
48 import org.openecomp.portalsdk.core.web.support.JsonMessage;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.stereotype.Controller;
51 import org.springframework.web.bind.annotation.RequestMapping;
52 import org.springframework.web.servlet.ModelAndView;
53
54 import com.fasterxml.jackson.databind.DeserializationFeature;
55 import com.fasterxml.jackson.databind.JsonNode;
56 import com.fasterxml.jackson.databind.ObjectMapper;
57 import com.google.common.base.Splitter;
58 import com.google.common.base.Strings;
59
60 @Controller
61 @RequestMapping("/")
62 public class PolicyValidationController extends RestrictedBaseController {
63
64         private static final Logger LOGGER      = FlexLogger.getLogger(PolicyValidationController.class);
65         
66         public static final String CONFIG_POLICY = "Config";
67         public static final String ACTION_POLICY = "Action";
68         public static final String DECISION_POLICY = "Decision";
69         public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
70         public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
71         public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
72         public static final String MICROSERVICES="Micro Service";
73         private static Map<String, String> mapAttribute = new HashMap<>();
74
75         @Autowired
76         CommonClassDao commonClassDao;
77
78         @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
79         public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
80                 try{
81                         boolean valid = true;
82                         StringBuilder responseString = new StringBuilder();
83                         ObjectMapper mapper = new ObjectMapper();
84                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
85                         JsonNode root = mapper.readTree(request.getReader());
86                         PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
87                         if(policyData.getPolicyName() != null){
88                                 String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
89                                 if(!policyNameValidate.contains("success")){
90                                         responseString.append("PolicyName:" +  policyNameValidate + "<br>");
91                                         valid = false;
92                                 };
93                         }else{
94                                 responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
95                                 valid = false;
96                         }
97                         if(policyData.getPolicyDescription() != null){
98                                 String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
99                                 if(!descriptionValidate.contains("success")){
100                                         responseString.append("Description:" +  descriptionValidate + "<br>");
101                                         valid = false;
102                                 }       
103                         }
104
105                         if(policyData.getPolicyType().equals(CONFIG_POLICY)){
106                                 if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) 
107                                                 ||  policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) {
108                                         if(policyData.getOnapName() != null){
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(policyData.getRiskType() != null){
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(policyData.getRiskLevel() != null){
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(policyData.getGuard() != null){
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(policyData.getConfigPolicyType().equals("Base")){
154                                         if(policyData.getConfigName() != null){
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(policyData.getConfigType() != null){
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(policyData.getConfigBodyData() != null){
175                                                 String configBodyData = policyData.getConfigBodyData();
176                                                 String policyType = policyData.getConfigType();
177                                                 if (policyType != null) {
178                                                         if (policyType.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 (policyType.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 (policyType.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 (policyType.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(policyData.getConfigPolicyType().equals("Firewall Config")){
207                                         if(policyData.getConfigName() != null){
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){
218                                                 responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>");
219                                                 valid = false;
220                                         }
221                                 }
222                                 if(policyData.getConfigPolicyType().equals("BRMS_Param")){
223                                         if(policyData.getRuleName() == null){
224                                                 responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required</i><br>");
225                                                 valid = false;
226                                         }
227                                 }
228                                 if(policyData.getConfigPolicyType().equals("BRMS_Raw")){
229                                         if(policyData.getConfigBodyData() != null){
230                                                 String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
231                                                 // If there are any error other than Annotations then this is not Valid
232                                                 if(message.contains("[ERR")){
233                                                         responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>");
234                                                         valid = false;
235                                                 }
236                                         }else{
237                                                 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required</i><br>");
238                                                 valid = false;
239                                         }
240                                 }
241                                 if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){
242                                         try{
243                                                 if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){
244                                                         responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
245                                                         valid = false; 
246                                                 }
247                                         }catch(Exception e){
248                                             LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
249                                                 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
250                                                 valid = false;
251                                         }
252
253                                         if(root.get("policyData").get("jsonBodyData") != null){
254                                                 ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class);
255                                                 if(pmBody.getEmailAddress() != null){
256                                                         String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
257                                                         if(result != "success"){
258                                                                 responseString.append(result + "<br>");
259                                                                 valid = false;
260                                                         }
261                                                 }
262                                                 if(pmBody.getGeoLink() != null){
263                                                         String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
264                                                         if(!result.contains("success")){
265                                                                 responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
266                                                                 valid = false;
267                                                         };
268                                                 }
269                                                 if(pmBody.getAttributes() != null){
270                                                         for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
271                                                                 String key = entry.getKey();
272                                                                 String value = entry.getValue();
273                                                                 if(!key.contains("Message")){
274                                                                         String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
275                                                                         if(!attributeValidate.contains("success")){
276                                                                                 responseString.append("<b>Attributes</b>:<i>" +  key + " : value has spaces</i><br>");
277                                                                                 valid = false;
278                                                                         };
279                                                                 }
280                                                         }       
281                                                 }
282                                         }else{
283                                                 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
284                                                 valid = false;
285                                         }
286                                 }
287                                 if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){
288                                         if(root.get("policyData").get("jsonBodyData") != null){
289                                                 ClosedLoopFaultBody faultBody = mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
290                                                 if(faultBody.getEmailAddress() != null){
291                                                         String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
292                                                         if(result != "success"){
293                                                                 responseString.append(result+ "<br>");
294                                                                 valid = false;
295                                                         }
296                                                 }
297                                                 if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
298                                                         responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
299                                                         valid = false; 
300                                                 }
301                                                 if(faultBody.getActions() == null){
302                                                         responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
303                                                         valid = false;
304                                                 }
305                                                 if(faultBody.getClosedLoopPolicyStatus() == null){
306                                                         responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
307                                                         valid = false;
308                                                 }
309                                                 if(faultBody.getConditions() == null){
310                                                         responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
311                                                         valid = false;
312                                                 }
313                                                 if(faultBody.getGeoLink() != null){
314                                                         String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
315                                                         if(!result.contains("success")){
316                                                                 responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
317                                                                 valid = false;
318                                                         }
319                                                 }
320
321                                                 if(faultBody.getTimeInterval() == 0){
322                                                         responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
323                                                         valid = false;
324                                                 }
325                                                 if(faultBody.getRetrys() == 0){
326                                                         responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
327                                                         valid = false;
328                                                 }
329                                                 if(faultBody.getTimeOutvPRO() == 0){
330                                                         responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
331                                                         valid = false;
332                                                 }
333                                                 if(faultBody.getTimeOutRuby() == 0){
334                                                         responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
335                                                         valid = false;
336                                                 }
337                                                 if(faultBody.getVnfType() == null){
338                                                         responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
339                                                         valid = false;
340                                                 }
341                                         }else{
342                                                 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
343                                                 responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
344                                                 responseString.append("<b>Aging Window</b>:<i>Aging Window is required</i><br>");
345                                                 responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
346                                                 responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
347                                                 responseString.append("<b>PEP Name</b>:<i>PEP Name is required</i><br>");
348                                                 responseString.append("<b>PEP Action</b>:<i>PEP Action is required</i><br>");
349                                                 responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
350                                                 responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
351                                                 responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
352                                                 responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
353                                                 responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
354                                                 valid = false; 
355                                         }
356                                 }
357
358                                 if (policyData.getConfigPolicyType().contains("Micro Service")){
359                                         if(policyData.getServiceType() != null){
360                                                 pullJsonKeyPairs(root.get("policyJSON"));
361                                                 MicroServiceModels returnModel = new MicroServiceModels();
362                                                 String service = null;
363                                                 String version = null;
364                                                 if (policyData.getServiceType().contains("-v")){
365                                                         service = policyData.getServiceType().split("-v")[0];
366                                                         version = policyData.getServiceType().split("-v")[1];
367                                                 }else {
368                                                         service = policyData.getServiceType();
369                                                         version = policyData.getVersion();
370                                                 }
371                                                 returnModel = getAttributeObject(service, version);
372                                                 String annoation = returnModel.getAnnotation();
373                                                 if (!Strings.isNullOrEmpty(annoation)){
374                                                          Map<String, String> rangeMap = new HashMap<>();
375                                                         rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation);
376                                                         for (Entry<String, String> rMap : rangeMap.entrySet()){
377                                                                 if (rMap.getValue().contains("range::")){
378                                                                         String value = mapAttribute.get(rMap.getKey().trim());
379                                                                         String[] tempString = rMap.getValue().split("::")[1].split("-");
380                                                                         int startNum = Integer.parseInt(tempString[0]);
381                                                                         int endNum = Integer.parseInt(tempString[1]);
382                                                                         String returnString = "Invalid Range:" + rMap.getKey() + " must be between " 
383                                                                                         + startNum + " - "  + endNum + ",";
384                                                                         if (PolicyUtils.isInteger(value.replace("\"", ""))){
385                                                                                 int result = Integer.parseInt(value.replace("\"", ""));
386                                                                                 if (result < startNum || result > endNum){
387                                                                                         responseString.append(returnString);                                                                    
388                                                                                         valid = false;
389                                                                                 }
390                                                                         }else {
391                                                                                 responseString.append(returnString);
392                                                                                 valid = false;
393                                                                         }
394                                                                 }
395                                                         }
396                                                 }
397                                         }else{
398                                                 responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
399                                                 valid = false;
400                                         }
401
402                                         if(policyData.getPriority() == null){
403                                                 responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
404                                                 valid = false;
405                                         }
406                                 }       
407                         }
408                         if (policyData.getPolicyType().equals(DECISION_POLICY)){
409                                 if(policyData.getOnapName() != null){
410                                         String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
411                                         if(!onapNameValidate.contains("success")){
412                                                 responseString.append("OnapName:" +  onapNameValidate + "<br>");
413                                                 valid = false;
414                                         }
415                                 }else{
416                                         responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
417                                         valid = false;
418                                 }
419                                 
420                                 if("Rainy_Day".equals(policyData.getRuleProvider())){
421                                         if(policyData.getRainyday()==null){
422                                                 responseString.append("<b> Rainy Day Parameters are Required </b><br>");
423                                                 valid = false;
424                                         }else{
425                                                 if(policyData.getRainyday().getServiceType()==null){
426                                                         responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
427                                                         valid = false;
428                                                 }
429                                                 if(policyData.getRainyday().getVnfType()==null){
430                                                         responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
431                                                         valid = false;
432                                                 }                                               
433                                                 if(policyData.getRainyday().getBbid()==null){
434                                                         responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
435                                                         valid = false;
436                                                 }
437                                                 if(policyData.getRainyday().getWorkstep()==null){
438                                                         responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
439                                                         valid = false;
440                                                 }
441                                                 if(policyData.getRainyday().getServiceType()==null){
442                                                         responseString.append("Rainy Day <b>Error Code</b> is Required<br>");
443                                                         valid = false;
444                                                 }
445                                         }
446                                 }
447                                 
448                                 if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
449                                         if(policyData.getYamlparams()==null){
450                                                 responseString.append("<b> Guard Params are Required </b>" + "<br>");
451                                                 valid = false;
452                                         }else{
453                                                 if(policyData.getYamlparams().getActor()==null){
454                                                         responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
455                                                         valid = false;
456                                                 }
457                                                 if(policyData.getYamlparams().getRecipe()==null){
458                                                         responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
459                                                         valid = false;
460                                                 }
461                                                 if(policyData.getYamlparams().getGuardActiveStart()==null){
462                                                         responseString.append("Guard Params <b>Guard Active Start/b>is Required " + "<br>");
463                                                         valid = false;
464                                                 }
465                                                 if(policyData.getYamlparams().getGuardActiveEnd()==null){
466                                                         responseString.append("Guard Params <b>Guard Active End</b>is Required " + "<br>");
467                                                         valid = false;
468                                                 }
469                                                 if("GUARD_YAML".equals(policyData.getRuleProvider())){
470                                                         if(policyData.getYamlparams().getLimit()==null){
471                                                                 responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
472                                                                 valid = false;
473                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
474                                                                 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
475                                                                 valid = false;
476                                                         }
477                                                         if(policyData.getYamlparams().getTimeWindow()==null){
478                                                                 responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
479                                                                 valid = false;
480                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
481                                                                 responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + "<br>");
482                                                                 valid = false;
483                                                         }
484                                                         if(policyData.getYamlparams().getTimeUnits()==null){
485                                                                 responseString.append("Guard Params <b>Time Units</b> is Required" + "<br>");
486                                                                 valid = false;
487                                                         }
488                                                 }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
489                                                         if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
490                                                                 responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
491                                                                 valid = false;
492                                                         }else{
493                                                                 for(String blackList: policyData.getYamlparams().getBlackList()){
494                                                                         if(blackList==null || !("success".equals(PolicyUtils.policySpecialCharValidator(blackList)))){
495                                                                                 responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
496                                                                                 valid = false;
497                                                                                 break;
498                                                                         }
499                                                                 }
500                                                         }
501                                                 }
502                                         }
503                                 }
504                         }
505
506                         if(policyData.getPolicyType().equals(ACTION_POLICY)){
507                                 if(policyData.getActionPerformer() != null){
508                                         String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
509                                         if(!actionPerformer.contains("success")){
510                                                 responseString.append("ActionPerformer:" +  actionPerformer + "<br>");
511                                                 valid = false;
512                                         }
513                                 }else{
514                                         responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
515                                         valid = false;
516                                 }
517                                 if(policyData.getAttributes() != null){
518                                         for(Object attribute : policyData.getAttributes()){
519                                                 if(attribute instanceof LinkedHashMap<?, ?>){
520                                                         try{
521                                                                 //This is for validation check if the value exists or not
522                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
523                                                                 String value =  ((LinkedHashMap<?, ?>) attribute).get("value").toString();
524                                                                 if("".equals(key) || "".equals(value)){
525                                                                         responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
526                                                                         valid = false;
527                                                                         break;  
528                                                                 }
529                                                         }catch(Exception e){
530                                                                 LOGGER.error("This is a Policy Validation check" +e);
531                                                                 responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
532                                                                 valid = false;
533                                                                 break;
534                                                         }
535                                                 }
536                                         }
537                                 }else{
538                                         responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
539                                         valid = false;
540                                 }
541                                 if(policyData.getActionAttributeValue() != null){
542                                         String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
543                                         if(!actionAttribute.contains("success")){
544                                                 responseString.append("ActionAttribute:" +  actionAttribute + "<br>");
545                                                 valid = false;
546                                         };
547                                 }else{
548                                         responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
549                                         valid = false;
550                                 }                       
551                         }
552                         
553                         if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){
554                                 if(!policyData.getRuleAlgorithmschoices().isEmpty()){
555                                         for(Object attribute : policyData.getRuleAlgorithmschoices()){
556                                                 if(attribute instanceof LinkedHashMap<?, ?>){
557                                                         try{
558                                                                 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
559                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
560                                                                 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
561                                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
562                                                                 if("".equals(label) || "".equals(key) || "".equals(rule)  || "".equals(value)){
563                                                                         responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
564                                                                         valid = false;
565                                                                 }
566                                                         }catch(Exception e){
567                                                                 LOGGER.error("This is a Policy Validation check" +e);
568                                                                 responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
569                                                                 valid = false;
570                                                                 break;
571                                                         }
572                                                 }
573                                         }
574                                 }
575                         }
576
577                         if(policyData.getPolicyType().equals(CONFIG_POLICY)){
578                                 String value = "";
579                                 if(valid){
580                                         List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
581                                         if (!spData.isEmpty()){
582                                                 SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
583                                                 safePolicyWarningData.getMessage();
584                                                 value = "Message:" +  safePolicyWarningData.getMessage();
585                                         }
586                                         responseString.append("success" + "@#"+ value);
587                                 }
588                         }else{
589                                 if(valid){
590                                         responseString.append("success");
591                                 }
592                         }
593
594                         PrintWriter out = response.getWriter();
595                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
596                         JSONObject j = new JSONObject(msg);
597                         out.write(j.toString());
598
599                         return null;
600                 }
601                 catch (Exception e){
602                         LOGGER.error("Exception Occured while Policy Validation" +e);
603                         response.setCharacterEncoding("UTF-8");
604                         request.setCharacterEncoding("UTF-8");
605                         PrintWriter out = response.getWriter();
606                         out.write(e.getMessage());
607                 }
608                 return null;
609         }
610
611         protected String emailValidation(String email, String response){
612                 if(email != null){
613                         String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
614                         if(!validateEmail.contains("success")){
615                                 response += "<b>Email</b>:<i>" +  validateEmail+ "</i><br>";
616                         }else{
617                                 return "success";
618                         }
619                 }
620                 return response;
621         }
622
623         private MicroServiceModels getAttributeObject(String name, String version) {    
624                 MicroServiceModels workingModel = new MicroServiceModels();
625                 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
626                 if(microServiceModelsData != null){
627                         workingModel = (MicroServiceModels) microServiceModelsData.get(0);
628                 }
629                 return workingModel;
630         }
631
632         private void pullJsonKeyPairs(JsonNode rootNode) {
633                 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
634
635                 while (fieldsIterator.hasNext()) {
636                         Map.Entry<String, JsonNode> field = fieldsIterator.next();
637                         final String key = field.getKey();
638                         final JsonNode value = field.getValue();
639                         if (value.isContainerNode() && !value.isArray()) {
640                                 pullJsonKeyPairs(value); // RECURSIVE CALL
641                         } else {
642                                 if (value.isArray()){
643                                         String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
644                                         mapAttribute.put(key, newValue);
645                                 }else {
646                                         mapAttribute.put(key, value.toString().trim());
647                                 }
648                         }
649                 }
650         }
651 }