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