From 82e81ac60d97b93847a26accc071e7043d831ab0 Mon Sep 17 00:00:00 2001 From: Michael Mokry Date: Mon, 11 Dec 2017 10:07:43 -0600 Subject: Adding SONAR fixes for - pushPolicy defect fixes for POLICY-486 - Common Policy Validation feature for POLIYC-449 Change-Id: I8d54aa5a9b819c6eb4427dfa47c4ce963a21c2e0 Issue-ID: POLICY-449,POLICY-486 Signed-off-by: Michael Mokry --- .../policy/rest/adapter/ClosedLoopFaultBody.java | 16 - .../policy/rest/adapter/PolicyRestAdapter.java | 553 ++++++++++----------- .../rest/daoimpl/PolicyValidationDaoImpl.java | 56 ++- .../onap/policy/rest/util/PolicyValidation.java | 171 ++++--- .../rest/util/PolicyValidationRequestWrapper.java | 95 ++-- .../rest/daoimpl/PolicyValidationDaoImplTest.java | 441 ++++++++++++++++ 6 files changed, 875 insertions(+), 457 deletions(-) create mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java (limited to 'ONAP-REST/src') diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java index 3d85f9f93..73909d923 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java @@ -221,22 +221,6 @@ public class ClosedLoopFaultBody { this.verificationSignatures = verificationSignatures; } - /*public ArrayList getD2Services() { - return d2Services; - } - - public void setD2Services(ArrayList d2Services) { - this.d2Services = d2Services; - } - - public ArrayList getSiteNames() { - return siteNames; - } - - public void setSiteNames(ArrayList siteNames) { - this.siteNames = siteNames; - }*/ - public boolean isvDNS() { return vDNS; } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java index 6de0c9b78..de424683d 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java @@ -342,12 +342,6 @@ public class PolicyRestAdapter { public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } - public String getUserGitPath() { - return gitPath; - } - public void setUserGitPath(String gitPath) { - this.gitPath = gitPath; - } public boolean isValidData() { return isValidData; } @@ -629,281 +623,274 @@ public class PolicyRestAdapter { public void setNewFileName(String newFileName) { this.newFileName = newFileName; } - - public String getDomain() { - return domain; - } - public void setDomain(String domain) { - this.domain = domain; - } - public OnapName getOnapNameField() { - return onapNameField; - } - public void setOnapNameField(OnapName onapNameField) { - this.onapNameField = onapNameField; - } - public Object getJsonBodyData() { - return jsonBodyData; - } - public void setJsonBodyData(Object jsonBodyData) { - this.jsonBodyData = jsonBodyData; - } - public String getDirPath() { - return dirPath; - } - public void setDirPath(String dirPath) { - this.dirPath = dirPath; - } - public String getConfigBodyPath() { - return configBodyPath; - } - public void setConfigBodyPath(String configBodyPath) { - this.configBodyPath = configBodyPath; - } - public ArrayList getAttributes() { - return attributes; - } - public void setAttributes(ArrayList attributes) { - this.attributes = attributes; - } - public ArrayList getSettings() { - return settings; - } - public void setSettings(ArrayList settings) { - this.settings = settings; - } - public ArrayList getRuleAlgorithmschoices() { - return ruleAlgorithmschoices; - } - public void setRuleAlgorithmschoices(ArrayList ruleAlgorithmschoices) { - this.ruleAlgorithmschoices = ruleAlgorithmschoices; - } - public LinkedHashMap getServiceTypePolicyName() { - return serviceTypePolicyName; - } - public void setServiceTypePolicyName(LinkedHashMap serviceTypePolicyName) { - this.serviceTypePolicyName = serviceTypePolicyName; - } - public LinkedHashMap getVerticaMetrics() { - return verticaMetrics; - } - public void setVerticaMetrics(LinkedHashMap verticaMetrics) { - this.verticaMetrics = verticaMetrics; - } - public LinkedHashMap getDescription() { - return description; - } - public void setDescription(LinkedHashMap description) { - this.description = description; - } - public LinkedHashMap getAttributeFields() { - return attributeFields; - } - public void setAttributeFields(LinkedHashMap attributeFields) { - this.attributeFields = attributeFields; - } - public String getClearTimeOut() { - return clearTimeOut; - } - public void setClearTimeOut(String clearTimeOut) { - this.clearTimeOut = clearTimeOut; - } - public String getTrapMaxAge() { - return trapMaxAge; - } - public void setTrapMaxAge(String trapMaxAge) { - this.trapMaxAge = trapMaxAge; - } - public String getVerificationclearTimeOut() { - return verificationclearTimeOut; - } - public void setVerificationclearTimeOut(String verificationclearTimeOut) { - this.verificationclearTimeOut = verificationclearTimeOut; - } - public Map getDynamicLayoutMap() { - return dynamicLayoutMap; - } - public void setDynamicLayoutMap(Map dynamicLayoutMap) { - this.dynamicLayoutMap = dynamicLayoutMap; - } - public String getFwPolicyType() { - return fwPolicyType; - } - public void setFwPolicyType(String fwPolicyType) { - this.fwPolicyType = fwPolicyType; - } - public ArrayList getFwattributes() { - return fwattributes; - } - public void setFwattributes(ArrayList fwattributes) { - this.fwattributes = fwattributes; - } - public String getParentForChild() { - return parentForChild; - } - public void setParentForChild(String parentForChild) { - this.parentForChild = parentForChild; - } - public String getRuleName() { - return ruleName; - } - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - public LinkedHashMap getRuleData() { - return ruleData; - } - public void setRuleData(LinkedHashMap ruleData) { - this.ruleData = ruleData; - } - public LinkedHashMap getRuleListData() { - return ruleListData; - } - public void setRuleListData(LinkedHashMap ruleListData) { - this.ruleListData = ruleListData; - } - public String getSecurityZone() { - return securityZone; - } - public void setSecurityZone(String securityZone) { - this.securityZone = securityZone; - } - public String getActionAttributeValue() { - return actionAttributeValue; - } - public void setActionAttributeValue(String actionAttributeValue) { - this.actionAttributeValue = actionAttributeValue; - } - public String getRuleProvider() { - return ruleProvider; - } - public void setRuleProvider(String ruleProvider) { - this.ruleProvider = ruleProvider; - } - public String getMsLocation() { - return msLocation; - } - public void setMsLocation(String msLocation) { - this.msLocation = msLocation; - } - public Map getDrlRuleAndUIParams() { - return drlRuleAndUIParams; - } - public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { - this.drlRuleAndUIParams = drlRuleAndUIParams; - } - public String getActionBody() { - return actionBody; - } - public void setActionBody(String actionBody) { - this.actionBody = actionBody; - } - public String getActionDictHeader() { - return actionDictHeader; - } - public void setActionDictHeader(String actionDictHeader) { - this.actionDictHeader = actionDictHeader; - } - public String getActionDictType() { - return actionDictType; - } - public void setActionDictType(String actionDictType) { - this.actionDictType = actionDictType; - } - public String getActionDictUrl() { - return actionDictUrl; - } - public void setActionDictUrl(String actionDictUrl) { - this.actionDictUrl = actionDictUrl; - } - public String getActionDictMethod() { - return actionDictMethod; - } - public void setActionDictMethod(String actionDictMethod) { - this.actionDictMethod = actionDictMethod; - } - public String getClWarning() { - return clWarning; - } - public void setClWarning(String clWarning) { - this.clWarning = clWarning; - } - public String getNewCLName() { - return newCLName; - } - public void setNewCLName(String newCLName) { - this.newCLName = newCLName; - } - public String getExistingCLName() { - return existingCLName; - } - public void setExistingCLName(String existingCLName) { - this.existingCLName = existingCLName; - } - public YAMLParams getYamlparams() { - return yamlparams; - } - public void setYamlparams(YAMLParams yamlparams) { - this.yamlparams = yamlparams; - } - /** - * @return the rainyday - */ - public RainyDayParams getRainyday() { - return rainyday; - } - /** - * @param rainyday the rainyday to set - */ - public void setRainyday(RainyDayParams rainyday) { - this.rainyday = rainyday; - } - /** - * @return the errorCodeList - */ - public List getErrorCodeList() { - return errorCodeList; - } - /** - * @param errorCodeList the errorCodeList to set - */ - public void setErrorCodeList(List errorCodeList) { - this.errorCodeList = errorCodeList; - } - /** - * @return the treatmentList - */ - public List getTreatmentList() { - return treatmentList; - } - /** - * @param treatmentList the treatmentList to set - */ - public void setTreatmentList(List treatmentList) { - this.treatmentList = treatmentList; - } - /** - * @return the rainydayMap - */ - public Map getRainydayMap() { - return rainydayMap; - } - /** - * @param rainydayMap the rainydayMap to set - */ - public void setRainydayMap(Map rainydayMap) { - this.rainydayMap = rainydayMap; - } - /** - * @return the policyJSON - */ - public Object getPolicyJSON() { - return policyJSON; - } - /** - * @param policyJSON the policyJSON to set - */ - public void setPolicyJSON(Object policyJSON) { - this.policyJSON = policyJSON; - } + public OnapName getOnapNameField() { + return onapNameField; + } + public void setOnapNameField(OnapName onapNameField) { + this.onapNameField = onapNameField; + } + public Object getJsonBodyData() { + return jsonBodyData; + } + public void setJsonBodyData(Object jsonBodyData) { + this.jsonBodyData = jsonBodyData; + } + public String getDirPath() { + return dirPath; + } + public void setDirPath(String dirPath) { + this.dirPath = dirPath; + } + public String getConfigBodyPath() { + return configBodyPath; + } + public void setConfigBodyPath(String configBodyPath) { + this.configBodyPath = configBodyPath; + } + public ArrayList getAttributes() { + return attributes; + } + public void setAttributes(ArrayList attributes) { + this.attributes = attributes; + } + public ArrayList getSettings() { + return settings; + } + public void setSettings(ArrayList settings) { + this.settings = settings; + } + public ArrayList getRuleAlgorithmschoices() { + return ruleAlgorithmschoices; + } + public void setRuleAlgorithmschoices(ArrayList ruleAlgorithmschoices) { + this.ruleAlgorithmschoices = ruleAlgorithmschoices; + } + public LinkedHashMap getServiceTypePolicyName() { + return serviceTypePolicyName; + } + public void setServiceTypePolicyName(LinkedHashMap serviceTypePolicyName) { + this.serviceTypePolicyName = serviceTypePolicyName; + } + public LinkedHashMap getVerticaMetrics() { + return verticaMetrics; + } + public void setVerticaMetrics(LinkedHashMap verticaMetrics) { + this.verticaMetrics = verticaMetrics; + } + public LinkedHashMap getDescription() { + return description; + } + public void setDescription(LinkedHashMap description) { + this.description = description; + } + public LinkedHashMap getAttributeFields() { + return attributeFields; + } + public void setAttributeFields(LinkedHashMap attributeFields) { + this.attributeFields = attributeFields; + } + public String getClearTimeOut() { + return clearTimeOut; + } + public void setClearTimeOut(String clearTimeOut) { + this.clearTimeOut = clearTimeOut; + } + public String getTrapMaxAge() { + return trapMaxAge; + } + public void setTrapMaxAge(String trapMaxAge) { + this.trapMaxAge = trapMaxAge; + } + public String getVerificationclearTimeOut() { + return verificationclearTimeOut; + } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { + this.verificationclearTimeOut = verificationclearTimeOut; + } + public Map getDynamicLayoutMap() { + return dynamicLayoutMap; + } + public void setDynamicLayoutMap(Map dynamicLayoutMap) { + this.dynamicLayoutMap = dynamicLayoutMap; + } + public String getFwPolicyType() { + return fwPolicyType; + } + public void setFwPolicyType(String fwPolicyType) { + this.fwPolicyType = fwPolicyType; + } + public ArrayList getFwattributes() { + return fwattributes; + } + public void setFwattributes(ArrayList fwattributes) { + this.fwattributes = fwattributes; + } + public String getParentForChild() { + return parentForChild; + } + public void setParentForChild(String parentForChild) { + this.parentForChild = parentForChild; + } + public String getRuleName() { + return ruleName; + } + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + public LinkedHashMap getRuleData() { + return ruleData; + } + public void setRuleData(LinkedHashMap ruleData) { + this.ruleData = ruleData; + } + public LinkedHashMap getRuleListData() { + return ruleListData; + } + public void setRuleListData(LinkedHashMap ruleListData) { + this.ruleListData = ruleListData; + } + public String getSecurityZone() { + return securityZone; + } + public void setSecurityZone(String securityZone) { + this.securityZone = securityZone; + } + public String getActionAttributeValue() { + return actionAttributeValue; + } + public void setActionAttributeValue(String actionAttributeValue) { + this.actionAttributeValue = actionAttributeValue; + } + public String getRuleProvider() { + return ruleProvider; + } + public void setRuleProvider(String ruleProvider) { + this.ruleProvider = ruleProvider; + } + public String getMsLocation() { + return msLocation; + } + public void setMsLocation(String msLocation) { + this.msLocation = msLocation; + } + public Map getDrlRuleAndUIParams() { + return drlRuleAndUIParams; + } + public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { + this.drlRuleAndUIParams = drlRuleAndUIParams; + } + public String getActionBody() { + return actionBody; + } + public void setActionBody(String actionBody) { + this.actionBody = actionBody; + } + public String getActionDictHeader() { + return actionDictHeader; + } + public void setActionDictHeader(String actionDictHeader) { + this.actionDictHeader = actionDictHeader; + } + public String getActionDictType() { + return actionDictType; + } + public void setActionDictType(String actionDictType) { + this.actionDictType = actionDictType; + } + public String getActionDictUrl() { + return actionDictUrl; + } + public void setActionDictUrl(String actionDictUrl) { + this.actionDictUrl = actionDictUrl; + } + public String getActionDictMethod() { + return actionDictMethod; + } + public void setActionDictMethod(String actionDictMethod) { + this.actionDictMethod = actionDictMethod; + } + public String getClWarning() { + return clWarning; + } + public void setClWarning(String clWarning) { + this.clWarning = clWarning; + } + public String getNewCLName() { + return newCLName; + } + public void setNewCLName(String newCLName) { + this.newCLName = newCLName; + } + public String getExistingCLName() { + return existingCLName; + } + public void setExistingCLName(String existingCLName) { + this.existingCLName = existingCLName; + } + public YAMLParams getYamlparams() { + return yamlparams; + } + public void setYamlparams(YAMLParams yamlparams) { + this.yamlparams = yamlparams; + } + /** + * @return the rainyday + */ + public RainyDayParams getRainyday() { + return rainyday; + } + /** + * @param rainyday the rainyday to set + */ + public void setRainyday(RainyDayParams rainyday) { + this.rainyday = rainyday; + } + /** + * @return the errorCodeList + */ + public List getErrorCodeList() { + return errorCodeList; + } + /** + * @param errorCodeList the errorCodeList to set + */ + public void setErrorCodeList(List errorCodeList) { + this.errorCodeList = errorCodeList; + } + /** + * @return the treatmentList + */ + public List getTreatmentList() { + return treatmentList; + } + /** + * @param treatmentList the treatmentList to set + */ + public void setTreatmentList(List treatmentList) { + this.treatmentList = treatmentList; + } + /** + * @return the rainydayMap + */ + public Map getRainydayMap() { + return rainydayMap; + } + /** + * @param rainydayMap the rainydayMap to set + */ + public void setRainydayMap(Map rainydayMap) { + this.rainydayMap = rainydayMap; + } + /** + * @return the policyJSON + */ + public Object getPolicyJSON() { + return policyJSON; + } + /** + * @param policyJSON the policyJSON to set + */ + public void setPolicyJSON(Object policyJSON) { + this.policyJSON = policyJSON; + } } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java b/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java index f6682eb40..8aa04356f 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java @@ -20,6 +20,7 @@ package org.onap.policy.rest.daoimpl; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; @@ -42,12 +43,13 @@ import org.onap.policy.rest.jpa.PolicyRoles; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; @Component public class PolicyValidationDaoImpl implements CommonClassDao{ private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationDaoImpl.class); + private static final String DB_CONNECTION_CLOSING_ERROR = "Error While Closing Connection/Statement"; + private static final String DBTABLE_QUERY_ERROR = "Error While Querying Table"; private static SessionFactory sessionfactory; public static SessionFactory getSessionfactory() { @@ -76,12 +78,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ Criteria cr = session.createCriteria(className); data = cr.list(); }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e); }finally{ try{ session.close(); }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR+e); } } return data; @@ -106,12 +108,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ } data = cr.list(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e); }finally{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } return data; @@ -125,12 +127,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ session.persist(entity); tx.commit(); }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); }finally{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } @@ -149,7 +151,7 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } @@ -169,7 +171,7 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } @@ -207,7 +209,7 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } return data; @@ -240,7 +242,7 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } return rolesData; @@ -249,12 +251,14 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ @Override public List checkExistingGroupListforUpdate(String arg0, String arg1) { - return null; + return Collections.emptyList(); } @Override - public void deleteAll() {} + public void deleteAll() { + // Do nothing because this method is not used and is a placeholder to avoid 'Unimplemented Method' error + } @SuppressWarnings("unchecked") @@ -276,13 +280,13 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ data = hbquery.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e); throw e; }finally{ try{ session.close(); }catch(HibernateException e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } return data; @@ -309,12 +313,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ data = cr.list().get(0); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e); }finally{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } return data; @@ -322,11 +326,15 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ @Override - public void updateClAlarms(String arg0, String arg1) {} + public void updateClAlarms(String arg0, String arg1) { + // Do nothing because this method is not used and is a placeholder to avoid 'Unimplemented Method' error + } @Override - public void updateClYaml(String arg0, String arg1) {} + public void updateClYaml(String arg0, String arg1) { + // Do nothing because this method is not used and is a placeholder to avoid 'Unimplemented Method' error + } @Override @@ -343,7 +351,7 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } @@ -360,12 +368,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ cr.setProjection(Projections.property(columnName)); data = cr.list(); }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e); }finally{ try{ session.close(); }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e); } } return data; @@ -396,12 +404,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{ entityData = cr.add(disjunction).list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" +className +e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + className + e); }finally{ try{ session.close(); }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1); } } return entityData; diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java index 223381afe..e98a41f9e 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java @@ -60,6 +60,9 @@ public class PolicyValidation { public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config"; public static final String MICROSERVICES="Micro Service"; public static final String FIREWALL="Firewall Config"; + public static final String HTML_ITALICS_LNBREAK = "
"; + public static final String SUCCESS = "success"; + public static final String EMPTY_COMPONENT_ATTR = "Component Attributes: One or more Fields in Component Attributes is Empty."; private static Map mapAttribute = new HashMap<>(); @@ -84,7 +87,7 @@ public class PolicyValidation { if(policyData.getPolicyName() != null){ String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName()); - if(!policyNameValidate.contains("success")){ + if(!policyNameValidate.contains(SUCCESS)){ responseString.append("PolicyName:" + policyNameValidate + "
"); valid = false; }; @@ -94,7 +97,7 @@ public class PolicyValidation { } if(policyData.getPolicyDescription() != null){ String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription()); - if(!descriptionValidate.contains("success")){ + if(!descriptionValidate.contains(SUCCESS)){ responseString.append("Description:" + descriptionValidate + "
"); valid = false; } @@ -107,7 +110,7 @@ public class PolicyValidation { if(!Strings.isNullOrEmpty(policyData.getOnapName())) { String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName()); - if(!onapNameValidate.contains("success")){ + if(!onapNameValidate.contains(SUCCESS)){ responseString.append("OnapName:" + onapNameValidate + "
"); valid = false; } @@ -119,7 +122,7 @@ public class PolicyValidation { if(!Strings.isNullOrEmpty(policyData.getRiskType())) { String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType()); - if(!riskTypeValidate.contains("success")){ + if(!riskTypeValidate.contains(SUCCESS)){ responseString.append("RiskType:" + riskTypeValidate + "
"); valid = false; } @@ -130,7 +133,7 @@ public class PolicyValidation { if(!Strings.isNullOrEmpty(policyData.getRiskLevel())) { String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel()); - if(!validateRiskLevel.contains("success")){ + if(!validateRiskLevel.contains(SUCCESS)){ responseString.append("RiskLevel:" + validateRiskLevel + "
"); valid = false; } @@ -141,7 +144,7 @@ public class PolicyValidation { if(!Strings.isNullOrEmpty(policyData.getGuard())) { String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard()); - if(!validateGuard.contains("success")){ + if(!validateGuard.contains(SUCCESS)){ responseString.append("Guard:" + validateGuard + "
"); valid = false; } @@ -153,7 +156,7 @@ public class PolicyValidation { if("Base".equalsIgnoreCase(policyData.getConfigPolicyType())){ if(!Strings.isNullOrEmpty(policyData.getConfigName())) { String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName()); - if(!configNameValidate.contains("success")){ + if(!configNameValidate.contains(SUCCESS)){ responseString.append("ConfigName:" + configNameValidate + "
"); valid = false; } @@ -163,7 +166,7 @@ public class PolicyValidation { } if(!Strings.isNullOrEmpty(policyData.getConfigType())) { String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType()); - if(!configTypeValidate.contains("success")){ + if(!configTypeValidate.contains(SUCCESS)){ responseString.append("ConfigType:" + configTypeValidate + "
"); valid = false; } @@ -190,11 +193,9 @@ public class PolicyValidation { responseString.append("Config Body: Property data is not valid" + "
"); valid = false; } - } else if (configType.equals("OTHER")) { - if (configBodyData.equals("")) { - responseString.append("Config Body: Config Body Should not be Empty" + "
"); - valid = false; - } + } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) { + responseString.append("Config Body: Config Body Should not be Empty" + "
"); + valid = false; } } }else{ @@ -203,27 +204,25 @@ public class PolicyValidation { } } - if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){ + if(FIREWALL.equalsIgnoreCase(policyData.getConfigPolicyType())){ if(policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()){ String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName()); - if(!configNameValidate.contains("success")){ - responseString.append("ConfigName:" + configNameValidate + "
"); + if(!configNameValidate.contains(SUCCESS)){ + responseString.append("ConfigName:" + configNameValidate + HTML_ITALICS_LNBREAK); valid = false; } }else{ - responseString.append("Config Name: Config Name is required" + "
"); + responseString.append("Config Name: Config Name is required" + HTML_ITALICS_LNBREAK); valid = false; } if(policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()){ - responseString.append("Security Zone: Security Zone is required" + "
"); + responseString.append("Security Zone: Security Zone is required" + HTML_ITALICS_LNBREAK); valid = false; } } - if("BRMS_Param".equalsIgnoreCase(policyData.getConfigPolicyType())){ - if(policyData.getRuleName() == null || policyData.getRuleName().isEmpty()){ - responseString.append("BRMS Template:BRMS Template is required
"); - valid = false; - } + if("BRMS_Param".equalsIgnoreCase(policyData.getConfigPolicyType()) && Strings.isNullOrEmpty(policyData.getRuleName())){ + responseString.append("BRMS Template:BRMS Template is required" + HTML_ITALICS_LNBREAK); + valid = false; } if("BRMS_Raw".equalsIgnoreCase(policyData.getConfigPolicyType())){ if(policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()){ @@ -231,44 +230,45 @@ public class PolicyValidation { // 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 +"
"); + responseString.append("Raw Rule Validate:Raw Rule has error"+ message + HTML_ITALICS_LNBREAK); valid = false; } }else{ - responseString.append("Raw Rule:Raw Rule is required
"); + responseString.append("Raw Rule:Raw Rule is required" + HTML_ITALICS_LNBREAK); valid = false; } } - if("ClosedLoop_PM".equalsIgnoreCase(policyData.getConfigPolicyType())){ + if(CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())){ try{ if(Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())){ - responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
"); + responseString.append("ServiceType PolicyName:ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK); valid = false; } }catch(Exception e){ LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e); - responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
"); + responseString.append("ServiceType PolicyName:ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK); valid = false; } if(policyData.getJsonBody() != null){ - ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class); + + ClosedLoopPMBody pmBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class); if(pmBody.getEmailAddress() != null){ String result = emailValidation(pmBody.getEmailAddress(), responseString.toString()); - if(result != "success"){ + if(result != SUCCESS){ responseString.append(result + "
"); valid = false; } } if((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS() || pmBody.isvUSP()) != true){ - responseString.append("D2/Virtualized Services: Select at least one D2/Virtualized Services
"); + responseString.append("D2/Virtualized Services: Select at least one D2/Virtualized Services" + HTML_ITALICS_LNBREAK); valid = false; } if(pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()){ String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink()); - if(!result.contains("success")){ - responseString.append("GeoLink:" + result + "
"); + if(!result.contains(SUCCESS)){ + responseString.append("GeoLink:" + result + HTML_ITALICS_LNBREAK); valid = false; }; } @@ -278,19 +278,19 @@ public class PolicyValidation { String value = entry.getValue(); if(!key.contains("Message")){ String attributeValidate = PolicyUtils.policySpecialCharValidator(value); - if(!attributeValidate.contains("success")){ - responseString.append("Attributes:" + key + " : value has spaces or invalid characters
"); + if(!attributeValidate.contains(SUCCESS)){ + responseString.append("Attributes:" + key + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK); valid = false; }; } } } }else{ - responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
"); + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK); valid = false; } } - if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){ + if(CLOSEDLOOP_POLICY.equalsIgnoreCase(policyData.getConfigPolicyType())){ if(policyData.getJsonBody() != null){ // For API we need to get the conditions key from the Json request and check it before deserializing to POJO due to the enum @@ -299,11 +299,11 @@ public class PolicyValidation { if(!json.isNull("conditions")){ String apiCondition = (String) json.get("conditions"); if(Strings.isNullOrEmpty(apiCondition)){ - responseString.append("Conditions: Select At least one Condition
"); + responseString.append("Conditions: Select At least one Condition" + HTML_ITALICS_LNBREAK); return responseString; } } else { - responseString.append("Conditions: There were no conditions provided in configBody json
"); + responseString.append("Conditions: There were no conditions provided in configBody json" + HTML_ITALICS_LNBREAK); return responseString; } } @@ -311,79 +311,79 @@ public class PolicyValidation { ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class); if(faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()){ String result = emailValidation(faultBody.getEmailAddress(), responseString.toString()); - if(result != "success"){ + if(result != SUCCESS){ responseString.append(result+ "
"); valid = false; } } if((faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){ - responseString.append("D2/Virtualized Services: Select at least one D2/Virtualized Services
"); + responseString.append("D2/Virtualized Services: Select at least one D2/Virtualized Services" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getActions() == null || faultBody.getActions().isEmpty()){ - responseString.append("vPRO Actions: vPRO Actions is required
"); + responseString.append("vPRO Actions: vPRO Actions is required" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getClosedLoopPolicyStatus() == null || faultBody.getClosedLoopPolicyStatus().isEmpty()){ - responseString.append("Policy Status: Policy Status is required
"); + responseString.append("Policy Status: Policy Status is required" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getConditions() == null){ - responseString.append("Conditions: Select At least one Condition
"); + responseString.append("Conditions: Select At least one Condition" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()){ String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink()); - if(!result.contains("success")){ - responseString.append("GeoLink:" + result + "
"); + if(!result.contains(SUCCESS)){ + responseString.append("GeoLink:" + result + HTML_ITALICS_LNBREAK); valid = false; } } if(faultBody.getAgingWindow() == 0){ - responseString.append("Aging Window: Aging Window is required
"); + responseString.append("Aging Window: Aging Window is required" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getTimeInterval() == 0){ - responseString.append("Time Interval: Time Interval is required
"); + responseString.append("Time Interval: Time Interval is required" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getRetrys() == 0){ - responseString.append("Number of Retries: Number of Retries is required
"); + responseString.append("Number of Retries: Number of Retries is required" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getTimeOutvPRO() == 0){ - responseString.append("APP-C Timeout: APP-C Timeout is required
"); + responseString.append("APP-C Timeout: APP-C Timeout is required" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getTimeOutRuby() == 0){ - responseString.append("TimeOutRuby: TimeOutRuby is required
"); + responseString.append("TimeOutRuby: TimeOutRuby is required" + HTML_ITALICS_LNBREAK); valid = false; } if(faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()){ - responseString.append("Vnf Type: Vnf Type is required
"); + responseString.append("Vnf Type: Vnf Type is required" + HTML_ITALICS_LNBREAK); 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
"); + responseString.append("D2/Virtualized Services: Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK); + responseString.append("vPRO Actions: vPRO Actions is required" + HTML_ITALICS_LNBREAK); + responseString.append("Aging Window: Aging Window is required" + HTML_ITALICS_LNBREAK); + responseString.append("Policy Status: Policy Status is required" + HTML_ITALICS_LNBREAK); + responseString.append("Conditions: Select Atleast one Condition" + HTML_ITALICS_LNBREAK); + responseString.append("PEP Name: PEP Name is required" + HTML_ITALICS_LNBREAK); + responseString.append("PEP Action: PEP Action is required" + HTML_ITALICS_LNBREAK); + responseString.append("Time Interval: Time Interval is required" + HTML_ITALICS_LNBREAK); + responseString.append("Number of Retries: Number of Retries is required" + HTML_ITALICS_LNBREAK); + responseString.append("APP-C Timeout: APP-C Timeout is required" + HTML_ITALICS_LNBREAK); + responseString.append("TimeOutRuby: TimeOutRuby is required" + HTML_ITALICS_LNBREAK); + responseString.append("Vnf Type: Vnf Type is required" + HTML_ITALICS_LNBREAK); valid = false; } } - if ("Micro Service".equals(policyData.getConfigPolicyType())){ + if (MICROSERVICES.equals(policyData.getConfigPolicyType())){ if(!Strings.isNullOrEmpty(policyData.getServiceType())){ pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON()); - MicroServiceModels returnModel = new MicroServiceModels(); + String service = null; String version = null; if (policyData.getServiceType().contains("-v")){ @@ -395,13 +395,12 @@ public class PolicyValidation { } if(!Strings.isNullOrEmpty(version)) { - returnModel = getAttributeObject(service, version); + MicroServiceModels returnModel = getAttributeObject(service, version); if(returnModel != null) { String annotation = returnModel.getAnnotation(); if (!Strings.isNullOrEmpty(annotation)){ - Map rangeMap = new HashMap<>(); - rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation); + Map rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation); for (Entry rMap : rangeMap.entrySet()){ if (rMap.getValue().contains("range::")){ String value = mapAttribute.get(rMap.getKey().trim()); @@ -424,7 +423,7 @@ public class PolicyValidation { } } else { responseString.append(""+rMap.getKey()+":" + rMap.getKey() - + " is required for the MicroService model " + service + "
"); + + " is required for the MicroService model " + service + HTML_ITALICS_LNBREAK); valid = false; } @@ -433,20 +432,20 @@ public class PolicyValidation { } } else { responseString.append("Micro Service Model: Invalid Model. The model name, " + service + - " of version, " + version + " was not found in the dictionary
"); + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK); valid = false; } } else { - responseString.append("Micro Version: Micro Service Version is required" + "
"); + responseString.append("Micro Version: Micro Service Version is required" + HTML_ITALICS_LNBREAK); valid = false; } } else { - responseString.append("Micro Service: Micro Service is required" + "
"); + responseString.append("Micro Service: Micro Service is required" + HTML_ITALICS_LNBREAK); valid = false; } if(Strings.isNullOrEmpty(policyData.getPriority())){ - responseString.append("Priority: Priority is required" + "
"); + responseString.append("Priority: Priority is required" + HTML_ITALICS_LNBREAK); valid = false; } } @@ -454,7 +453,7 @@ public class PolicyValidation { if (DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){ if(!Strings.isNullOrEmpty(policyData.getOnapName())){ String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName()); - if(!onapNameValidate.contains("success")){ + if(!onapNameValidate.contains(SUCCESS)){ responseString.append("OnapName:" + onapNameValidate + "
"); valid = false; } @@ -570,7 +569,7 @@ public class PolicyValidation { valid = false; }else{ for(String blackList: policyData.getYamlparams().getBlackList()){ - if(blackList==null || !("success".equals(PolicyUtils.policySpecialCharValidator(blackList)))){ + if(blackList==null || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))){ responseString.append(" Guard Params BlackList Should be valid String" + "
"); valid = false; break; @@ -585,7 +584,7 @@ public class PolicyValidation { if(ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){ if(!Strings.isNullOrEmpty(policyData.getActionPerformer())){ String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer()); - if(!actionPerformer.contains("success")){ + if(!actionPerformer.contains(SUCCESS)){ responseString.append("ActionPerformer:" + actionPerformer + "
"); valid = false; } @@ -601,25 +600,25 @@ public class PolicyValidation { 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." + "
"); + responseString.append(EMPTY_COMPONENT_ATTR + "
"); 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." + "
"); + responseString.append(EMPTY_COMPONENT_ATTR + "
"); valid = false; break; } } } }else{ - responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
"); + responseString.append(EMPTY_COMPONENT_ATTR + "
"); valid = false; } if(!Strings.isNullOrEmpty(policyData.getActionAttributeValue())){ String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue()); - if(!actionAttribute.contains("success")){ + if(!actionAttribute.contains(SUCCESS)){ responseString.append("ActionAttribute:" + actionAttribute + "
"); valid = false; }; @@ -662,11 +661,11 @@ public class PolicyValidation { value = "Message:" + safePolicyWarningData.getMessage(); } } - responseString.append("success" + "@#"+ value); + responseString.append(SUCCESS + "@#"+ value); } }else{ if(valid){ - responseString.append("success"); + responseString.append(SUCCESS); } } @@ -681,10 +680,10 @@ public class PolicyValidation { protected String emailValidation(String email, String response){ if(email != null){ String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", "")); - if(!validateEmail.contains("success")){ - response += "Email:" + validateEmail+ "
"; + if(!validateEmail.contains(SUCCESS)){ + response += "Email:" + validateEmail + HTML_ITALICS_LNBREAK; }else{ - return "success"; + return SUCCESS; } } return response; diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java index 072462297..03c1fb0c7 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java @@ -63,16 +63,14 @@ public class PolicyValidationRequestWrapper { policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); JsonObject json = null; - if(root != null){ - json = stringToJsonObject(root.toString()); - - if(json != null){ - if(json.containsKey("policyJSON")){ - policyData.setPolicyJSON(root.get("policyJSON")); - }else{ - String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString(); - policyData.setJsonBody(jsonBodyData); - } + json = stringToJsonObject(root.toString()); + + if(json != null){ + if(json.containsKey("policyJSON")){ + policyData.setPolicyJSON(root.get("policyJSON")); + }else{ + String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString(); + policyData.setJsonBody(jsonBodyData); } } @@ -127,13 +125,13 @@ public class PolicyValidationRequestWrapper { // Set Matching attributes in RainyDayParams in adapter RainyDayParams rainyday = new RainyDayParams(); - rainyday.setServiceType(matching.get("ServiceType")); - rainyday.setVnfType(matching.get("VNFType")); - rainyday.setBbid(matching.get("BB_ID")); - rainyday.setWorkstep(matching.get("WorkStep")); - - - + if(matching != null) { + rainyday.setServiceType(matching.get("ServiceType")); + rainyday.setVnfType(matching.get("VNFType")); + rainyday.setBbid(matching.get("BB_ID")); + rainyday.setWorkstep(matching.get("WorkStep")); + } + Map treatments = parameters.getTreatments(); ArrayList treatmentsTableChoices = new ArrayList<>(); @@ -153,32 +151,32 @@ public class PolicyValidationRequestWrapper { // Set Matching attributes in YAMLParams in adapter YAMLParams yamlparams = new YAMLParams(); - yamlparams.setActor(matching.get("actor")); - yamlparams.setRecipe(matching.get("recipe")); - yamlparams.setGuardActiveStart(matching.get("guardActiveStart")); - yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd")); - - if("GUARD_YAML".equals(ruleProvider)){ - yamlparams.setLimit(matching.get("limit")); - yamlparams.setTimeWindow(matching.get("timeWindow")); - yamlparams.setTimeUnits(matching.get("timeUnits")); - }else{ + if (matching != null) { + yamlparams.setActor(matching.get("actor")); + yamlparams.setRecipe(matching.get("recipe")); + yamlparams.setGuardActiveStart(matching.get("guardActiveStart")); + yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd")); - List blackList = new ArrayList<>(); + if("GUARD_YAML".equals(ruleProvider)){ + yamlparams.setLimit(matching.get("limit")); + yamlparams.setTimeWindow(matching.get("timeWindow")); + yamlparams.setTimeUnits(matching.get("timeUnits")); + }else{ + + List blackList = new ArrayList<>(); - if(!Strings.isNullOrEmpty(matching.get("blackList"))){ - String[] blackListArray = matching.get("blackList").split(","); - for(String element : blackListArray){ - blackList.add(element); - } - } - - yamlparams.setBlackList(blackList); + if(!Strings.isNullOrEmpty(matching.get("blackList"))){ + String[] blackListArray = matching.get("blackList").split(","); + for(String element : blackListArray){ + blackList.add(element); + } + } + + yamlparams.setBlackList(blackList); - } - + } + } policyData.setYamlparams(yamlparams); -; } } else if("Action".equals(parameters.getPolicyClass().toString())){ @@ -216,15 +214,16 @@ public class PolicyValidationRequestWrapper { policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices); ArrayList attributeList = new ArrayList<>(); - - for (String keyField : matching.keySet()) { - LinkedHashMap attributeMap = new LinkedHashMap<>(); - String key = keyField; - String value = matching.get(keyField); - attributeMap.put("key", key); - attributeMap.put("value", value); - attributeList.add(attributeMap); - } + if (matching != null) { + for (String keyField : matching.keySet()) { + LinkedHashMap attributeMap = new LinkedHashMap<>(); + String key = keyField; + String value = matching.get(keyField); + attributeMap.put("key", key); + attributeMap.put("value", value); + attributeList.add(attributeMap); + } + } policyData.setAttributes(attributeList); policyData.setActionAttributeValue(parameters.getActionAttribute()); diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java new file mode 100644 index 000000000..7467d4dfe --- /dev/null +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java @@ -0,0 +1,441 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * Copyright (C) 2017 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.rest.daoimpl; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +import javax.script.SimpleBindings; + +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.h2.tools.Server; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +//import org.onap.policy.conf.HibernateSession; +//import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.jpa.OnapName; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyRoles; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.rest.jpa.SystemLogDB; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.rest.jpa.WatchPolicyNotificationTable; +import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.test.annotation.Rollback; + + +public class PolicyValidationDaoImplTest { + + private static Logger logger = FlexLogger.getLogger(PolicyValidationDaoImplTest.class); + + SessionFactory sessionFactory; + Server server; + PolicyValidationDaoImpl commonClassDao; + + @Before + public void setUp() throws Exception{ + try{ + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName("org.h2.Driver"); + // In-memory DB for testing + dataSource.setUrl("jdbc:h2:mem:test"); + dataSource.setUsername("sa"); + dataSource.setPassword(""); + LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); + sessionBuilder.scanPackages("org.onap.*", "com.*"); + + Properties properties = new Properties(); + properties.put("hibernate.show_sql", "false"); + properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + properties.put("hibernate.hbm2ddl.auto", "drop"); + properties.put("hibernate.hbm2ddl.auto", "create"); + + sessionBuilder.addProperties(properties); + sessionFactory = sessionBuilder.buildSessionFactory(); + + // Set up dao with SessionFactory + commonClassDao = new PolicyValidationDaoImpl(); + PolicyValidationDaoImpl.setSessionfactory(sessionFactory); + //PolicyController.setLogTableLimit("1"); + //HibernateSession.setSession(sessionFactory); + SystemLogDB data1 = new SystemLogDB(); + data1.setDate(new Date()); + data1.setLogtype("INFO"); + data1.setRemote("Test"); + data1.setSystem("Test"); + data1.setType("Test"); + SystemLogDB data2 = new SystemLogDB(); + data2.setDate(new Date()); + data2.setLogtype("error"); + data2.setRemote("Test"); + data2.setSystem("Test"); + data2.setType("Test"); + //HibernateSession.getSession().save(data1); + //HibernateSession.getSession().save(data2); + + // Create TCP server for troubleshooting + server = Server.createTcpServer("-tcpAllowOthers").start(); + System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test"); + + }catch(Exception e){ + System.err.println(e); + fail(); + } + } + + @Test + @Transactional + @Rollback(true) + public void testDB(){ + try{ + // Add data + UserInfo userinfo = new UserInfo(); + userinfo.setUserLoginId("Test"); + userinfo.setUserName("Test"); + commonClassDao.save(userinfo); + OnapName onapName = new OnapName(); + onapName.setOnapName("Test"); + onapName.setUserCreatedBy(userinfo); + onapName.setUserModifiedBy(userinfo); + onapName.setModifiedDate(new Date()); + commonClassDao.save(onapName); + + + List list = commonClassDao.getData(OnapName.class); + assertTrue(list.size() == 1); + logger.debug(list.size()); + logger.debug(list.get(0)); + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + @Test + @Transactional + @Rollback(true) + public void testUser(){ + try{ + // Add data + UserInfo userinfo = new UserInfo(); + String loginId_userName = "Test"; + userinfo.setUserLoginId(loginId_userName); + userinfo.setUserName(loginId_userName); + commonClassDao.save(userinfo); + + + List dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings()); + + assertEquals(1, dataCur.size()); + UserInfo cur = (UserInfo) dataCur.get(0); + assertEquals(loginId_userName, cur.getUserLoginId()); + assertEquals(loginId_userName, cur.getUserName()); + + assertFalse(dataCur.isEmpty()); + + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + @Test + @Transactional + @Rollback(true) + public void getDataByQuery_DashboardController(){ + try{ + // Add data + PolicyEntity pe = new PolicyEntity(); + String name = "TestPolicy"; + pe.setPolicyName(name); + pe.setPolicyData("dummyData"); + pe.prePersist(); + pe.setScope("dummyScope"); + pe.setDescription("descr"); + pe.setDeleted(false); + pe.setCreatedBy("Test"); + commonClassDao.save(pe); + + List dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings()); + + assertTrue(1 == dataCur.size()); + assertTrue( dataCur.get(0) instanceof PolicyEntity); + assertEquals( name, ((PolicyEntity)dataCur.get(0)).getPolicyName()); + assertEquals( pe, ((PolicyEntity)dataCur.get(0))); + + + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + @Test + @Transactional + @Rollback(true) + public void getDataByQuery_AutoPushController(){ + try{ + // Add data + PolicyVersion pv = new PolicyVersion(); + pv.setActiveVersion(2); + pv.setPolicyName("myPname"); + pv.prePersist(); + pv.setCreatedBy("Test"); + pv.setModifiedBy("Test"); + + PolicyVersion pv2 = new PolicyVersion(); + pv2.setActiveVersion(1); + pv2.setPolicyName("test"); + pv2.prePersist(); + pv2.setCreatedBy("Test"); + pv2.setModifiedBy("Test"); + + commonClassDao.save(pv); + commonClassDao.save(pv2); + + String scope = "my"; + scope += "%"; + String query = "From PolicyVersion where policy_name like :scope and id > 0"; + SimpleBindings params = new SimpleBindings(); + params.put("scope", scope); + List dataCur = commonClassDao.getDataByQuery(query, params); + + + assertTrue(1 == dataCur.size()); + assertEquals(pv, (PolicyVersion) dataCur.get(0)); + + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + @Test + @Transactional + @Rollback(true) + public void getDataByQuery_PolicyNotificationMail(){ + try{ + // Add data + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + String policyFileName = "banana"; + watch.setLoginIds("Test"); + watch.setPolicyName("bananaWatch"); + commonClassDao.save(watch); + + if(policyFileName.contains("/")){ + policyFileName = policyFileName.substring(0, policyFileName.indexOf("/")); + policyFileName = policyFileName.replace("/", File.separator); + } + if(policyFileName.contains("\\")){ + policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\")); + policyFileName = policyFileName.replace("\\", "\\\\"); + } + + + // Current Implementation + policyFileName += "%"; + String query = "from WatchPolicyNotificationTable where policyName like:policyFileName"; + SimpleBindings params = new SimpleBindings(); + params.put("policyFileName", policyFileName); + List dataCur = commonClassDao.getDataByQuery(query, params); + + // Assertions + assertTrue(dataCur.size() == 1); + assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); + assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0)); + + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + + @Test + @Transactional + @Rollback(true) + public void getDataByQuery_PolicyController(){ + try{ + // Add data + PolicyEntity pe = new PolicyEntity(); + String name = "actionDummy"; + pe.setPolicyName(name); + pe.setPolicyData("dummyData"); + pe.prePersist(); + pe.setScope("dummyScope"); + pe.setDescription("descr"); + pe.setDeleted(false); + pe.setCreatedBy("Test"); + commonClassDao.save(pe); + + String dbCheckName = "dummyScope:action"; + String[] splitDBCheckName = dbCheckName.split(":"); + + + // Current Implementation + String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; + SimpleBindings params = new SimpleBindings(); + params.put("splitDBCheckName1", splitDBCheckName[1] + "%"); + params.put("splitDBCheckName0", splitDBCheckName[0]); + List dataCur = commonClassDao.getDataByQuery(query, params); + + // Assertions + assertTrue(dataCur.size() == 1); + assertTrue(dataCur.get(0) instanceof PolicyEntity); + assertEquals(pe, (PolicyEntity) dataCur.get(0)); + + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + @Test + @Transactional + @Rollback(true) + public void getDataByQuery_PolicyNotificationController(){ + try{ + // Add data + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + String finalName = "banana"; // Policy File Name + String userId = "Test"; + watch.setLoginIds(userId); + watch.setPolicyName(finalName); + commonClassDao.save(watch); + + + // Current Implementation + String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + SimpleBindings params = new SimpleBindings(); + params.put("finalName", finalName); + params.put("userId", userId); + List dataCur = commonClassDao.getDataByQuery(query, params); + + // Assertions + assertTrue(dataCur.size() == 1); + assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); + assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0) ); + + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + + /* Test for SQL Injection Protection + */ + + @Test + @Transactional + @Rollback(true) + public void getDataByQuery_PolicyNotificationController_Injection(){ + try{ + // Add data + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + String userId = "Test"; + watch.setLoginIds(userId); + watch.setPolicyName("banana"); + commonClassDao.save(watch); + + WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable(); + watch2.setLoginIds(userId); + watch2.setPolicyName("banana2"); + commonClassDao.save(watch2); + + // SQL Injection attempt + String finalName = "banana' OR '1'='1"; + + + // Current Implementation + String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + SimpleBindings params = new SimpleBindings(); + params.put("finalName", finalName); + params.put("userId", userId); + List dataCur = commonClassDao.getDataByQuery(query, params); + + // Assertions + assertTrue(dataCur.size() <= 1); + + if(dataCur.size() >= 1){ + assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); + assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0))); + assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0))); + } + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + @Test + public void testCommonClassDaoImplMethods(){ + try{ + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId("TestID"); + userInfo.setUserName("Test"); + commonClassDao.save(userInfo); + List data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test"); + assertTrue(data.size() == 1); + UserInfo userInfoUpdate = (UserInfo) data.get(0); + userInfoUpdate.setUserName("Test1"); + commonClassDao.update(userInfoUpdate); + List data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId"); + assertTrue(data1.size() == 1); + UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1"); + assertTrue("TestID".equals(data2.getUserLoginId())); + List data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class); + assertTrue(data3.size() == 1); + PolicyRoles roles = new PolicyRoles(); + roles.setRole("admin"); + roles.setLoginId(userInfo); + roles.setScope("test"); + commonClassDao.save(roles); + List roles1 = commonClassDao.getUserRoles(); + assertTrue(roles1.size() == 1); + List multipleData = new ArrayList<>(); + multipleData.add("TestID:Test1"); + List data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName", multipleData); + assertTrue(data4.size() == 1); + commonClassDao.delete(data2); + }catch(Exception e){ + logger.debug("Exception Occured"+e); + fail(); + } + } + + @After + public void deleteDB(){ + sessionFactory.close(); + server.stop(); + + } + +} -- cgit 1.2.3-korg