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