Fixes for sonar critical issues
[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.ByteArrayInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.PrintWriter;
28 import java.io.StringReader;
29 import java.nio.charset.StandardCharsets;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.LinkedHashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.Scanner;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
41 import javax.json.Json;
42 import javax.json.JsonReader;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45 import javax.xml.parsers.SAXParser;
46 import javax.xml.parsers.SAXParserFactory;
47
48 import org.apache.commons.lang.StringUtils;
49 import org.dom4j.util.XMLErrorHandler;
50 import org.json.JSONObject;
51 import org.onap.policy.common.logging.flexlogger.FlexLogger;
52 import org.onap.policy.common.logging.flexlogger.Logger;
53 import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
54 import org.onap.policy.rest.adapter.ClosedLoopPMBody;
55 import org.onap.policy.rest.adapter.PolicyRestAdapter;
56 import org.onap.policy.rest.dao.CommonClassDao;
57 import org.onap.policy.rest.jpa.MicroServiceModels;
58 import org.onap.policy.rest.jpa.SafePolicyWarning;
59 import org.onap.policy.utils.PolicyUtils;
60 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
61 import org.openecomp.portalsdk.core.web.support.JsonMessage;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.stereotype.Controller;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.servlet.ModelAndView;
66 import org.xml.sax.InputSource;
67 import org.xml.sax.XMLReader;
68
69 import com.fasterxml.jackson.databind.DeserializationFeature;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
72 import com.google.common.base.CharMatcher;
73 import com.google.common.base.Splitter;
74 import com.google.common.base.Strings;
75
76 @Controller
77 @RequestMapping("/")
78 public class PolicyValidationController extends RestrictedBaseController {
79
80         private static final Logger LOGGER      = FlexLogger.getLogger(PolicyValidationController.class);
81         
82         public static final String CONFIG_POLICY = "Config";
83         public static final String ACTION_POLICY = "Action";
84         public static final String DECISION_POLICY = "Decision";
85         public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
86         public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
87         public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
88         public static final String MICROSERVICES="Micro Service";
89         private Pattern pattern;
90         private Matcher matcher;
91         private static Map<String, String> mapAttribute = new HashMap<>();
92
93         private static final String EMAIL_PATTERN = 
94                         "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
95                                         + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
96
97         @Autowired
98         CommonClassDao commonClassDao;
99
100         @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
101         public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
102                 try{
103                         boolean valid = true;
104                         StringBuilder responseString = new StringBuilder();
105                         ObjectMapper mapper = new ObjectMapper();
106                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
107                         JsonNode root = mapper.readTree(request.getReader());
108                         PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
109                         if(policyData.getPolicyName() != null){
110                                 String policyNameValidate = emptyValidator(policyData.getPolicyName());
111                                 if(!policyNameValidate.contains("success")){
112                                         responseString.append("PolicyName:" +  policyNameValidate + "<br>");
113                                         valid = false;
114                                 };
115                         }else{
116                                 responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
117                                 valid = false;
118                         }
119                         if(policyData.getPolicyDescription() != null){
120                                 String descriptionValidate = descriptionValidator(policyData.getPolicyDescription());
121                                 if(!descriptionValidate.contains("success")){
122                                         responseString.append("Description:" +  descriptionValidate + "<br>");
123                                         valid = false;
124                                 }       
125                         }
126
127                         if(policyData.getPolicyType().equals(CONFIG_POLICY)){
128                                 if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) 
129                                                 ||  policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) {
130                                         if(policyData.getOnapName() != null){
131                                                 String onapNameValidate = emptyValidator(policyData.getOnapName());
132                                                 if(!onapNameValidate.contains("success")){
133                                                         responseString.append("OnapName:" +  onapNameValidate + "<br>");
134                                                         valid = false;
135                                                 }
136                                         }else{
137                                                 responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
138                                                 valid = false;
139                                         }
140                                 }
141
142                                 if(policyData.getRiskType() != null){
143                                         String riskTypeValidate = emptyValidator(policyData.getRiskType());
144                                         if(!riskTypeValidate.contains("success")){
145                                                 responseString.append("RiskType:" +  riskTypeValidate + "<br>");
146                                                 valid = false;
147                                         }
148                                 }else {
149                                         responseString.append("Risk Type: Risk Type Should not be Empty" + "<br>");
150                                         valid = false;
151                                 }
152
153                                 if(policyData.getRiskLevel() != null){
154                                         String validateRiskLevel = emptyValidator(policyData.getRiskLevel());
155                                         if(!validateRiskLevel.contains("success")){
156                                                 responseString.append("RiskLevel:" +  validateRiskLevel + "<br>");
157                                                 valid = false;
158                                         }
159                                 }else {
160                                         responseString.append("Risk Level: Risk Level Should not be Empty" + "<br>");
161                                         valid = false;
162                                 }
163
164                                 if(policyData.getGuard() != null){
165                                         String validateGuard = emptyValidator(policyData.getGuard());
166                                         if(!validateGuard.contains("success")){
167                                                 responseString.append("Guard:" +  validateGuard + "<br>");
168                                                 valid = false;
169                                         }
170                                 }else {
171                                         responseString.append("Guard: Guard Value Should not be Empty" + "<br>");
172                                         valid = false;
173                                 }
174
175                                 if(policyData.getConfigPolicyType().equals("Base")){
176                                         if(policyData.getConfigName() != null){
177                                                 String configNameValidate = emptyValidator(policyData.getConfigName());
178                                                 if(!configNameValidate.contains("success")){
179                                                         responseString.append("ConfigName:" +  configNameValidate + "<br>");
180                                                         valid = false;
181                                                 }
182                                         }else{
183                                                 responseString.append("Config Name: Config Name Should not be Empty" + "<br>");
184                                                 valid = false;
185                                         }
186                                         if(policyData.getConfigType() != null){
187                                                 String configTypeValidate = emptyValidator(policyData.getConfigType());
188                                                 if(!configTypeValidate.contains("success")){
189                                                         responseString.append("ConfigType:" +  configTypeValidate + "<br>");
190                                                         valid = false;
191                                                 }
192                                         }else{
193                                                 responseString.append("Config Type: Config Type Should not be Empty" + "<br>");
194                                                 valid = false;
195                                         }
196                                         if(policyData.getConfigBodyData() != null){
197                                                 String configBodyData = policyData.getConfigBodyData();
198                                                 String policyType = policyData.getConfigType();
199                                                 if (policyType != null) {
200                                                         if (policyType.equals("JSON")) {
201                                                                 if (!isJSONValid(configBodyData)) {
202                                                                         responseString.append("Config Body: JSON Content is not valid" + "<br>");
203                                                                         valid = false;
204                                                                 }
205                                                         } else if (policyType.equals("XML")) {
206                                                                 if (!isXMLValid(configBodyData)) {
207                                                                         responseString.append("Config Body: XML Content data is not valid" + "<br>");
208                                                                         valid = false;
209                                                                 }
210                                                         } else if (policyType.equals("PROPERTIES")) {
211                                                                 if (!isPropValid(configBodyData)||configBodyData.equals("")) {
212                                                                         responseString.append("Config Body: Property data is not valid" + "<br>");
213                                                                         valid = false;
214                                                                 } 
215                                                         } else if (policyType.equals("OTHER")) {
216                                                                 if (configBodyData.equals("")) {
217                                                                         responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
218                                                                         valid = false;
219                                                                 }
220                                                         }
221                                                 }
222                                         }else{
223                                                 responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
224                                                 valid = false;
225                                         }
226                                 }
227
228                                 if(policyData.getConfigPolicyType().equals("Firewall Config")){
229                                         if(policyData.getConfigName() != null){
230                                                 String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName());
231                                                 if(!configNameValidate.contains("success")){
232                                                         responseString.append("<b>ConfigName</b>:<i>" +  configNameValidate + "</i><br>");
233                                                         valid = false;
234                                                 }
235                                         }else{
236                                                 responseString.append("<b>Config Name</b>:<i> Config Name is required" + "</i><br>");
237                                                 valid = false;
238                                         }
239                                         if(policyData.getSecurityZone() == null){
240                                                 responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>");
241                                                 valid = false;
242                                         }
243                                 }
244                                 if(policyData.getConfigPolicyType().equals("BRMS_Param")){
245                                         if(policyData.getRuleName() == null){
246                                                 responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required</i><br>");
247                                                 valid = false;
248                                         }
249                                 }
250                                 if(policyData.getConfigPolicyType().equals("BRMS_Raw")){
251                                         if(policyData.getConfigBodyData() != null){
252                                                 String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
253                                                 // If there are any error other than Annotations then this is not Valid
254                                                 if(message.contains("[ERR")){
255                                                         responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>");
256                                                         valid = false;
257                                                 }
258                                         }else{
259                                                 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required</i><br>");
260                                                 valid = false;
261                                         }
262                                 }
263                                 if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){
264                                         try{
265                                                 if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){
266                                                         responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
267                                                         valid = false; 
268                                                 }
269                                         }catch(Exception e){
270                                             LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
271                                                 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
272                                                 valid = false;
273                                         }
274
275                                         if(root.get("policyData").get("jsonBodyData") != null){
276                                                 ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class);
277                                                 if(pmBody.getEmailAddress() != null){
278                                                         String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
279                                                         if(result != "success"){
280                                                                 responseString.append(result + "<br>");
281                                                                 valid = false;
282                                                         }
283                                                 }
284                                                 if(pmBody.getGeoLink() != null){
285                                                         String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink());
286                                                         if(!result.contains("success")){
287                                                                 responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
288                                                                 valid = false;
289                                                         };
290                                                 }
291                                                 if(pmBody.getAttributes() != null){
292                                                         for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
293                                                                 String key = entry.getKey();
294                                                                 String value = entry.getValue();
295                                                                 if(!key.contains("Message")){
296                                                                         String attributeValidate = PolicyUtils.emptyPolicyValidator(value);
297                                                                         if(!attributeValidate.contains("success")){
298                                                                                 responseString.append("<b>Attributes</b>:<i>" +  key + " : value has spaces</i><br>");
299                                                                                 valid = false;
300                                                                         };
301                                                                 }
302                                                         }       
303                                                 }
304                                         }else{
305                                                 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
306                                                 valid = false;
307                                         }
308                                 }
309                                 if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){
310                                         if(root.get("policyData").get("jsonBodyData") != null){
311                                                 ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
312                                                 if(faultBody.getEmailAddress() != null){
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.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
320                                                         responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
321                                                         valid = false; 
322                                                 }
323                                                 if(faultBody.getActions() == null){
324                                                         responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
325                                                         valid = false;
326                                                 }
327                                                 if(faultBody.getClosedLoopPolicyStatus() == null){
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 Atleast one Condition</i><br>");
333                                                         valid = false;
334                                                 }
335                                                 if(faultBody.getGeoLink() != null){
336                                                         String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink());
337                                                         if(!result.contains("success")){
338                                                                 responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
339                                                                 valid = false;
340                                                         };
341                                                 }
342
343                                                 if(faultBody.getTimeInterval() == 0){
344                                                         responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
345                                                         valid = false;
346                                                 }
347                                                 if(faultBody.getRetrys() == 0){
348                                                         responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
349                                                         valid = false;
350                                                 }
351                                                 if(faultBody.getTimeOutvPRO() == 0){
352                                                         responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
353                                                         valid = false;
354                                                 }
355                                                 if(faultBody.getTimeOutRuby() == 0){
356                                                         responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
357                                                         valid = false;
358                                                 }
359                                                 if(faultBody.getVnfType() == null){
360                                                         responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
361                                                         valid = false;
362                                                 }
363                                         }else{
364                                                 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
365                                                 responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
366                                                 responseString.append("<b>Aging Window</b>:<i>Aging Window is required</i><br>");
367                                                 responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
368                                                 responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
369                                                 responseString.append("<b>PEP Name</b>:<i>PEP Name is required</i><br>");
370                                                 responseString.append("<b>PEP Action</b>:<i>PEP Action is required</i><br>");
371                                                 responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
372                                                 responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
373                                                 responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
374                                                 responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
375                                                 responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
376                                                 valid = false; 
377                                         }
378                                 }
379
380                                 if (policyData.getConfigPolicyType().contains("Micro Service")){
381                                         if(policyData.getServiceType() != null){
382                                                 pullJsonKeyPairs(root.get("policyJSON"));
383                                                 MicroServiceModels returnModel = new MicroServiceModels();
384                                                 String service = null;
385                                                 String version = null;
386                                                 if (policyData.getServiceType().contains("-v")){
387                                                         service = policyData.getServiceType().split("-v")[0];
388                                                         version = policyData.getServiceType().split("-v")[1];
389                                                 }else {
390                                                         service = policyData.getServiceType();
391                                                         version = policyData.getVersion();
392                                                 }
393                                                 returnModel = getAttributeObject(service, version);
394                                                 String annoation = returnModel.getAnnotation();
395                                                 if (!Strings.isNullOrEmpty(annoation)){
396                                                          Map<String, String> rangeMap = new HashMap<>();
397                                                         rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation);
398                                                         for (Entry<String, String> rMap : rangeMap.entrySet()){
399                                                                 if (rMap.getValue().contains("range::")){
400                                                                         String value = mapAttribute.get(rMap.getKey().trim());
401                                                                         String[] tempString = rMap.getValue().split("::")[1].split("-");
402                                                                         int startNum = Integer.parseInt(tempString[0]);
403                                                                         int endNum = Integer.parseInt(tempString[1]);
404                                                                         String returnString = "Invalid Range:" + rMap.getKey() + " must be between " 
405                                                                                         + startNum + " - "  + endNum + ",";
406                                                                         if (PolicyUtils.isInteger(value.replace("\"", ""))){
407                                                                                 int result = Integer.parseInt(value.replace("\"", ""));
408                                                                                 if (result < startNum || result > endNum){
409                                                                                         responseString.append(returnString);                                                                    
410                                                                                         valid = false;
411                                                                                 }
412                                                                         }else {
413                                                                                 responseString.append(returnString);
414                                                                                 valid = false;
415                                                                         }
416                                                                 }
417                                                         }
418                                                 }
419                                         }else{
420                                                 responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
421                                                 valid = false;
422                                         }
423
424                                         if(policyData.getPriority() == null){
425                                                 responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
426                                                 valid = false;
427                                         }
428                                 }       
429                         }
430                         if (policyData.getPolicyType().equals(DECISION_POLICY)){
431                                 if(policyData.getOnapName() != null){
432                                         String onapNameValidate = emptyValidator(policyData.getOnapName());
433                                         if(!onapNameValidate.contains("success")){
434                                                 responseString.append("OnapName:" +  onapNameValidate + "<br>");
435                                                 valid = false;
436                                         }
437                                 }else{
438                                         responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
439                                         valid = false;
440                                 }
441                                 
442                                 if("Rainy_Day".equals(policyData.getRuleProvider())){
443                                         if(policyData.getRainyday()==null){
444                                                 responseString.append("<b> Rainy Day Parameters are Required </b><br>");
445                                                 valid = false;
446                                         }else{
447                                                 if(policyData.getRainyday().getServiceType()==null){
448                                                         responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
449                                                         valid = false;
450                                                 }
451                                                 if(policyData.getRainyday().getVnfType()==null){
452                                                         responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
453                                                         valid = false;
454                                                 }                                               
455                                                 if(policyData.getRainyday().getBbid()==null){
456                                                         responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
457                                                         valid = false;
458                                                 }
459                                                 if(policyData.getRainyday().getWorkstep()==null){
460                                                         responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
461                                                         valid = false;
462                                                 }
463                                                 if(policyData.getRainyday().getServiceType()==null){
464                                                         responseString.append("Rainy Day <b>Error Code</b> is Required<br>");
465                                                         valid = false;
466                                                 }
467                                         }
468                                 }
469                                 
470                                 if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
471                                         if(policyData.getYamlparams()==null){
472                                                 responseString.append("<b> Guard Params are Required </b>" + "<br>");
473                                                 valid = false;
474                                         }else{
475                                                 if(policyData.getYamlparams().getActor()==null){
476                                                         responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
477                                                         valid = false;
478                                                 }
479                                                 if(policyData.getYamlparams().getRecipe()==null){
480                                                         responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
481                                                         valid = false;
482                                                 }
483                                                 if(policyData.getYamlparams().getGuardActiveStart()==null){
484                                                         responseString.append("Guard Params <b>Guard Active Start/b>is Required " + "<br>");
485                                                         valid = false;
486                                                 }
487                                                 if(policyData.getYamlparams().getGuardActiveEnd()==null){
488                                                         responseString.append("Guard Params <b>Guard Active End</b>is Required " + "<br>");
489                                                         valid = false;
490                                                 }
491                                                 if("GUARD_YAML".equals(policyData.getRuleProvider())){
492                                                         if(policyData.getYamlparams().getLimit()==null){
493                                                                 responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
494                                                                 valid = false;
495                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
496                                                                 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
497                                                                 valid = false;
498                                                         }
499                                                         if(policyData.getYamlparams().getTimeWindow()==null){
500                                                                 responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
501                                                                 valid = false;
502                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
503                                                                 responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + "<br>");
504                                                                 valid = false;
505                                                         }
506                                                         if(policyData.getYamlparams().getTimeUnits()==null){
507                                                                 responseString.append("Guard Params <b>Time Units</b> is Required" + "<br>");
508                                                                 valid = false;
509                                                         }
510                                                 }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
511                                                         if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
512                                                                 responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
513                                                                 valid = false;
514                                                         }else{
515                                                                 for(String blackList: policyData.getYamlparams().getBlackList()){
516                                                                         if(blackList==null || !("success".equals(emptyValidator(blackList)))){
517                                                                                 responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
518                                                                                 valid = false;
519                                                                                 break;
520                                                                         }
521                                                                 }
522                                                         }
523                                                 }
524                                         }
525                                 }
526                         }
527
528                         if(policyData.getPolicyType().equals(ACTION_POLICY)){
529                                 if(policyData.getActionPerformer() != null){
530                                         String actionPerformer = emptyValidator(policyData.getActionPerformer());
531                                         if(!actionPerformer.contains("success")){
532                                                 responseString.append("ActionPerformer:" +  actionPerformer + "<br>");
533                                                 valid = false;
534                                         };
535                                 }else{
536                                         responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
537                                         valid = false;
538                                 }
539                                 if(policyData.getAttributes() != null){
540                                         for(Object attribute : policyData.getAttributes()){
541                                                 if(attribute instanceof LinkedHashMap<?, ?>){
542                                                         try{
543                                                                 //This is for validation check if the value exists or not
544                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
545                                                                 String value =  ((LinkedHashMap<?, ?>) attribute).get("value").toString();
546                                                                 if("".equals(key) || "".equals(value)){
547                                                                         responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
548                                                                         valid = false;
549                                                                         break;  
550                                                                 }
551                                                         }catch(Exception e){
552                                                                 LOGGER.error("This is a Policy Validation check" +e);
553                                                                 responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
554                                                                 valid = false;
555                                                                 break;
556                                                         }
557                                                 }
558                                         }
559                                 }else{
560                                         responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
561                                         valid = false;
562                                 }
563                                 if(policyData.getActionAttributeValue() != null){
564                                         String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
565                                         if(!actionAttribute.contains("success")){
566                                                 responseString.append("ActionAttribute:" +  actionAttribute + "<br>");
567                                                 valid = false;
568                                         };
569                                 }else{
570                                         responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
571                                         valid = false;
572                                 }                       
573                         }
574                         
575                         if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){
576                                 if(!policyData.getRuleAlgorithmschoices().isEmpty()){
577                                         for(Object attribute : policyData.getRuleAlgorithmschoices()){
578                                                 if(attribute instanceof LinkedHashMap<?, ?>){
579                                                         try{
580                                                                 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
581                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
582                                                                 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
583                                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
584                                                                 if("".equals(label) || "".equals(key) || "".equals(rule)  || "".equals(value)){
585                                                                         responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
586                                                                         valid = false;
587                                                                 }
588                                                         }catch(Exception e){
589                                                                 LOGGER.error("This is a Policy Validation check" +e);
590                                                                 responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
591                                                                 valid = false;
592                                                                 break;
593                                                         }
594                                                 }
595                                         }
596                                 }
597                         }
598
599                         if(policyData.getPolicyType().equals(CONFIG_POLICY)){
600                                 String value = "";
601                                 if(valid){
602                                         List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
603                                         if (!spData.isEmpty()){
604                                                 SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
605                                                 safePolicyWarningData.getMessage();
606                                                 value = "Message:" +  safePolicyWarningData.getMessage();
607                                         }
608                                         responseString.append("success" + "@#"+ value);
609                                 }
610                         }else{
611                                 if(valid){
612                                         responseString.append("success");
613                                 }
614                         }
615
616                         PrintWriter out = response.getWriter();
617                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
618                         JSONObject j = new JSONObject(msg);
619                         out.write(j.toString());
620
621                         return null;
622                 }
623                 catch (Exception e){
624                         LOGGER.error("Exception Occured while Policy Validation" +e);
625                         response.setCharacterEncoding("UTF-8");
626                         request.setCharacterEncoding("UTF-8");
627                         PrintWriter out = response.getWriter();
628                         out.write(e.getMessage());
629                 }
630                 return null;
631         }
632
633         protected String  emptyValidator(String field){
634                 String error;
635                 if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
636                         error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
637                         return error;
638                 } else {
639                         if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
640                                 error = "success";
641                         }else{
642                                 error = "The Value Contains Non ASCII Characters";
643                                 return error;
644                         }       
645                 }
646                 return error;   
647         }
648
649         protected String descriptionValidator(String field) {
650                 String error;
651                 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
652                         error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
653                         return error;
654                 } else {
655                         error = "success";
656                 }
657                 return error;   
658         }
659
660         public String validateEmailAddress(String emailAddressValue) {
661                 String error = "success";
662                 List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
663                 for(int i =0 ; i < emailList.size() ; i++){
664                         pattern = Pattern.compile(EMAIL_PATTERN);
665                         matcher = pattern.matcher(emailList.get(i).trim());
666                         if(!matcher.matches()){
667                                 error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i).toString();
668                                 return error;
669                         }else{
670                                 error = "success";
671                         }
672                 }
673                 return error;           
674         }
675
676         protected String emailValidation(String email, String response){
677                 if(email != null){
678                         String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
679                         if(!validateEmail.contains("success")){
680                                 response += "<b>Email</b>:<i>" +  validateEmail+ "</i><br>";
681                         }else{
682                                 return "success";
683                         }
684                 }
685                 return response;
686         }
687
688         private MicroServiceModels getAttributeObject(String name, String version) {    
689                 MicroServiceModels workingModel = new MicroServiceModels();
690                 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
691                 if(microServiceModelsData != null){
692                         workingModel = (MicroServiceModels) microServiceModelsData.get(0);
693                 }
694                 return workingModel;
695         }
696
697         private void pullJsonKeyPairs(JsonNode rootNode) {
698                 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
699
700                 while (fieldsIterator.hasNext()) {
701                         Map.Entry<String, JsonNode> field = fieldsIterator.next();
702                         final String key = field.getKey();
703                         final JsonNode value = field.getValue();
704                         if (value.isContainerNode() && !value.isArray()) {
705                                 pullJsonKeyPairs(value); // RECURSIVE CALL
706                         } else {
707                                 if (value.isArray()){
708                                         String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
709                                         mapAttribute.put(key, newValue);
710                                 }else {
711                                         mapAttribute.put(key, value.toString().trim());
712                                 }
713                         }
714                 }
715         }
716
717         // Validation for json.
718         protected static boolean isJSONValid(String data) {
719                 JsonReader jsonReader = null;
720                 try {
721                         new JSONObject(data);
722                         InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
723                         jsonReader = Json.createReader(stream);
724                         LOGGER.info("Json Value is: " + jsonReader.read().toString() );
725                 } catch (Exception e) {
726                         LOGGER.error("Exception Occured While Validating"+e);
727                         return false;
728                 }finally{
729                         if(jsonReader != null){
730                                 jsonReader.close();
731                         }
732                 }
733                 return true;
734         }
735
736         // Validation for XML.
737         private boolean isXMLValid(String data) {
738                 SAXParserFactory factory = SAXParserFactory.newInstance();
739                 factory.setValidating(false);
740                 factory.setNamespaceAware(true);
741                 try {
742                         SAXParser parser = factory.newSAXParser();
743                         XMLReader reader = parser.getXMLReader();
744                         reader.setErrorHandler(new XMLErrorHandler());
745                         reader.parse(new InputSource(new StringReader(data)));
746                 } catch (Exception e) {
747                         LOGGER.error("Exception Occured While Validating"+e);
748                         return false;
749                 }
750                 return true;
751         }
752
753         // Validation for Properties file.
754         public boolean isPropValid(String prop) {
755                 Scanner scanner = new Scanner(prop);
756                 while (scanner.hasNextLine()) {
757                         String line = scanner.nextLine();
758                         line = line.replaceAll("\\s+", "");
759                         if (line.startsWith("#")) {
760                                 continue;
761                         } else {
762                                 if (line.contains("=")) {
763                                         String[] parts = line.split("=");
764                                         if (parts.length < 2) {
765                                                 scanner.close();
766                                                 return false;
767                                         }
768                                 } else {
769                                         scanner.close();
770                                         return false;
771                                 }
772                         }
773                 }
774                 scanner.close();
775                 return true;
776         }
777
778 }