2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.policy.controller;
24 import java.io.ByteArrayInputStream;
25 import java.io.InputStream;
26 import java.io.PrintWriter;
27 import java.io.StringReader;
28 import java.nio.charset.StandardCharsets;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.LinkedHashMap;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Scanner;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
40 import javax.json.Json;
41 import javax.json.JsonReader;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44 import javax.xml.parsers.SAXParser;
45 import javax.xml.parsers.SAXParserFactory;
47 import org.apache.commons.lang.StringUtils;
48 import org.dom4j.util.XMLErrorHandler;
49 import org.json.JSONObject;
50 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
51 import org.openecomp.policy.common.logging.flexlogger.Logger;
52 import org.openecomp.policy.rest.adapter.ClosedLoopFaultBody;
53 import org.openecomp.policy.rest.adapter.ClosedLoopPMBody;
54 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
55 import org.openecomp.policy.rest.dao.CommonClassDao;
56 import org.openecomp.policy.rest.jpa.MicroServiceModels;
57 import org.openecomp.policy.rest.jpa.SafePolicyWarning;
58 import org.openecomp.policy.utils.PolicyUtils;
59 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
60 import org.openecomp.portalsdk.core.web.support.JsonMessage;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.stereotype.Controller;
63 import org.springframework.web.bind.annotation.RequestMapping;
64 import org.springframework.web.servlet.ModelAndView;
65 import org.xml.sax.InputSource;
66 import org.xml.sax.XMLReader;
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;
77 public class PolicyValidationController extends RestrictedBaseController {
79 private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class);
81 public static final String CONFIG_POLICY = "Config";
82 public static final String ACTION_POLICY = "Action";
83 public static final String DECISION_POLICY = "Decision";
84 public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
85 public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
86 public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
87 public static final String MICROSERVICES="Micro Service";
88 private Pattern pattern;
89 private Matcher matcher;
90 private static Map<String, String> mapAttribute = new HashMap<>();
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,})$";
97 CommonClassDao commonClassDao;
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{
102 boolean valid = true;
103 StringBuilder responseString = new StringBuilder();
104 ObjectMapper mapper = new ObjectMapper();
105 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
106 JsonNode root = mapper.readTree(request.getReader());
107 PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
108 if(policyData.getPolicyName() != null){
109 String policyNameValidate = emptyValidator(policyData.getPolicyName());
110 if(!policyNameValidate.contains("success")){
111 responseString.append("PolicyName:" + policyNameValidate + "<br>");
115 responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
118 if(policyData.getPolicyDescription() != null){
119 String descriptionValidate = descriptionValidator(policyData.getPolicyDescription());
120 if(!descriptionValidate.contains("success")){
121 responseString.append("Description:" + descriptionValidate + "<br>");
126 if(policyData.getPolicyType().equals(CONFIG_POLICY)){
127 if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY)
128 || policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) {
129 if(policyData.getEcompName() != null){
130 String ecompNameValidate = emptyValidator(policyData.getEcompName());
131 if(!ecompNameValidate.contains("success")){
132 responseString.append("EcompName:" + ecompNameValidate + "<br>");
136 responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "<br>");
141 if(policyData.getRiskType() != null){
142 String riskTypeValidate = emptyValidator(policyData.getRiskType());
143 if(!riskTypeValidate.contains("success")){
144 responseString.append("RiskType:" + riskTypeValidate + "<br>");
148 responseString.append("Risk Type: Risk Type Should not be Empty" + "<br>");
152 if(policyData.getRiskLevel() != null){
153 String validateRiskLevel = emptyValidator(policyData.getRiskLevel());
154 if(!validateRiskLevel.contains("success")){
155 responseString.append("RiskLevel:" + validateRiskLevel + "<br>");
159 responseString.append("Risk Level: Risk Level Should not be Empty" + "<br>");
163 if(policyData.getGuard() != null){
164 String validateGuard = emptyValidator(policyData.getGuard());
165 if(!validateGuard.contains("success")){
166 responseString.append("Guard:" + validateGuard + "<br>");
170 responseString.append("Guard: Guard Value Should not be Empty" + "<br>");
174 if(policyData.getConfigPolicyType().equals("Base")){
175 if(policyData.getConfigName() != null){
176 String configNameValidate = emptyValidator(policyData.getConfigName());
177 if(!configNameValidate.contains("success")){
178 responseString.append("ConfigName:" + configNameValidate + "<br>");
182 responseString.append("Config Name: Config Name Should not be Empty" + "<br>");
185 if(policyData.getConfigType() != null){
186 String configTypeValidate = emptyValidator(policyData.getConfigType());
187 if(!configTypeValidate.contains("success")){
188 responseString.append("ConfigType:" + configTypeValidate + "<br>");
192 responseString.append("Config Type: Config Type Should not be Empty" + "<br>");
195 if(policyData.getConfigBodyData() != null){
196 String configBodyData = policyData.getConfigBodyData();
197 String policyType = policyData.getConfigType();
198 if (policyType != null) {
199 if (policyType.equals("JSON")) {
200 if (!isJSONValid(configBodyData)) {
201 responseString.append("Config Body: JSON Content is not valid" + "<br>");
204 } else if (policyType.equals("XML")) {
205 if (!isXMLValid(configBodyData)) {
206 responseString.append("Config Body: XML Content data is not valid" + "<br>");
209 } else if (policyType.equals("PROPERTIES")) {
210 if (!isPropValid(configBodyData)||configBodyData.equals("")) {
211 responseString.append("Config Body: Property data is not valid" + "<br>");
214 } else if (policyType.equals("OTHER")) {
215 if (configBodyData.equals("")) {
216 responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
222 responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
227 if(policyData.getConfigPolicyType().equals("Firewall Config")){
228 if(policyData.getConfigName() != null){
229 String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName());
230 if(!configNameValidate.contains("success")){
231 responseString.append("<b>ConfigName</b>:<i>" + configNameValidate + "</i><br>");
235 responseString.append("<b>Config Name</b>:<i> Config Name is required" + "</i><br>");
238 if(policyData.getSecurityZone() == null){
239 responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>");
243 if(policyData.getConfigPolicyType().equals("BRMS_Param")){
244 if(policyData.getRuleName() == null){
245 responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required</i><br>");
249 if(policyData.getConfigPolicyType().equals("BRMS_Raw")){
250 if(policyData.getConfigBodyData() != null){
251 String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
252 // If there are any error other than Annotations then this is not Valid
253 if(message.contains("[ERR")){
254 responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>");
258 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required</i><br>");
262 if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){
264 if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){
265 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
269 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
273 if(root.get("policyData").get("jsonBodyData") != null){
274 ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class);
275 if(pmBody.getEmailAddress() != null){
276 String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
277 if(result != "success"){
278 responseString.append(result + "<br>");
282 if(pmBody.getGeoLink() != null){
283 String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink());
284 if(!result.contains("success")){
285 responseString.append("<b>GeoLink</b>:<i>" + result + "</i><br>");
289 if(pmBody.getAttributes() != null){
290 for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
291 String key = entry.getKey();
292 String value = entry.getValue();
293 if(!key.contains("Message")){
294 String attributeValidate = PolicyUtils.emptyPolicyValidator(value);
295 if(!attributeValidate.contains("success")){
296 responseString.append("<b>Attributes</b>:<i>" + key + " : value has spaces</i><br>");
303 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
307 if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){
308 if(root.get("policyData").get("jsonBodyData") != null){
309 ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
310 if(faultBody.getEmailAddress() != null){
311 String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
312 if(result != "success"){
313 responseString.append(result+ "<br>");
317 if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
318 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
321 if(faultBody.getActions() == null){
322 responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
325 if(faultBody.getClosedLoopPolicyStatus() == null){
326 responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
329 if(faultBody.getConditions() == null){
330 responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
333 if(faultBody.getGeoLink() != null){
334 String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink());
335 if(!result.contains("success")){
336 responseString.append("<b>GeoLink</b>:<i>" + result + "</i><br>");
341 if(faultBody.getTimeInterval() == 0){
342 responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
345 if(faultBody.getRetrys() == 0){
346 responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
349 if(faultBody.getTimeOutvPRO() == 0){
350 responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
353 if(faultBody.getTimeOutRuby() == 0){
354 responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
357 if(faultBody.getVnfType() == null){
358 responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
362 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
363 responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
364 responseString.append("<b>Aging Window</b>:<i>Aging Window is required</i><br>");
365 responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
366 responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
367 responseString.append("<b>PEP Name</b>:<i>PEP Name is required</i><br>");
368 responseString.append("<b>PEP Action</b>:<i>PEP Action is required</i><br>");
369 responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
370 responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
371 responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
372 responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
373 responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
378 if (policyData.getConfigPolicyType().contains("Micro Service")){
379 if(policyData.getServiceType() != null){
380 pullJsonKeyPairs(root.get("policyJSON"));
381 MicroServiceModels returnModel = new MicroServiceModels();
382 String service = null;
383 String version = null;
384 if (policyData.getServiceType().contains("-v")){
385 service = policyData.getServiceType().split("-v")[0];
386 version = policyData.getServiceType().split("-v")[1];
388 service = policyData.getServiceType();
389 version = policyData.getVersion();
391 returnModel = getAttributeObject(service, version);
392 String annoation = returnModel.getAnnotation();
393 if (!Strings.isNullOrEmpty(annoation)){
394 Map<String, String> rangeMap = new HashMap<>();
395 rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation);
396 for (Entry<String, String> rMap : rangeMap.entrySet()){
397 if (rMap.getValue().contains("range::")){
398 String value = mapAttribute.get(rMap.getKey().trim());
399 String[] tempString = rMap.getValue().split("::")[1].split("-");
400 int startNum = Integer.parseInt(tempString[0]);
401 int endNum = Integer.parseInt(tempString[1]);
402 String returnString = "Invalid Range:" + rMap.getKey() + " must be between "
403 + startNum + " - " + endNum + ",";
404 if (isInteger(value.replace("\"", ""))){
405 int result = Integer.parseInt(value.replace("\"", ""));
408 if (result < startNum || result > endNum){
409 responseString.append(returnString);
413 responseString.append(returnString);
420 responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
424 if(policyData.getPriority() == null){
425 responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
430 if (policyData.getPolicyType().equals(DECISION_POLICY)){
431 if(policyData.getEcompName() != null){
432 String ecompNameValidate = emptyValidator(policyData.getEcompName());
433 if(!ecompNameValidate.contains("success")){
434 responseString.append("EcompName:" + ecompNameValidate + "<br>");
438 responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "<br>");
441 if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
442 if(policyData.getYamlparams()==null){
443 responseString.append("<b> Guard Params are Required </b>" + "<br>");
446 if(policyData.getYamlparams().getActor()==null){
447 responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
450 if(policyData.getYamlparams().getRecipe()==null){
451 responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
454 if(policyData.getYamlparams().getGuardActiveStart()==null){
455 responseString.append("Guard Params <b>Guard Active Start/b>is Required " + "<br>");
458 if(policyData.getYamlparams().getGuardActiveEnd()==null){
459 responseString.append("Guard Params <b>Guard Active End</b>is Required " + "<br>");
462 if("GUARD_YAML".equals(policyData.getRuleProvider())){
463 if(policyData.getYamlparams().getLimit()==null){
464 responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
466 }else if(!isInteger(policyData.getYamlparams().getLimit())){
467 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
470 if(policyData.getYamlparams().getTimeWindow()==null){
471 responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
474 }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
475 if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
476 responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
479 for(String blackList: policyData.getYamlparams().getBlackList()){
480 if(blackList==null || !("success".equals(emptyValidator(blackList)))){
481 responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
492 if(policyData.getPolicyType().equals(ACTION_POLICY)){
493 if(policyData.getActionPerformer() != null){
494 String actionPerformer = emptyValidator(policyData.getActionPerformer());
495 if(!actionPerformer.contains("success")){
496 responseString.append("ActionPerformer:" + actionPerformer + "<br>");
500 responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
503 if(policyData.getAttributes() != null){
504 for(Object attribute : policyData.getAttributes()){
505 if(attribute instanceof LinkedHashMap<?, ?>){
507 //This is for validation check if the value exists or not
508 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
509 String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
510 if("".equals(key) || "".equals(value)){
511 responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
516 LOGGER.error("This is a Policy Validation check" +e);
517 responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
524 responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
527 if(policyData.getActionAttributeValue() != null){
528 String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
529 if(!actionAttribute.contains("success")){
530 responseString.append("ActionAttribute:" + actionAttribute + "<br>");
534 responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
539 if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){
540 if(!policyData.getRuleAlgorithmschoices().isEmpty()){
541 for(Object attribute : policyData.getRuleAlgorithmschoices()){
542 if(attribute instanceof LinkedHashMap<?, ?>){
544 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
545 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
546 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
547 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
548 if("".equals(label) || "".equals(key) || "".equals(rule) || "".equals(value)){
549 responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
553 LOGGER.error("This is a Policy Validation check" +e);
554 responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
563 if(policyData.getPolicyType().equals(CONFIG_POLICY)){
566 List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
567 if (!spData.isEmpty()){
568 SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
569 safePolicyWarningData.getMessage();
570 value = "Message:" + safePolicyWarningData.getMessage();
572 responseString.append("success" + "@#"+ value);
576 responseString.append("success");
580 PrintWriter out = response.getWriter();
581 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
582 JSONObject j = new JSONObject(msg);
583 out.write(j.toString());
588 LOGGER.error("Exception Occured while Policy Validation" +e);
589 response.setCharacterEncoding("UTF-8");
590 request.setCharacterEncoding("UTF-8");
591 PrintWriter out = response.getWriter();
592 out.write(e.getMessage());
597 protected boolean isInteger(String number) {
599 Integer.parseInt(number);
600 }catch(NumberFormatException e){
606 protected String emptyValidator(String field){
608 if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
609 error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
612 if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
615 error = "The Value Contains Non ASCII Characters";
622 protected String descriptionValidator(String field) {
624 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
625 error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
633 public String validateEmailAddress(String emailAddressValue) {
634 String error = "success";
635 List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
636 for(int i =0 ; i < emailList.size() ; i++){
637 pattern = Pattern.compile(EMAIL_PATTERN);
638 matcher = pattern.matcher(emailList.get(i).trim());
639 if(!matcher.matches()){
640 error = "Please check the Following Email Address is not Valid .... " +emailList.get(i).toString();
649 protected String emailValidation(String email, String response){
651 String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
652 if(!validateEmail.contains("success")){
653 response += "<b>Email</b>:<i>" + validateEmail+ "</i><br>";
661 private MicroServiceModels getAttributeObject(String name, String version) {
662 MicroServiceModels workingModel = new MicroServiceModels();
663 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
664 if(microServiceModelsData != null){
665 workingModel = (MicroServiceModels) microServiceModelsData.get(0);
670 private void pullJsonKeyPairs(JsonNode rootNode) {
671 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
673 while (fieldsIterator.hasNext()) {
674 Map.Entry<String, JsonNode> field = fieldsIterator.next();
675 final String key = field.getKey();
676 final JsonNode value = field.getValue();
677 if (value.isContainerNode() && !value.isArray()) {
678 pullJsonKeyPairs(value); // RECURSIVE CALL
680 if (value.isArray()){
681 String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
682 mapAttribute.put(key, newValue);
684 mapAttribute.put(key, value.toString().trim());
690 // Validation for json.
691 protected static boolean isJSONValid(String data) {
692 JsonReader jsonReader = null;
694 new JSONObject(data);
695 InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
696 jsonReader = Json.createReader(stream);
697 LOGGER.info("Json Value is: " + jsonReader.read().toString() );
698 } catch (Exception e) {
699 LOGGER.error("Exception Occured While Validating"+e);
702 if(jsonReader != null){
709 // Validation for XML.
710 private boolean isXMLValid(String data) {
711 SAXParserFactory factory = SAXParserFactory.newInstance();
712 factory.setValidating(false);
713 factory.setNamespaceAware(true);
715 SAXParser parser = factory.newSAXParser();
716 XMLReader reader = parser.getXMLReader();
717 reader.setErrorHandler(new XMLErrorHandler());
718 reader.parse(new InputSource(new StringReader(data)));
719 } catch (Exception e) {
720 LOGGER.error("Exception Occured While Validating"+e);
726 // Validation for Properties file.
727 public boolean isPropValid(String prop) {
728 Scanner scanner = new Scanner(prop);
729 while (scanner.hasNextLine()) {
730 String line = scanner.nextLine();
731 line = line.replaceAll("\\s+", "");
732 if (line.startsWith("#")) {
735 if (line.contains("=")) {
736 String[] parts = line.split("=");
737 if (parts.length < 2) {