Policy 1707 commit to LF
[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.rest.adapter.ClosedLoopFaultBody;
52 import org.openecomp.policy.rest.adapter.ClosedLoopPMBody;
53 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
54 import org.openecomp.policy.rest.dao.CommonClassDao;
55 import org.openecomp.policy.rest.jpa.MicroServiceModels;
56 import org.openecomp.policy.rest.jpa.SafePolicyWarning;
57 import org.openecomp.policy.utils.PolicyUtils;
58 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
59 import org.openecomp.portalsdk.core.web.support.JsonMessage;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.stereotype.Controller;
62 import org.springframework.web.bind.annotation.RequestMapping;
63 import org.springframework.web.servlet.ModelAndView;
64 import org.xml.sax.InputSource;
65 import org.xml.sax.SAXException;
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         public static final String CONFIG_POLICY = "Config";
80         public static final String ACTION_POLICY = "Action";
81         public static final String DECISION_POLICY = "Decision";
82         public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
83         public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
84         public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
85         public static final String MICROSERVICES="Micro Service";
86         private Pattern pattern;
87         private Matcher matcher;
88
89         private static Map<String, String> rangeMap = new HashMap<String,String>();
90         private static Map<String, String> mapAttribute = new HashMap<String,String>();
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                         String responseString = "";
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 = responseString + "PolicyName:" +  policyNameValidate + "<br>";
112                                         valid = false;
113                                 };
114                         }else{
115                                 responseString = responseString + "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 = responseString + "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 = responseString + "EcompName:" +  ecompNameValidate + "<br>";
133                                                         valid = false;
134                                                 }
135                                         }else{
136                                                 responseString = responseString + "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 = responseString + "RiskType:" +  riskTypeValidate + "<br>";
145                                                 valid = false;
146                                         }
147                                 }else {
148                                         responseString = responseString + "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 = responseString + "RiskLevel:" +  validateRiskLevel + "<br>";
156                                                 valid = false;
157                                         }
158                                 }else {
159                                         responseString = responseString + "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 = responseString + "Guard:" +  validateGuard + "<br>";
167                                                 valid = false;
168                                         }
169                                 }else {
170                                         responseString = responseString + "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 = responseString + "ConfigName:" +  configNameValidate + "<br>";
179                                                         valid = false;
180                                                 }
181                                         }else{
182                                                 responseString = responseString + "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 = responseString + "ConfigType:" +  configTypeValidate + "<br>";
189                                                         valid = false;
190                                                 }
191                                         }else{
192                                                 responseString = responseString + "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 = responseString + "Config Body: JSON Content is not valid" + "<br>";
202                                                                         valid = false;
203                                                                 }
204                                                         } else if (policyType.equals("XML")) {
205                                                                 if (!isXMLValid(configBodyData)) {
206                                                                         responseString = responseString + "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 = responseString + "Config Body: Property data is not valid" + "<br>";
212                                                                         valid = false;
213                                                                 } 
214                                                         } else if (policyType.equals("OTHER")) {
215                                                                 if (configBodyData.equals("")) {
216                                                                         responseString = responseString + "Config Body: Config Body Should not be Empty" + "<br>";
217                                                                         valid = false;
218                                                                 }
219                                                         }
220                                                 }
221                                         }else{
222                                                 responseString = responseString + "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 = responseString + "<b>ConfigName</b>:<i>" +  configNameValidate + "</i><br>";
232                                                         valid = false;
233                                                 }
234                                         }else{
235                                                 responseString = responseString + "<b>Config Name</b>:<i> Config Name is required" + "</i><br>";
236                                                 valid = false;
237                                         }
238                                         if(policyData.getSecurityZone() == null){
239                                                 responseString = responseString + "<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 = responseString + "<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 = responseString + "<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>";
255                                                         valid = false;
256                                                 }
257                                         }else{
258                                                 responseString = responseString + "<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 = responseString + "<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>";
266                                                         valid = false; 
267                                                 }
268                                         }catch(Exception e){
269                                                 responseString = responseString + "<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);
277                                                         if(result != "success"){
278                                                                 responseString = 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 = responseString + "<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 = responseString + "<b>Attributes</b>:<i>" +  key + " : value has spaces</i><br>";
297                                                                                 valid = false;
298                                                                         };
299                                                                 }
300                                                         }       
301                                                 }
302                                         }else{
303                                                 responseString = responseString + "<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);
312                                                         if(result != "success"){
313                                                                 responseString = result+ "<br>";
314                                                                 valid = false;
315                                                         }
316                                                 }
317                                                 if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
318                                                         responseString = responseString + "<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 = responseString + "<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>";
323                                                         valid = false;
324                                                 }
325                                                 if(faultBody.getAgingWindow() == 0){
326                                                         responseString = responseString + "<b>Aging Window</b>:<i>Aging Window is required</i><br>";
327                                                         valid = false;
328                                                 }
329                                                 if(faultBody.getClosedLoopPolicyStatus() == null){
330                                                         responseString = responseString + "<b>Policy Status</b>:<i>Policy Status is required</i><br>";
331                                                         valid = false;
332                                                 }
333                                                 if(faultBody.getConditions() == null){
334                                                         responseString = responseString + "<b>Conditions</b>:<i>Select Atleast one Condition</i><br>";
335                                                         valid = false;
336                                                 }
337                                                 if(faultBody.getGeoLink() != null){
338                                                         String result = PolicyUtils.emptyPolicyValidator(faultBody.getGeoLink());
339                                                         if(!result.contains("success")){
340                                                                 responseString = responseString + "<b>GeoLink</b>:<i>" +  result + "</i><br>";
341                                                                 valid = false;
342                                                         };
343                                                 }
344
345                                                 if(faultBody.getTimeInterval() == 0){
346                                                         responseString = responseString + "<b>Time Interval</b>:<i>Time Interval is required</i><br>";
347                                                         valid = false;
348                                                 }
349                                                 if(faultBody.getRetrys() == 0){
350                                                         responseString = responseString + "<b>Number of Retries</b>:<i>Number of Retries is required</i><br>";
351                                                         valid = false;
352                                                 }
353                                                 if(faultBody.getTimeOutvPRO() == 0){
354                                                         responseString = responseString + "<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>";
355                                                         valid = false;
356                                                 }
357                                                 if(faultBody.getTimeOutRuby() == 0){
358                                                         responseString = responseString + "<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>";
359                                                         valid = false;
360                                                 }
361                                                 if(faultBody.getVnfType() == null){
362                                                         responseString = responseString + "<b>Vnf Type</b>:<i>Vnf Type is required</i><br>";
363                                                         valid = false;
364                                                 }
365                                         }else{
366                                                 responseString = responseString + "<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>";
367                                                 responseString = responseString + "<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>";
368                                                 responseString = responseString + "<b>Aging Window</b>:<i>Aging Window is required</i><br>";
369                                                 responseString = responseString + "<b>Policy Status</b>:<i>Policy Status is required</i><br>";
370                                                 responseString = responseString + "<b>Conditions</b>:<i>Select Atleast one Condition</i><br>";
371                                                 responseString = responseString + "<b>PEP Name</b>:<i>PEP Name is required</i><br>";
372                                                 responseString = responseString + "<b>PEP Action</b>:<i>PEP Action is required</i><br>";
373                                                 responseString = responseString + "<b>Time Interval</b>:<i>Time Interval is required</i><br>";
374                                                 responseString = responseString + "<b>Number of Retries</b>:<i>Number of Retries is required</i><br>";
375                                                 responseString = responseString + "<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>";
376                                                 responseString = responseString + "<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>";
377                                                 responseString = responseString + "<b>Vnf Type</b>:<i>Vnf Type is required</i><br>";
378                                                 valid = false; 
379                                         }
380                                 }
381
382                                 if (policyData.getConfigPolicyType().contains("Micro Service")){
383                                         if(policyData.getServiceType() != null){
384                                                 pullJsonKeyPairs(root.get("policyJSON"));
385                                                 MicroServiceModels returnModel = new MicroServiceModels();
386                                                 String service = null;
387                                                 String version = null;
388                                                 if (policyData.getServiceType().contains("-v")){
389                                                         service = policyData.getServiceType().split("-v")[0];
390                                                         version = policyData.getServiceType().split("-v")[1];
391                                                 }else {
392                                                         service = policyData.getServiceType();
393                                                         version = policyData.getVersion();
394                                                 }
395                                                 returnModel = getAttributeObject(service, version);
396                                                 String annoation = returnModel.getAnnotation();
397                                                 if (!Strings.isNullOrEmpty(annoation)){
398                                                         rangeMap = new HashMap<String,String>();
399                                                         rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation);
400                                                         for (Entry<String, String> rMap : rangeMap.entrySet()){
401                                                                 if (rMap.getValue().contains("range::")){
402                                                                         String value = mapAttribute.get(rMap.getKey().trim());
403                                                                         String[] tempString = rMap.getValue().split("::")[1].split("-");
404                                                                         int startNum = Integer.parseInt(tempString[0]);
405                                                                         int endNum = Integer.parseInt(tempString[1]);
406                                                                         String returnString = "Invalid Range:" + rMap.getKey() + " must be between " 
407                                                                                         + startNum + " - "  + endNum + ",";
408                                                                         if (isType(value.replace("\"", ""))){
409                                                                                 int result = Integer.parseInt(value.replace("\"", ""));
410
411
412                                                                                 if (result < startNum || result > endNum){
413                                                                                         responseString = responseString + returnString;                                                                 
414                                                                                         valid = false;
415                                                                                 }
416                                                                         }else {
417                                                                                 responseString = responseString + returnString;
418                                                                                 valid = false;
419                                                                         }
420                                                                 }
421                                                         }
422                                                 }
423                                                 //for continue testing for Dkat, just blocked this validation until fixing it. gw1218 on 3/30/17
424                                                 //if (!checkAttributeValues()){
425                                                 //responseString = responseString + "<b>Micro Service</b>:<i>  Attribute Values Missing" + "</i><br>";
426                                                 //valid = false;
427                                                 //} 
428
429                                         }else{
430                                                 responseString = responseString + "<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>";
431                                                 valid = false;
432                                         }
433
434                                         if(policyData.getPriority() == null){
435                                                 responseString = responseString + "<b>Priority</b>:<i> Priority is required" + "</i><br>";
436                                                 valid = false;
437                                         }
438                                 }       
439                         }
440                         if (policyData.getPolicyType().equals(DECISION_POLICY)){
441                                 if(policyData.getEcompName() != null){
442                                         String ecompNameValidate = emptyValidator(policyData.getEcompName());
443                                         if(!ecompNameValidate.contains("success")){
444                                                 responseString = responseString + "EcompName:" +  ecompNameValidate + "<br>";
445                                                 valid = false;
446                                         }
447                                 }else{
448                                         responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "<br>";
449                                         valid = false;
450                                 }
451
452                         }
453
454                         if(policyData.getPolicyType().equals(ACTION_POLICY)){
455                                 if(policyData.getActionPerformer() != null){
456                                         String actionPerformer = emptyValidator(policyData.getActionPerformer());
457                                         if(!actionPerformer.contains("success")){
458                                                 responseString = responseString + "ActionPerformer:" +  actionPerformer + "<br>";
459                                                 valid = false;
460                                         };
461                                 }else{
462                                         responseString = responseString + "ActionPerformer: ActionPerformer Should not be empty" + "<br>";
463                                         valid = false;
464                                 }
465                                 if(policyData.getActionAttributeValue() != null){
466                                         String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
467                                         if(!actionAttribute.contains("success")){
468                                                 responseString = responseString + "ActionAttribute:" +  actionAttribute + "<br>";
469                                                 valid = false;
470                                         };
471                                 }else{
472                                         responseString = responseString + "ActionAttribute: ActionAttribute Should not be empty" + "<br>";
473                                         valid = false;
474                                 }                       
475                         }
476
477                         if(policyData.getPolicyType().equals(CONFIG_POLICY)){
478                                 if(valid){
479                                         List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
480                                         if (!spData.isEmpty()){
481                                                 SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
482                                                 safePolicyWarningData.getMessage();
483                                                 responseString = responseString + "Messaage:" +  safePolicyWarningData.getMessage();
484                                         }
485                                         responseString = "success" + "@#"+ responseString;
486                                 }
487                         }else{
488                                 if(valid){
489                                         responseString = "success";
490                                 }
491                         }
492
493                         PrintWriter out = response.getWriter();
494                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString));
495                         JSONObject j = new JSONObject(msg);
496                         out.write(j.toString());
497
498                         return null;
499                 }
500                 catch (Exception e){
501                         response.setCharacterEncoding("UTF-8");
502                         request.setCharacterEncoding("UTF-8");
503                         PrintWriter out = response.getWriter();
504                         out.write(e.getMessage());
505                 }
506                 return null;
507         }
508
509         protected String  emptyValidator(String field){
510                 String error = "success";
511                 if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
512                         error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
513                         return error;
514                 } else {
515                         if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
516                                 error = "success";
517                         }else{
518                                 error = "The Value Contains Non ASCII Characters";
519                                 return error;
520                         }       
521                 }
522                 return error;   
523         }
524
525         protected String descriptionValidator(String field) {
526                 String error = "success";
527                 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
528                         error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
529                         return error;
530                 } else {
531                         error = "success";
532                 }
533                 return error;   
534         }
535
536         public String validateEmailAddress(String emailAddressValue) {
537                 String error = "success";
538                 List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
539                 for(int i =0 ; i < emailList.size() ; i++){
540                         pattern = Pattern.compile(EMAIL_PATTERN);
541                         matcher = pattern.matcher(emailList.get(i).trim());
542                         if(!matcher.matches()){
543                                 error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i).toString();
544                                 return error;
545                         }else{
546                                 error = "success";
547                         }
548                 }
549                 return error;           
550         }
551
552         protected String emailValidation(String email, String responseString){
553                 if(email != null){
554                         String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
555                         if(!validateEmail.contains("success")){
556                                 responseString = responseString + "<b>Email</b>:<i>" +  validateEmail+ "</i><br>";
557                         }else{
558                                 return "success";
559                         }
560                 }
561                 return responseString;
562         }
563
564         private MicroServiceModels getAttributeObject(String name, String version) {    
565                 MicroServiceModels workingModel = new MicroServiceModels();
566                 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
567                 if(microServiceModelsData != null){
568                         workingModel = (MicroServiceModels) microServiceModelsData.get(0);
569                 }
570                 return workingModel;
571         }
572
573         private void pullJsonKeyPairs(JsonNode rootNode) {
574                 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
575
576                 while (fieldsIterator.hasNext()) {
577                         Map.Entry<String, JsonNode> field = fieldsIterator.next();
578                         final String key = field.getKey();
579                         final JsonNode value = field.getValue();
580                         if (value.isContainerNode() && !value.isArray()) {
581                                 pullJsonKeyPairs(value); // RECURSIVE CALL
582                         } else {
583                                 if (value.isArray()){
584                                         String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
585                                         mapAttribute.put(key, newValue);
586                                 }else {
587                                         mapAttribute.put(key, value.toString().trim());
588                                 }
589                         }
590                 }
591         }
592
593         private Boolean isType(String testStr) {
594                 try {
595                         Integer.parseInt(testStr);
596                         return true;
597                 } catch(Exception e) {
598                         return false;
599                 }
600         }
601
602         // Validation for json.
603         protected static boolean isJSONValid(String data) {
604                 try {
605                         new JSONObject(data);
606                         InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
607                         JsonReader jsonReader = Json.createReader(stream);
608                         System.out.println("Json Value is: " + jsonReader.read().toString() );
609                 } catch (Exception e) {
610                         e.printStackTrace();
611                         return false;
612                 }
613                 return true;
614         }
615
616         // Validation for XML.
617         private boolean isXMLValid(String data) {
618                 SAXParserFactory factory = SAXParserFactory.newInstance();
619                 factory.setValidating(false);
620                 factory.setNamespaceAware(true);
621                 try {
622                         SAXParser parser = factory.newSAXParser();
623                         XMLReader reader = parser.getXMLReader();
624                         reader.setErrorHandler(new XMLErrorHandler());
625                         reader.parse(new InputSource(new StringReader(data)));
626                 } catch (ParserConfigurationException e) {
627                         return false;
628                 } catch (SAXException e) {
629                         return false;
630                 } catch (IOException e) {
631                         return false;
632                 }
633                 return true;
634         }
635
636         // Validation for Properties file.
637         public boolean isPropValid(String prop) {
638                 Scanner scanner = new Scanner(prop);
639                 while (scanner.hasNextLine()) {
640                         String line = scanner.nextLine();
641                         line.replaceAll("\\s+", "");
642                         if (line.startsWith("#")) {
643                                 continue;
644                         } else {
645                                 if (line.contains("=")) {
646                                         String[] parts = line.split("=");
647                                         if (parts.length < 2) {
648                                                 scanner.close();
649                                                 return false;
650                                         }
651                                 } else {
652                                         scanner.close();
653                                         return false;
654                                 }
655                         }
656                 }
657                 scanner.close();
658                 return true;
659         }
660
661 }