X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=blobdiff_plain;f=POLICY-SDK-APP%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fpolicy%2Fcontroller%2FPolicyValidationController.java;h=05264c8b61ad5dade7d10683646415cf9b874ece;hp=d1fba383ff3993afb9be50cf62328b8517c975c4;hb=1e61676b77dd09659027b8984f050df7e8538526;hpb=7ea81288603904f0cb6f57936da44d6a3dd521a6 diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java index d1fba383f..05264c8b6 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,759 +20,62 @@ package org.onap.policy.controller; +import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.io.StringReader; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Scanner; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.json.Json; -import javax.json.JsonReader; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import org.apache.commons.lang.StringUtils; -import org.dom4j.util.XMLErrorHandler; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.ClosedLoopFaultBody; -import org.onap.policy.rest.adapter.ClosedLoopPMBody; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.MicroServiceModels; -import org.onap.policy.rest.jpa.SafePolicyWarning; +import org.onap.policy.rest.util.PolicyValidation; +import org.onap.policy.rest.util.PolicyValidationRequestWrapper; import org.onap.policy.utils.PolicyUtils; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.web.support.JsonMessage; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.CharMatcher; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; @Controller @RequestMapping("/") public class PolicyValidationController extends RestrictedBaseController { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class); - - public static final String CONFIG_POLICY = "Config"; - public static final String ACTION_POLICY = "Action"; - public static final String DECISION_POLICY = "Decision"; - public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault"; - public static final String CLOSEDLOOP_PM = "ClosedLoop_PM"; - public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config"; - public static final String MICROSERVICES="Micro Service"; - private Pattern pattern; - private Matcher matcher; - private static Map mapAttribute = new HashMap<>(); - - private static final String EMAIL_PATTERN = - "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" - + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - - @Autowired - CommonClassDao commonClassDao; - - @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{ - try{ - boolean valid = true; - StringBuilder responseString = new StringBuilder(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); - if(policyData.getPolicyName() != null){ - String policyNameValidate = emptyValidator(policyData.getPolicyName()); - if(!policyNameValidate.contains("success")){ - responseString.append("PolicyName:" + policyNameValidate + "
"); - valid = false; - }; - }else{ - responseString.append( "PolicyName: PolicyName Should not be empty" + "
"); - valid = false; - } - if(policyData.getPolicyDescription() != null){ - String descriptionValidate = descriptionValidator(policyData.getPolicyDescription()); - if(!descriptionValidate.contains("success")){ - responseString.append("Description:" + descriptionValidate + "
"); - valid = false; - } - } - - if(policyData.getPolicyType().equals(CONFIG_POLICY)){ - if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) - || policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) { - if(policyData.getOnapName() != null){ - String onapNameValidate = emptyValidator(policyData.getOnapName()); - if(!onapNameValidate.contains("success")){ - responseString.append("OnapName:" + onapNameValidate + "
"); - valid = false; - } - }else{ - responseString.append("Onap Name: Onap Name Should not be empty" + "
"); - valid = false; - } - } - - if(policyData.getRiskType() != null){ - String riskTypeValidate = emptyValidator(policyData.getRiskType()); - if(!riskTypeValidate.contains("success")){ - responseString.append("RiskType:" + riskTypeValidate + "
"); - valid = false; - } - }else { - responseString.append("Risk Type: Risk Type Should not be Empty" + "
"); - valid = false; - } - - if(policyData.getRiskLevel() != null){ - String validateRiskLevel = emptyValidator(policyData.getRiskLevel()); - if(!validateRiskLevel.contains("success")){ - responseString.append("RiskLevel:" + validateRiskLevel + "
"); - valid = false; - } - }else { - responseString.append("Risk Level: Risk Level Should not be Empty" + "
"); - valid = false; - } - - if(policyData.getGuard() != null){ - String validateGuard = emptyValidator(policyData.getGuard()); - if(!validateGuard.contains("success")){ - responseString.append("Guard:" + validateGuard + "
"); - valid = false; - } - }else { - responseString.append("Guard: Guard Value Should not be Empty" + "
"); - valid = false; - } - - if(policyData.getConfigPolicyType().equals("Base")){ - if(policyData.getConfigName() != null){ - String configNameValidate = emptyValidator(policyData.getConfigName()); - if(!configNameValidate.contains("success")){ - responseString.append("ConfigName:" + configNameValidate + "
"); - valid = false; - } - }else{ - responseString.append("Config Name: Config Name Should not be Empty" + "
"); - valid = false; - } - if(policyData.getConfigType() != null){ - String configTypeValidate = emptyValidator(policyData.getConfigType()); - if(!configTypeValidate.contains("success")){ - responseString.append("ConfigType:" + configTypeValidate + "
"); - valid = false; - } - }else{ - responseString.append("Config Type: Config Type Should not be Empty" + "
"); - valid = false; - } - if(policyData.getConfigBodyData() != null){ - String configBodyData = policyData.getConfigBodyData(); - String policyType = policyData.getConfigType(); - if (policyType != null) { - if (policyType.equals("JSON")) { - if (!isJSONValid(configBodyData)) { - responseString.append("Config Body: JSON Content is not valid" + "
"); - valid = false; - } - } else if (policyType.equals("XML")) { - if (!isXMLValid(configBodyData)) { - responseString.append("Config Body: XML Content data is not valid" + "
"); - valid = false; - } - } else if (policyType.equals("PROPERTIES")) { - if (!isPropValid(configBodyData)||configBodyData.equals("")) { - responseString.append("Config Body: Property data is not valid" + "
"); - valid = false; - } - } else if (policyType.equals("OTHER")) { - if (configBodyData.equals("")) { - responseString.append("Config Body: Config Body Should not be Empty" + "
"); - valid = false; - } - } - } - }else{ - responseString.append("Config Body: Config Body Should not be Empty" + "
"); - valid = false; - } - } - - if(policyData.getConfigPolicyType().equals("Firewall Config")){ - if(policyData.getConfigName() != null){ - String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName()); - if(!configNameValidate.contains("success")){ - responseString.append("ConfigName:" + configNameValidate + "
"); - valid = false; - } - }else{ - responseString.append("Config Name: Config Name is required" + "
"); - valid = false; - } - if(policyData.getSecurityZone() == null){ - responseString.append("Security Zone: Security Zone is required" + "
"); - valid = false; - } - } - if(policyData.getConfigPolicyType().equals("BRMS_Param")){ - if(policyData.getRuleName() == null){ - responseString.append("BRMS Template:BRMS Template is required
"); - valid = false; - } - } - if(policyData.getConfigPolicyType().equals("BRMS_Raw")){ - if(policyData.getConfigBodyData() != null){ - String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData()); - // If there are any error other than Annotations then this is not Valid - if(message.contains("[ERR")){ - responseString.append("Raw Rule Validate:Raw Rule has error"+ message +"
"); - valid = false; - } - }else{ - responseString.append("Raw Rule:Raw Rule is required
"); - valid = false; - } - } - if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){ - try{ - if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){ - responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
"); - valid = false; - } - }catch(Exception e){ - LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e); - responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
"); - valid = false; - } - - if(root.get("policyData").get("jsonBodyData") != null){ - ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class); - if(pmBody.getEmailAddress() != null){ - String result = emailValidation(pmBody.getEmailAddress(), responseString.toString()); - if(result != "success"){ - responseString.append(result + "
"); - valid = false; - } - } - if(pmBody.getGeoLink() != null){ - String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink()); - if(!result.contains("success")){ - responseString.append("GeoLink:" + result + "
"); - valid = false; - }; - } - if(pmBody.getAttributes() != null){ - for(Entry entry : pmBody.getAttributes().entrySet()){ - String key = entry.getKey(); - String value = entry.getValue(); - if(!key.contains("Message")){ - String attributeValidate = PolicyUtils.emptyPolicyValidator(value); - if(!attributeValidate.contains("success")){ - responseString.append("Attributes:" + key + " : value has spaces
"); - valid = false; - }; - } - } - } - }else{ - responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
"); - valid = false; - } - } - if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){ - if(root.get("policyData").get("jsonBodyData") != null){ - ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); - if(faultBody.getEmailAddress() != null){ - String result = emailValidation(faultBody.getEmailAddress(), responseString.toString()); - if(result != "success"){ - responseString.append(result+ "
"); - valid = false; - } - } - if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){ - responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
"); - valid = false; - } - if(faultBody.getActions() == null){ - responseString.append("vPRO Actions:vPRO Actions is required
"); - valid = false; - } - if(faultBody.getClosedLoopPolicyStatus() == null){ - responseString.append("Policy Status:Policy Status is required
"); - valid = false; - } - if(faultBody.getConditions() == null){ - responseString.append("Conditions:Select Atleast one Condition
"); - valid = false; - } - if(faultBody.getGeoLink() != null){ - String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink()); - if(!result.contains("success")){ - responseString.append("GeoLink:" + result + "
"); - valid = false; - }; - } - - if(faultBody.getTimeInterval() == 0){ - responseString.append("Time Interval:Time Interval is required
"); - valid = false; - } - if(faultBody.getRetrys() == 0){ - responseString.append("Number of Retries:Number of Retries is required
"); - valid = false; - } - if(faultBody.getTimeOutvPRO() == 0){ - responseString.append("APP-C Timeout:APP-C Timeout is required
"); - valid = false; - } - if(faultBody.getTimeOutRuby() == 0){ - responseString.append("TimeOutRuby:TimeOutRuby is required
"); - valid = false; - } - if(faultBody.getVnfType() == null){ - responseString.append("Vnf Type:Vnf Type is required
"); - valid = false; - } - }else{ - responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
"); - responseString.append("vPRO Actions:vPRO Actions is required
"); - responseString.append("Aging Window:Aging Window is required
"); - responseString.append("Policy Status:Policy Status is required
"); - responseString.append("Conditions:Select Atleast one Condition
"); - responseString.append("PEP Name:PEP Name is required
"); - responseString.append("PEP Action:PEP Action is required
"); - responseString.append("Time Interval:Time Interval is required
"); - responseString.append("Number of Retries:Number of Retries is required
"); - responseString.append("APP-C Timeout:APP-C Timeout is required
"); - responseString.append("TimeOutRuby:TimeOutRuby is required
"); - responseString.append("Vnf Type:Vnf Type is required
"); - valid = false; - } - } - - if (policyData.getConfigPolicyType().contains("Micro Service")){ - if(policyData.getServiceType() != null){ - pullJsonKeyPairs(root.get("policyJSON")); - MicroServiceModels returnModel = new MicroServiceModels(); - String service = null; - String version = null; - if (policyData.getServiceType().contains("-v")){ - service = policyData.getServiceType().split("-v")[0]; - version = policyData.getServiceType().split("-v")[1]; - }else { - service = policyData.getServiceType(); - version = policyData.getVersion(); - } - returnModel = getAttributeObject(service, version); - String annoation = returnModel.getAnnotation(); - if (!Strings.isNullOrEmpty(annoation)){ - Map rangeMap = new HashMap<>(); - rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation); - for (Entry rMap : rangeMap.entrySet()){ - if (rMap.getValue().contains("range::")){ - String value = mapAttribute.get(rMap.getKey().trim()); - String[] tempString = rMap.getValue().split("::")[1].split("-"); - int startNum = Integer.parseInt(tempString[0]); - int endNum = Integer.parseInt(tempString[1]); - String returnString = "Invalid Range:" + rMap.getKey() + " must be between " - + startNum + " - " + endNum + ","; - if (PolicyUtils.isInteger(value.replace("\"", ""))){ - int result = Integer.parseInt(value.replace("\"", "")); - if (result < startNum || result > endNum){ - responseString.append(returnString); - valid = false; - } - }else { - responseString.append(returnString); - valid = false; - } - } - } - } - }else{ - responseString.append("Micro Service: Micro Service is required" + "
"); - valid = false; - } - - if(policyData.getPriority() == null){ - responseString.append("Priority: Priority is required" + "
"); - valid = false; - } - } - } - if (policyData.getPolicyType().equals(DECISION_POLICY)){ - if(policyData.getOnapName() != null){ - String onapNameValidate = emptyValidator(policyData.getOnapName()); - if(!onapNameValidate.contains("success")){ - responseString.append("OnapName:" + onapNameValidate + "
"); - valid = false; - } - }else{ - responseString.append("Onap Name: Onap Name Should not be empty" + "
"); - valid = false; - } - - if("Rainy_Day".equals(policyData.getRuleProvider())){ - if(policyData.getRainyday()==null){ - responseString.append(" Rainy Day Parameters are Required
"); - valid = false; - }else{ - if(policyData.getRainyday().getServiceType()==null){ - responseString.append("Rainy Day Service Type is Required
"); - valid = false; - } - if(policyData.getRainyday().getVnfType()==null){ - responseString.append("Rainy Day VNF Type is Required
"); - valid = false; - } - if(policyData.getRainyday().getBbid()==null){ - responseString.append("Rainy Day Building Block ID is Required
"); - valid = false; - } - if(policyData.getRainyday().getWorkstep()==null){ - responseString.append("Rainy Day Work Step is Required
"); - valid = false; - } - if(policyData.getRainyday().getServiceType()==null){ - responseString.append("Rainy Day Error Code is Required
"); - valid = false; - } - } - } - - if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){ - if(policyData.getYamlparams()==null){ - responseString.append(" Guard Params are Required " + "
"); - valid = false; - }else{ - if(policyData.getYamlparams().getActor()==null){ - responseString.append("Guard Params Actor is Required " + "
"); - valid = false; - } - if(policyData.getYamlparams().getRecipe()==null){ - responseString.append("Guard Params Recipe is Required " + "
"); - valid = false; - } - if(policyData.getYamlparams().getGuardActiveStart()==null){ - responseString.append("Guard Params Guard Active Start/b>is Required " + "
"); - valid = false; - } - if(policyData.getYamlparams().getGuardActiveEnd()==null){ - responseString.append("Guard Params Guard Active Endis Required " + "
"); - valid = false; - } - if("GUARD_YAML".equals(policyData.getRuleProvider())){ - if(policyData.getYamlparams().getLimit()==null){ - responseString.append(" Guard Params Limit is Required " + "
"); - valid = false; - }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){ - responseString.append(" Guard Params Limit Should be Integer " + "
"); - valid = false; - } - if(policyData.getYamlparams().getTimeWindow()==null){ - responseString.append("Guard Params Time Window is Required" + "
"); - valid = false; - }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){ - responseString.append(" Guard Params Time Window Should be Integer " + "
"); - valid = false; - } - if(policyData.getYamlparams().getTimeUnits()==null){ - responseString.append("Guard Params Time Units is Required" + "
"); - valid = false; - } - }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){ - if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){ - responseString.append(" Guard Params BlackList is Required " + "
"); - valid = false; - }else{ - for(String blackList: policyData.getYamlparams().getBlackList()){ - if(blackList==null || !("success".equals(emptyValidator(blackList)))){ - responseString.append(" Guard Params BlackList Should be valid String" + "
"); - valid = false; - break; - } - } - } - } - } - } - } - - if(policyData.getPolicyType().equals(ACTION_POLICY)){ - if(policyData.getActionPerformer() != null){ - String actionPerformer = emptyValidator(policyData.getActionPerformer()); - if(!actionPerformer.contains("success")){ - responseString.append("ActionPerformer:" + actionPerformer + "
"); - valid = false; - }; - }else{ - responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "
"); - valid = false; - } - if(policyData.getAttributes() != null){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - try{ - //This is for validation check if the value exists or not - String key = ((LinkedHashMap) attribute).get("key").toString(); - String value = ((LinkedHashMap) attribute).get("value").toString(); - if("".equals(key) || "".equals(value)){ - responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
"); - valid = false; - break; - } - }catch(Exception e){ - LOGGER.error("This is a Policy Validation check" +e); - responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
"); - valid = false; - break; - } - } - } - }else{ - responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
"); - valid = false; - } - if(policyData.getActionAttributeValue() != null){ - String actionAttribute = emptyValidator(policyData.getActionAttributeValue()); - if(!actionAttribute.contains("success")){ - responseString.append("ActionAttribute:" + actionAttribute + "
"); - valid = false; - }; - }else{ - responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "
"); - valid = false; - } - } - - if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){ - if(!policyData.getRuleAlgorithmschoices().isEmpty()){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap){ - try{ - String label = ((LinkedHashMap) attribute).get("id").toString(); - String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); - if("".equals(label) || "".equals(key) || "".equals(rule) || "".equals(value)){ - responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
"); - valid = false; - } - }catch(Exception e){ - LOGGER.error("This is a Policy Validation check" +e); - responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
"); - valid = false; - break; - } - } - } - } - } - - if(policyData.getPolicyType().equals(CONFIG_POLICY)){ - String value = ""; - if(valid){ - List spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType()); - if (!spData.isEmpty()){ - SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0); - safePolicyWarningData.getMessage(); - value = "Message:" + safePolicyWarningData.getMessage(); - } - responseString.append("success" + "@#"+ value); - } - }else{ - if(valid){ - responseString.append("success"); - } - } - - PrintWriter out = response.getWriter(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString())); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error("Exception Occured while Policy Validation" +e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - protected String emptyValidator(String field){ - String error; - if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { - error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; - return error; - } else { - if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){ - error = "success"; - }else{ - error = "The Value Contains Non ASCII Characters"; - return error; - } - } - return error; - } - - protected String descriptionValidator(String field) { - String error; - if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) { - error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:"; - return error; - } else { - error = "success"; - } - return error; - } - - public String validateEmailAddress(String emailAddressValue) { - String error = "success"; - List emailList = Arrays.asList(emailAddressValue.toString().split(",")); - for(int i =0 ; i < emailList.size() ; i++){ - pattern = Pattern.compile(EMAIL_PATTERN); - matcher = pattern.matcher(emailList.get(i).trim()); - if(!matcher.matches()){ - error = "Please check the Following Email Address is not Valid .... " +emailList.get(i).toString(); - return error; - }else{ - error = "success"; - } - } - return error; - } - - protected String emailValidation(String email, String response){ - if(email != null){ - String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", "")); - if(!validateEmail.contains("success")){ - response += "Email:" + validateEmail+ "
"; - }else{ - return "success"; - } - } - return response; - } - - private MicroServiceModels getAttributeObject(String name, String version) { - MicroServiceModels workingModel = new MicroServiceModels(); - List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version); - if(microServiceModelsData != null){ - workingModel = (MicroServiceModels) microServiceModelsData.get(0); - } - return workingModel; - } - - private void pullJsonKeyPairs(JsonNode rootNode) { - Iterator> fieldsIterator = rootNode.fields(); - - while (fieldsIterator.hasNext()) { - Map.Entry field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullJsonKeyPairs(value); // RECURSIVE CALL - } else { - if (value.isArray()){ - String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - }else { - mapAttribute.put(key, value.toString().trim()); - } - } - } - } - - // Validation for json. - protected static boolean isJSONValid(String data) { - JsonReader jsonReader = null; - try { - new JSONObject(data); - InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); - jsonReader = Json.createReader(stream); - LOGGER.info("Json Value is: " + jsonReader.read().toString() ); - } catch (Exception e) { - LOGGER.error("Exception Occured While Validating"+e); - return false; - }finally{ - if(jsonReader != null){ - jsonReader.close(); - } - } - return true; - } - - // Validation for XML. - private boolean isXMLValid(String data) { - SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setValidating(false); - factory.setNamespaceAware(true); - try { - SAXParser parser = factory.newSAXParser(); - XMLReader reader = parser.getXMLReader(); - reader.setErrorHandler(new XMLErrorHandler()); - reader.parse(new InputSource(new StringReader(data))); - } catch (Exception e) { - LOGGER.error("Exception Occured While Validating"+e); - return false; - } - return true; - } - - // Validation for Properties file. - public boolean isPropValid(String prop) { - Scanner scanner = new Scanner(prop); - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - line = line.replaceAll("\\s+", ""); - if (line.startsWith("#")) { - continue; - } else { - if (line.contains("=")) { - String[] parts = line.split("="); - if (parts.length < 2) { - scanner.close(); - return false; - } - } else { - scanner.close(); - return false; - } - } - } - scanner.close(); - return true; - } - -} \ No newline at end of file + private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class); + + /** + * validatePolicy. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ + @RequestMapping( + value = {"/policyController/validate_policy.htm"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException { + try { + + PolicyValidation validation = new PolicyValidation(); + PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper(); + StringBuilder responseString; + ObjectMapper mapper = new ObjectMapper(); + + PolicyRestAdapter policyData = wrapper.populateRequestParameters(request); + responseString = validation.validatePolicy(policyData); + + response.getWriter().write(new JSONObject( + new JsonMessage(mapper.writeValueAsString(responseString.toString()))).toString()); + } catch (Exception e) { + LOGGER.error("Exception Occured During Policy Validation" + e); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.getWriter().write(PolicyUtils.CATCH_EXCEPTION); + } + return null; + } +}