[Policy-20] getConfig & Policy resolved blockers
[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.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.openecomp.policy.common.logging.flexlogger.FlexLogger;
51 import org.openecomp.policy.common.logging.flexlogger.Logger;
52 import org.openecomp.policy.rest.adapter.ClosedLoopFaultBody;
53 import org.openecomp.policy.rest.adapter.ClosedLoopPMBody;
54 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
55 import org.openecomp.policy.rest.dao.CommonClassDao;
56 import org.openecomp.policy.rest.jpa.MicroServiceModels;
57 import org.openecomp.policy.rest.jpa.SafePolicyWarning;
58 import org.openecomp.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.getEcompName() != null){
130                                                 String ecompNameValidate = emptyValidator(policyData.getEcompName());
131                                                 if(!ecompNameValidate.contains("success")){
132                                                         responseString.append("EcompName:" +  ecompNameValidate + "<br>");
133                                                         valid = false;
134                                                 }
135                                         }else{
136                                                 responseString.append("Ecomp Name: Ecomp 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 (isInteger(value.replace("\"", ""))){
405                                                                                 int result = Integer.parseInt(value.replace("\"", ""));
406
407
408                                                                                 if (result < startNum || result > endNum){
409                                                                                         responseString.append(returnString);                                                                    
410                                                                                         valid = false;
411                                                                                 }
412                                                                         }else {
413                                                                                 responseString.append(returnString);
414                                                                                 valid = false;
415                                                                         }
416                                                                 }
417                                                         }
418                                                 }
419                                         }else{
420                                                 responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
421                                                 valid = false;
422                                         }
423
424                                         if(policyData.getPriority() == null){
425                                                 responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
426                                                 valid = false;
427                                         }
428                                 }       
429                         }
430                         if (policyData.getPolicyType().equals(DECISION_POLICY)){
431                                 if(policyData.getEcompName() != null){
432                                         String ecompNameValidate = emptyValidator(policyData.getEcompName());
433                                         if(!ecompNameValidate.contains("success")){
434                                                 responseString.append("EcompName:" +  ecompNameValidate + "<br>");
435                                                 valid = false;
436                                         }
437                                 }else{
438                                         responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "<br>");
439                                         valid = false;
440                                 }
441                                 if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
442                                         if(policyData.getYamlparams()==null){
443                                                 responseString.append("<b> Guard Params are Required </b>" + "<br>");
444                                                 valid = false;
445                                         }else{
446                                                 if(policyData.getYamlparams().getActor()==null){
447                                                         responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
448                                                         valid = false;
449                                                 }
450                                                 if(policyData.getYamlparams().getRecipe()==null){
451                                                         responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
452                                                         valid = false;
453                                                 }
454                                                 if(policyData.getYamlparams().getGuardActiveStart()==null){
455                                                         responseString.append("Guard Params <b>Guard Active Start/b>is Required " + "<br>");
456                                                         valid = false;
457                                                 }
458                                                 if(policyData.getYamlparams().getGuardActiveEnd()==null){
459                                                         responseString.append("Guard Params <b>Guard Active End</b>is Required " + "<br>");
460                                                         valid = false;
461                                                 }
462                                                 if("GUARD_YAML".equals(policyData.getRuleProvider())){
463                                                         if(policyData.getYamlparams().getLimit()==null){
464                                                                 responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
465                                                                 valid = false;
466                                                         }else if(!isInteger(policyData.getYamlparams().getLimit())){
467                                                                 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
468                                                                 valid = false;
469                                                         }
470                                                         if(policyData.getYamlparams().getTimeWindow()==null){
471                                                                 responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
472                                                                 valid = false;
473                                                         }
474                                                 }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
475                                                         if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
476                                                                 responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
477                                                                 valid = false;
478                                                         }else{
479                                                                 for(String blackList: policyData.getYamlparams().getBlackList()){
480                                                                         if(blackList==null || !("success".equals(emptyValidator(blackList)))){
481                                                                                 responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
482                                                                                 valid = false;
483                                                                                 break;
484                                                                         }
485                                                                 }
486                                                         }
487                                                 }
488                                         }
489                                 }
490                         }
491
492                         if(policyData.getPolicyType().equals(ACTION_POLICY)){
493                                 if(policyData.getActionPerformer() != null){
494                                         String actionPerformer = emptyValidator(policyData.getActionPerformer());
495                                         if(!actionPerformer.contains("success")){
496                                                 responseString.append("ActionPerformer:" +  actionPerformer + "<br>");
497                                                 valid = false;
498                                         };
499                                 }else{
500                                         responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
501                                         valid = false;
502                                 }
503                                 if(policyData.getAttributes() != null){
504                                         for(Object attribute : policyData.getAttributes()){
505                                                 if(attribute instanceof LinkedHashMap<?, ?>){
506                                                         try{
507                                                                 //This is for validation check if the value exists or not
508                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
509                                                                 String value =  ((LinkedHashMap<?, ?>) attribute).get("value").toString();
510                                                                 if("".equals(key) || "".equals(value)){
511                                                                         responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
512                                                                         valid = false;
513                                                                         break;  
514                                                                 }
515                                                         }catch(Exception e){
516                                                                 LOGGER.error("This is a Policy Validation check" +e);
517                                                                 responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
518                                                                 valid = false;
519                                                                 break;
520                                                         }
521                                                 }
522                                         }
523                                 }else{
524                                         responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
525                                         valid = false;
526                                 }
527                                 if(policyData.getActionAttributeValue() != null){
528                                         String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
529                                         if(!actionAttribute.contains("success")){
530                                                 responseString.append("ActionAttribute:" +  actionAttribute + "<br>");
531                                                 valid = false;
532                                         };
533                                 }else{
534                                         responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
535                                         valid = false;
536                                 }                       
537                         }
538                         
539                         if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){
540                                 if(!policyData.getRuleAlgorithmschoices().isEmpty()){
541                                         for(Object attribute : policyData.getRuleAlgorithmschoices()){
542                                                 if(attribute instanceof LinkedHashMap<?, ?>){
543                                                         try{
544                                                                 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
545                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
546                                                                 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
547                                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
548                                                                 if("".equals(label) || "".equals(key) || "".equals(rule)  || "".equals(value)){
549                                                                         responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
550                                                                         valid = false;
551                                                                 }
552                                                         }catch(Exception e){
553                                                                 LOGGER.error("This is a Policy Validation check" +e);
554                                                                 responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
555                                                                 valid = false;
556                                                                 break;
557                                                         }
558                                                 }
559                                         }
560                                 }
561                         }
562
563                         if(policyData.getPolicyType().equals(CONFIG_POLICY)){
564                                 String value = "";
565                                 if(valid){
566                                         List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
567                                         if (!spData.isEmpty()){
568                                                 SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
569                                                 safePolicyWarningData.getMessage();
570                                                 value = "Message:" +  safePolicyWarningData.getMessage();
571                                         }
572                                         responseString.append("success" + "@#"+ value);
573                                 }
574                         }else{
575                                 if(valid){
576                                         responseString.append("success");
577                                 }
578                         }
579
580                         PrintWriter out = response.getWriter();
581                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
582                         JSONObject j = new JSONObject(msg);
583                         out.write(j.toString());
584
585                         return null;
586                 }
587                 catch (Exception e){
588                         LOGGER.error("Exception Occured while Policy Validation" +e);
589                         response.setCharacterEncoding("UTF-8");
590                         request.setCharacterEncoding("UTF-8");
591                         PrintWriter out = response.getWriter();
592                         out.write(e.getMessage());
593                 }
594                 return null;
595         }
596
597         protected boolean isInteger(String number) {
598                 try{
599                         Integer.parseInt(number);
600                 }catch(NumberFormatException e){
601                         return false;
602                 }
603                 return true;
604         }
605
606         protected String  emptyValidator(String field){
607                 String error;
608                 if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
609                         error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
610                         return error;
611                 } else {
612                         if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
613                                 error = "success";
614                         }else{
615                                 error = "The Value Contains Non ASCII Characters";
616                                 return error;
617                         }       
618                 }
619                 return error;   
620         }
621
622         protected String descriptionValidator(String field) {
623                 String error;
624                 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
625                         error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
626                         return error;
627                 } else {
628                         error = "success";
629                 }
630                 return error;   
631         }
632
633         public String validateEmailAddress(String emailAddressValue) {
634                 String error = "success";
635                 List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
636                 for(int i =0 ; i < emailList.size() ; i++){
637                         pattern = Pattern.compile(EMAIL_PATTERN);
638                         matcher = pattern.matcher(emailList.get(i).trim());
639                         if(!matcher.matches()){
640                                 error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i).toString();
641                                 return error;
642                         }else{
643                                 error = "success";
644                         }
645                 }
646                 return error;           
647         }
648
649         protected String emailValidation(String email, String response){
650                 if(email != null){
651                         String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
652                         if(!validateEmail.contains("success")){
653                                 response += "<b>Email</b>:<i>" +  validateEmail+ "</i><br>";
654                         }else{
655                                 return "success";
656                         }
657                 }
658                 return response;
659         }
660
661         private MicroServiceModels getAttributeObject(String name, String version) {    
662                 MicroServiceModels workingModel = new MicroServiceModels();
663                 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
664                 if(microServiceModelsData != null){
665                         workingModel = (MicroServiceModels) microServiceModelsData.get(0);
666                 }
667                 return workingModel;
668         }
669
670         private void pullJsonKeyPairs(JsonNode rootNode) {
671                 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
672
673                 while (fieldsIterator.hasNext()) {
674                         Map.Entry<String, JsonNode> field = fieldsIterator.next();
675                         final String key = field.getKey();
676                         final JsonNode value = field.getValue();
677                         if (value.isContainerNode() && !value.isArray()) {
678                                 pullJsonKeyPairs(value); // RECURSIVE CALL
679                         } else {
680                                 if (value.isArray()){
681                                         String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
682                                         mapAttribute.put(key, newValue);
683                                 }else {
684                                         mapAttribute.put(key, value.toString().trim());
685                                 }
686                         }
687                 }
688         }
689
690         // Validation for json.
691         protected static boolean isJSONValid(String data) {
692                 JsonReader jsonReader = null;
693                 try {
694                         new JSONObject(data);
695                         InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
696                         jsonReader = Json.createReader(stream);
697                         LOGGER.info("Json Value is: " + jsonReader.read().toString() );
698                 } catch (Exception e) {
699                         LOGGER.error("Exception Occured While Validating"+e);
700                         return false;
701                 }finally{
702                         if(jsonReader != null){
703                                 jsonReader.close();
704                         }
705                 }
706                 return true;
707         }
708
709         // Validation for XML.
710         private boolean isXMLValid(String data) {
711                 SAXParserFactory factory = SAXParserFactory.newInstance();
712                 factory.setValidating(false);
713                 factory.setNamespaceAware(true);
714                 try {
715                         SAXParser parser = factory.newSAXParser();
716                         XMLReader reader = parser.getXMLReader();
717                         reader.setErrorHandler(new XMLErrorHandler());
718                         reader.parse(new InputSource(new StringReader(data)));
719                 } catch (Exception e) {
720                         LOGGER.error("Exception Occured While Validating"+e);
721                         return false;
722                 }
723                 return true;
724         }
725
726         // Validation for Properties file.
727         public boolean isPropValid(String prop) {
728                 Scanner scanner = new Scanner(prop);
729                 while (scanner.hasNextLine()) {
730                         String line = scanner.nextLine();
731                         line = line.replaceAll("\\s+", "");
732                         if (line.startsWith("#")) {
733                                 continue;
734                         } else {
735                                 if (line.contains("=")) {
736                                         String[] parts = line.split("=");
737                                         if (parts.length < 2) {
738                                                 scanner.close();
739                                                 return false;
740                                         }
741                                 } else {
742                                         scanner.close();
743                                         return false;
744                                 }
745                         }
746                 }
747                 scanner.close();
748                 return true;
749         }
750
751 }