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