From 59e3ddb0f0698965962a7d5879a6e39a80744648 Mon Sep 17 00:00:00 2001 From: "Rodriguez, Cuauhtemoctzin (cr056n)" Date: Fri, 4 Aug 2017 16:02:20 -0500 Subject: Add fix for SQL injection. Add fix for SQL injection by passing parameters into getDataByQuery method and binding parameters. Add junit test file. Override equals and hashcode methods for more thorough testing on ActionBodyEntity, ConfigurationDataEntity, PolicyEntity, PolicyVersion, WatchPolicyNotificationTable classes. Issue-Id: [POLICY-158] Change-Id: Icebe1ca1ff01c8ea7435729967f4d349a1026054 Signed-off-by: ITSERVICES\cr056n --- POLICY-SDK-APP/pom.xml | 10 + .../onap/policy/admin/PolicyManagerServlet.java | 131 ++++--- .../onap/policy/admin/PolicyNotificationMail.java | 8 +- .../onap/policy/controller/AutoPushController.java | 15 +- .../policy/controller/DashboardController.java | 95 ++--- .../onap/policy/controller/PolicyController.java | 65 ++-- .../PolicyExportAndImportController.java | 8 +- .../controller/PolicyNotificationController.java | 8 +- .../org/onap/policy/daoImp/CommonClassDaoImpl.java | 35 +- .../policy/admin/PolicyManagerServletTest.java | 27 +- .../policy/controller/PolicyControllerTest.java | 4 +- .../onap/policy/daoImp/CommonClassDaoImplTest.java | 385 +++++++++++++++++++++ 12 files changed, 644 insertions(+), 147 deletions(-) create mode 100644 POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java (limited to 'POLICY-SDK-APP') diff --git a/POLICY-SDK-APP/pom.xml b/POLICY-SDK-APP/pom.xml index b8ac94bd2..fe861fea9 100644 --- a/POLICY-SDK-APP/pom.xml +++ b/POLICY-SDK-APP/pom.xml @@ -232,5 +232,15 @@ snakeyaml 1.16 + + org.apache.tomcat + tomcat-jdbc + 8.0.24 + + + org.apache.tomcat + tomcat-dbcp + 8.5.9 + diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java index 6fab5a608..b4817147c 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java @@ -45,6 +45,7 @@ import java.util.Set; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonReader; +import javax.script.SimpleBindings; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; @@ -371,8 +372,11 @@ public class PolicyManagerServlet extends HttpServlet { if(policyName.contains("\\")){ policyName = policyName.replace("\\", "\\\\"); } - String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0"; - List activeData = controller.getDataByQuery(policyVersionQuery); + String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0"; + SimpleBindings pvParams = new SimpleBindings(); + pvParams.put("policyName", policyName); + pvParams.put("version", version); + List activeData = controller.getDataByQuery(policyVersionQuery, pvParams); if(!activeData.isEmpty()){ PolicyVersion policy = (PolicyVersion) activeData.get(0); JSONObject el = new JSONObject(); @@ -461,8 +465,11 @@ public class PolicyManagerServlet extends HttpServlet { dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); } String[] splitDBCheckName = dbCheckName.split(":"); - String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'"; - List policyEntity = controller.getDataByQuery(peQuery); + String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0"; + SimpleBindings policyParams = new SimpleBindings(); + policyParams.put("splitDBCheckName_1", splitDBCheckName[1]); + policyParams.put("splitDBCheckName_0", splitDBCheckName[0]); + List policyEntity = controller.getDataByQuery(peQuery, policyParams); PolicyEntity pentity = (PolicyEntity) policyEntity.get(0); if(pentity.isDeleted()){ return error("The Policy is Not Existing in Workspace"); @@ -520,8 +527,11 @@ public class PolicyManagerServlet extends HttpServlet { } PolicyController controller = getPolicyControllerInstance(); String[] split = path.split(":"); - String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; - List queryData = controller.getDataByQuery(query); + String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; + SimpleBindings peParams = new SimpleBindings(); + peParams.put("split_1", split[1]); + peParams.put("split_0", split[0]); + List queryData = controller.getDataByQuery(query, peParams); if(!queryData.isEmpty()){ PolicyEntity entity = (PolicyEntity) queryData.get(0); File temp = null; @@ -650,13 +660,15 @@ public class PolicyManagerServlet extends HttpServlet { private List queryPolicyEditorScopes(String scopeName){ String scopeNamequery = ""; + SimpleBindings params = new SimpleBindings(); if(scopeName == null){ scopeNamequery = "from PolicyEditorScopes"; }else{ - scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; + scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName"; + params.put("scopeName", scopeName + "%"); } PolicyController controller = getPolicyControllerInstance(); - List scopesList = controller.getDataByQuery(scopeNamequery); + List scopesList = controller.getDataByQuery(scopeNamequery, params); return scopesList; } @@ -669,10 +681,14 @@ public class PolicyManagerServlet extends HttpServlet { if(scopeName.contains("\\")){ scopeName = scopeName.replace("\\", "\\\\\\\\"); } - String query = "from PolicyVersion where POLICY_NAME like '" +scopeName+"%'"; - String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like '" +scopeName+"%'"; - List activePolicies = controller.getDataByQuery(query); - List scopesList = controller.getDataByQuery(scopeNamequery); + String query = "from PolicyVersion where POLICY_NAME like :scopeName"; + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName"; + + SimpleBindings params = new SimpleBindings(); + params.put("scopeName", scopeName + "%"); + + List activePolicies = controller.getDataByQuery(query, params); + List scopesList = controller.getDataByQuery(scopeNamequery, params); for(Object list : scopesList){ PolicyEditorScopes scopeById = (PolicyEditorScopes) list; String scope = scopeById.getScopeName(); @@ -773,10 +789,12 @@ public class PolicyManagerServlet extends HttpServlet { newScopeName = newScopeName.replace("\\", "\\\\\\\\"); } PolicyController controller = getPolicyControllerInstance(); - String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'"; - String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; - List activePolicies = controller.getDataByQuery(query); - List scopesList = controller.getDataByQuery(scopeNamequery); + String query = "from PolicyVersion where POLICY_NAME like :scopeName"; + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName"; + SimpleBindings pvParams = new SimpleBindings(); + pvParams.put("scopeName", scopeName + "%"); + List activePolicies = controller.getDataByQuery(query, pvParams); + List scopesList = controller.getDataByQuery(scopeNamequery, pvParams); for(Object object : activePolicies){ PolicyVersion activeVersion = (PolicyVersion) object; String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml"; @@ -866,8 +884,11 @@ public class PolicyManagerServlet extends HttpServlet { String[] oldPolicySplit = oldPolicyCheck.split(":"); //Check PolicyEntity table with newPolicy Name - String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'"; - List queryData = controller.getDataByQuery(policyEntityquery); + String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_1"; + SimpleBindings policyParams = new SimpleBindings(); + policyParams.put("newPolicySplit_1", newPolicySplit[1]); + policyParams.put("newPolicySplit_0", newPolicySplit[0]); + List queryData = controller.getDataByQuery(policyEntityquery, policyParams); if(!queryData.isEmpty()){ entity = (PolicyEntity) queryData.get(0); return error("Policy rename failed. Since, the policy with same name already exists."); @@ -875,20 +896,26 @@ public class PolicyManagerServlet extends HttpServlet { //Query the Policy Entity with oldPolicy Name String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf(".")); - String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'"; - List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery); + String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0"; + SimpleBindings params = new SimpleBindings(); + params.put("policyEntityCheck", policyEntityCheck + "%"); + params.put("oldPolicySplit_0", oldPolicySplit[0]); + List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params); if(!oldEntityData.isEmpty()){ String groupQuery = "FROM PolicyGroupEntity where ("; + SimpleBindings geParams = new SimpleBindings(); for(int i=0; i groupEntityData = controller.getDataByQuery(groupQuery); + List groupEntityData = controller.getDataByQuery(groupQuery, geParams); if(groupEntityData.size() > 0){ return error("Policy rename failed. Since the policy or its version is active in PDP Groups."); } @@ -1077,15 +1104,21 @@ public class PolicyManagerServlet extends HttpServlet { boolean success = false; //Check PolicyEntity table with newPolicy Name - String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'"; - List queryData = controller.getDataByQuery(policyEntityquery); + String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0"; + SimpleBindings policyParams = new SimpleBindings(); + policyParams.put("newPolicySplit_1", newPolicySplit[1]); + policyParams.put("newPolicySplit_0", newPolicySplit[0]); + List queryData = controller.getDataByQuery(policyEntityquery, policyParams); if(!queryData.isEmpty()){ return error("Policy already exists with same name"); } //Query the Policy Entity with oldPolicy Name - policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; - queryData = controller.getDataByQuery(policyEntityquery); + policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0"; + SimpleBindings peParams = new SimpleBindings(); + peParams.put("oldPolicySplit_1", oldPolicySplit[1]); + peParams.put("oldPolicySplit_0", oldPolicySplit[0]); + queryData = controller.getDataByQuery(policyEntityquery, peParams); if(!queryData.isEmpty()){ entity = (PolicyEntity) queryData.get(0); } @@ -1131,6 +1164,7 @@ public class PolicyManagerServlet extends HttpServlet { String policyNamewithExtension = path.replace("/", File.separator); String policyVersionName = policyNamewithExtension.replace(".xml", ""); String query = ""; + SimpleBindings policyParams = new SimpleBindings(); if(path.endsWith(".xml")){ policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")); policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, "."); @@ -1143,13 +1177,16 @@ public class PolicyManagerServlet extends HttpServlet { splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_"); } String[] split = splitPolicyName.split(":"); - query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'"; + query = "FROM PolicyEntity where policyName like split_1 and scope = split_0"; + policyParams.put("split_1", split[1] + "%"); + policyParams.put("split_0", split[0]); }else{ policyNamewithoutExtension = path.replace(File.separator, "."); - query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'"; + query = "FROM PolicyEntity where scope like :policyNamewithoutExtension"; + policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%"); } - List policyEntityobjects = controller.getDataByQuery(query); + List policyEntityobjects = controller.getDataByQuery(query, policyParams); String activePolicyName = null; boolean pdpCheck = false; if(path.endsWith(".xml")){ @@ -1159,8 +1196,10 @@ public class PolicyManagerServlet extends HttpServlet { if(!policyEntityobjects.isEmpty()){ for(Object object : policyEntityobjects){ policyEntity = (PolicyEntity) object; - String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; - List groupobject = controller.getDataByQuery(groupEntityquery); + String groupEntityquery = "from PolicyGroupEntity where policyid = :policyId"; + SimpleBindings pgeParams = new SimpleBindings(); + pgeParams.put("policyId", policyEntity.getPolicyId()); + List groupobject = controller.getDataByQuery(groupEntityquery, pgeParams); if(!groupobject.isEmpty()){ pdpCheck = true; activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName(); @@ -1202,14 +1241,21 @@ public class PolicyManagerServlet extends HttpServlet { }else if("CURRENT".equals(deleteVersion)){ String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1); String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, "."); - query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'"; - List policyEntitys = controller.getDataByQuery(query); + query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope"; + + SimpleBindings peParams = new SimpleBindings(); + peParams.put("currentVersionPolicyName", currentVersionPolicyName); + peParams.put("currentVersionScope", currentVersionScope); + + List policyEntitys = controller.getDataByQuery(query, peParams); if(!policyEntitys.isEmpty()){ policyEntity = (PolicyEntity) policyEntitys.get(0); } if(policyEntity != null){ - String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0"; - List groupobject = controller.getDataByQuery(groupEntityquery); + String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0"; + SimpleBindings geParams = new SimpleBindings(); + geParams.put("policyEntityId", policyEntity.getPolicyId()); + List groupobject = controller.getDataByQuery(groupEntityquery, geParams); if(groupobject.isEmpty()){ //Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); @@ -1260,8 +1306,10 @@ public class PolicyManagerServlet extends HttpServlet { if(!policyEntityobjects.isEmpty()){ for(Object object : policyEntityobjects){ policyEntity = (PolicyEntity) object; - String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; - List groupobject = controller.getDataByQuery(groupEntityquery); + String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId"; + SimpleBindings geParams = new SimpleBindings(); + geParams.put("policyEntityId", policyEntity.getPolicyId()); + List groupobject = controller.getDataByQuery(groupEntityquery, geParams); if(!groupobject.isEmpty()){ pdpCheck = true; activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName()); @@ -1344,8 +1392,11 @@ public class PolicyManagerServlet extends HttpServlet { } String[] split = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; - List queryData = controller.getDataByQuery(query); + String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; + SimpleBindings peParams = new SimpleBindings(); + peParams.put("split_1", split[1]); + peParams.put("split_0", split[0]); + List queryData = controller.getDataByQuery(query, peParams); PolicyEntity entity = (PolicyEntity) queryData.get(0); InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8)); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java index bf89c01ff..a4e476200 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java @@ -30,6 +30,7 @@ import java.util.Properties; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; +import javax.script.SimpleBindings; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -116,9 +117,12 @@ public class PolicyNotificationMail{ policyFileName = policyFileName.replace("\\", "\\\\"); } - String query = "from WatchPolicyNotificationTable where policyName like'" +policyFileName+"%'"; + policyFileName += "%"; + String query = "from WatchPolicyNotificationTable where policyName like:policyFileName"; boolean sendFlag = false; - List watchList = policyNotificationDao.getDataByQuery(query); + SimpleBindings params = new SimpleBindings(); + params.put("policyFileName", policyFileName); + List watchList = policyNotificationDao.getDataByQuery(query, params); if(watchList != null && !watchList.isEmpty()){ for(Object watch : watchList){ WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch; diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java index 7d601d6f3..b72993f19 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -38,6 +38,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -148,8 +149,11 @@ public class AutoPushController extends RestrictedBaseController{ }else{ if(!scopes.isEmpty()){ for(String scope : scopes){ - String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0"; - List filterdatas = commonClassDao.getDataByQuery(query); + scope += "%"; + String query = "From PolicyVersion where policy_name like :scope and id > 0"; + SimpleBindings params = new SimpleBindings(); + params.put("scope", scope); + List filterdatas = commonClassDao.getDataByQuery(query, params); if(filterdatas != null){ for(int i =0; i < filterdatas.size(); i++){ data.add(filterdatas.get(i)); @@ -236,8 +240,11 @@ public class AutoPushController extends RestrictedBaseController{ dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); } String[] split = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; - List queryData = controller.getDataByQuery(query); + String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; + SimpleBindings policyParams = new SimpleBindings(); + policyParams.put("split_1", split[1]); + policyParams.put("split_0", split[0]); + List queryData = controller.getDataByQuery(query, policyParams); PolicyEntity policyEntity = (PolicyEntity) queryData.get(0); File temp = new File(name); BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java index d6d4a2c69..aedb94301 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java @@ -7,9 +7,9 @@ * 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. @@ -40,6 +40,7 @@ import javax.management.ReflectionException; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; +import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -76,16 +77,16 @@ public class DashboardController extends RestrictedBaseController{ private static final Logger policyLogger = FlexLogger.getLogger(DashboardController.class); @Autowired SystemLogDbDao systemDAO; - + @Autowired CommonClassDao commonClassDao; - + private int pdpCount; private PDPGroupContainer pdpConatiner; private ArrayList pdpStatusData; private ArrayList papStatusData; private ArrayList policyActivityData; - + private PolicyController policyController; public PolicyController getPolicyController() { return policyController; @@ -94,11 +95,11 @@ public class DashboardController extends RestrictedBaseController{ public void setPolicyController(PolicyController policyController) { this.policyController = policyController; } - + private PolicyController getPolicyControllerInstance(){ return policyController != null ? getPolicyController() : new PolicyController(); } - + @RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getData(HttpServletRequest request, HttpServletResponse response){ try{ @@ -113,7 +114,7 @@ public class DashboardController extends RestrictedBaseController{ policyLogger.error("Exception Occured"+e); } } - + @RequestMapping(value={"/get_DashboardSystemAlertData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response){ try{ @@ -128,7 +129,7 @@ public class DashboardController extends RestrictedBaseController{ policyLogger.error("Exception Occured"+e); } } - + @RequestMapping(value={"/get_DashboardPAPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response){ try{ @@ -145,7 +146,7 @@ public class DashboardController extends RestrictedBaseController{ policyLogger.error("Exception Occured"+e); } } - + @RequestMapping(value={"/get_DashboardPDPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response){ try{ @@ -164,7 +165,7 @@ public class DashboardController extends RestrictedBaseController{ policyLogger.error("Exception Occured"+e); } } - + @RequestMapping(value={"/get_DashboardPolicyActivityData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response){ try{ @@ -183,7 +184,7 @@ public class DashboardController extends RestrictedBaseController{ policyLogger.error("Exception Occured"+e); } } - + /* * Add the PAP information to the PAP Table */ @@ -195,7 +196,7 @@ public class DashboardController extends RestrictedBaseController{ Set groups = controller.getPapEngine().getOnapPDPGroups(); if (groups == null) { papStatus = "UNKNOWN"; - throw new PAPException("PAP not running"); + throw new PAPException("PAP not running"); }else { papStatus = "IS_OK"; } @@ -207,23 +208,23 @@ public class DashboardController extends RestrictedBaseController{ JSONObject object = new JSONObject(); object.put("system", papURL); object.put("status", papStatus); - List data = commonClassDao.getDataByQuery("from PolicyEntity"); + List data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings()); object.put("noOfPolicy", data.size()); object.put("noOfConnectedTrap", pdpCount); papStatusData.add(0, object); } - + /** * Add PDP Information to the PDP Table - * + * */ - public void addPDPToTable(){ + public void addPDPToTable(){ pdpCount = 0; pdpStatusData = new ArrayList<>(); long naCount; long denyCount = 0; long permitCount = 0; - for (PDPGroup group : this.pdpConatiner.getGroups()){ + for (PDPGroup group : this.pdpConatiner.getGroups()){ for (PDP pdp : group.getPdps()){ naCount = -1; if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){ @@ -247,7 +248,7 @@ public class DashboardController extends RestrictedBaseController{ object.put("denyCount", "NA"); object.put("naCount", "NA"); pdpStatusData.add(object); - }else{ + }else{ JSONObject object = new JSONObject(); object.put("id", pdp.getId()); object.put("name", pdp.getName()); @@ -263,23 +264,23 @@ public class DashboardController extends RestrictedBaseController{ } } } - - private static String parseIPSystem(String line) { + + private static String parseIPSystem(String line) { Pattern pattern = Pattern.compile("://(.+?):"); Matcher ip = pattern.matcher(line); if (ip.find()) { return ip.group(1); - } + } return null; } - + /* * Contact JMX Connector Sever and return the value of the given jmxAttribute */ @SuppressWarnings({ "rawtypes", "unchecked" }) private long getRequestCounts(String host, int port, String jmxAttribute) { - + policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server"); HashMap map = new HashMap(); map = null; @@ -295,7 +296,7 @@ public class DashboardController extends RestrictedBaseController{ policyLogger.error("MalformedURLException for JMX connection" , e); } catch (IOException e) { policyLogger.error("Error in reteriving" + jmxAttribute + " from JMX connection", e); - } catch (AttributeNotFoundException e) { + } catch (AttributeNotFoundException e) { policyLogger.error("AttributeNotFoundException " + jmxAttribute + " for JMX connection", e); } catch (InstanceNotFoundException e) { policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e); @@ -307,15 +308,15 @@ public class DashboardController extends RestrictedBaseController{ } catch (ReflectionException e) { policyLogger.error("ReflectionException for JMX connection", e); } - + return -1; } - + private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException{ return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"); } - - + + /* * Add the information to the Policy Table */ @@ -325,9 +326,9 @@ public class DashboardController extends RestrictedBaseController{ int policyFireCount = 0; Map policyMap = new HashMap<>(); Object policyList = null; - //get list of policy - - for (PDPGroup group : this.pdpConatiner.getGroups()){ + //get list of policy + + for (PDPGroup group : this.pdpConatiner.getGroups()){ for (PDPPolicy policy : group.getPolicies()){ try{ policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId()); @@ -335,8 +336,8 @@ public class DashboardController extends RestrictedBaseController{ policyLogger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e); } } - - for (PDP pdp : group.getPdps()){ + + for (PDP pdp : group.getPdps()){ // Add rows to the Policy Table policyList = null; if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){ @@ -345,16 +346,16 @@ public class DashboardController extends RestrictedBaseController{ } if (policyList != null && policyList.toString().length() > 3){ String[] splitPolicy = policyList.toString().split(","); - for (String policyKeyValue : splitPolicy){ - policyID = urnPolicyID(policyKeyValue); - policyFireCount = countPolicyID(policyKeyValue); + for (String policyKeyValue : splitPolicy){ + policyID = urnPolicyID(policyKeyValue); + policyFireCount = countPolicyID(policyKeyValue); if (policyID != null ){ if (policyMap.containsKey(policyID)){ JSONObject object = new JSONObject(); object.put("policyId", policyMap.get(policyID)); object.put("fireCount", policyFireCount); object.put("system", pdp.getId()); - policyActivityData.add(object); + policyActivityData.add(object); } } } @@ -372,11 +373,11 @@ public class DashboardController extends RestrictedBaseController{ object.put("system", pdp.getId()); policyActivityData.add(object); } - } + } } } } - + /* * Contact JMX Connector Sever and return the list of {policy id , count} */ @@ -397,7 +398,7 @@ public class DashboardController extends RestrictedBaseController{ policyLogger.error("MalformedURLException for JMX connection" , e); } catch (IOException e) { policyLogger.error("AttributeNotFoundException for policyMap" , e); - } catch (AttributeNotFoundException e) { + } catch (AttributeNotFoundException e) { policyLogger.error("AttributeNotFoundException for JMX connection", e); } catch (InstanceNotFoundException e) { policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e); @@ -409,22 +410,22 @@ public class DashboardController extends RestrictedBaseController{ } catch (ReflectionException e) { policyLogger.error("ReflectionException for JMX connection", e); } - + return null; - + } - + private static String urnPolicyID(String line){ - String[] splitLine = line.toString().split("="); + String[] splitLine = line.toString().split("="); String removeSpaces = splitLine[0].replaceAll("\\s+", ""); return removeSpaces.replace("{", ""); } - + private static Integer countPolicyID(String line){ String[] splitLine = line.toString().split("="); String sCount = splitLine[1].replace("}", ""); int intCount = Integer.parseInt(sCount); return intCount; } - + } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java index 375ee2d10..35b9b959d 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -7,9 +7,9 @@ * 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. @@ -33,6 +33,7 @@ import java.util.Properties; import javax.annotation.PostConstruct; import javax.mail.MessagingException; +import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -65,7 +66,7 @@ import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -75,7 +76,7 @@ public class PolicyController extends RestrictedBaseController { private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class); private static CommonClassDao commonClassDao; - + // Our authorization object // XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization(); @@ -108,7 +109,7 @@ public class PolicyController extends RestrictedBaseController { private static final String characterEncoding = "UTF-8"; private static final String contentType = "application/json"; private static final String file = "file"; - + //Smtp Java Mail Properties private static String smtpHost = null; private static String smtpPort = null; @@ -127,20 +128,20 @@ public class PolicyController extends RestrictedBaseController { private static String xacmldbUserName = null; private static String xacmldbPassword = null; - //AutoPush feature. + //AutoPush feature. private static String autoPushAvailable; private static String autoPushDSClosedLoop; private static String autoPushDSFirewall; private static String autoPushDSMicroservice; private static String autoPushPDPGroup; - + //papURL private static String papUrl; - + //MicroService Model Properties private static String msOnapName; private static String msPolicyName; - + //WebApp directories private static String configHome; private static String actionHome; @@ -162,7 +163,7 @@ public class PolicyController extends RestrictedBaseController { // load a properties file prop.load(input); //pap url - setPapUrl(prop.getProperty("xacml.rest.pap.url")); + setPapUrl(prop.getProperty("xacml.rest.pap.url")); // get the property values setSmtpHost(prop.getProperty("onap.smtp.host")); setSmtpPort(prop.getProperty("onap.smtp.port")); @@ -192,7 +193,7 @@ public class PolicyController extends RestrictedBaseController { //WebApp directories setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config"); setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action"); - //Get the Property Values for Dashboard tab Limit + //Get the Property Values for Dashboard tab Limit try{ setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit")); setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit")); @@ -214,7 +215,7 @@ public class PolicyController extends RestrictedBaseController { } } - //Initialize the FunctionDefinition table at Server Start up + //Initialize the FunctionDefinition table at Server Start up Map> functionMap = getFunctionDatatypeMap(); for (Datatype id : functionMap.keySet()) { List functionDefinations = functionMap.get(id); @@ -225,7 +226,7 @@ public class PolicyController extends RestrictedBaseController { } - public static Map> getFunctionDatatypeMap() { + public static Map> getFunctionDatatypeMap() { synchronized(mapAccess) { if (mapDatatype2Function == null) { buildFunctionMaps(); @@ -245,8 +246,8 @@ public class PolicyController extends RestrictedBaseController { private static void buildFunctionMaps() { mapDatatype2Function = new HashMap<>(); - mapID2Function = new HashMap<>(); - List functiondefinitions = commonClassDao.getData(FunctionDefinition.class); + mapID2Function = new HashMap<>(); + List functiondefinitions = commonClassDao.getData(FunctionDefinition.class); for (int i = 0; i < functiondefinitions.size(); i ++) { FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i); mapID2Function.put(value.getXacmlid(), value); @@ -271,7 +272,7 @@ public class PolicyController extends RestrictedBaseController { policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e); } } - + public PolicyEntity getPolicyEntityData(String scope, String policyName){ String key = scope + ":" + policyName; List data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key); @@ -319,19 +320,19 @@ public class PolicyController extends RestrictedBaseController { } } - //Policy tabs Model and View + //Policy tabs Model and View @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET) public ModelAndView view(HttpServletRequest request){ String myRequestURL = request.getRequestURL().toString(); try { // // Set the URL for the RESTful PAP Engine - // + // setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); } catch (Exception e) { policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e); - } + } Map model = new HashMap<>(); return new ModelAndView("policy_Editor","model", model); } @@ -351,7 +352,7 @@ public class PolicyController extends RestrictedBaseController { } public static boolean getActivePolicy(String query) { - if(commonClassDao.getDataByQuery(query).size() > 0){ + if(commonClassDao.getDataByQuery(query, new SimpleBindings()).size() > 0){ return true; }else{ return false; @@ -359,9 +360,9 @@ public class PolicyController extends RestrictedBaseController { } public void executeQuery(String query) { - commonClassDao.updateQuery(query); + commonClassDao.updateQuery(query); } - + public void saveData(Object cloneEntity) { commonClassDao.save(cloneEntity); } @@ -373,7 +374,7 @@ public class PolicyController extends RestrictedBaseController { public void deleteData(Object entity) { commonClassDao.delete(entity); } - + public List getData(@SuppressWarnings("rawtypes") Class className){ return commonClassDao.getData(className); } @@ -382,8 +383,8 @@ public class PolicyController extends RestrictedBaseController { return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); } - public List getDataByQuery(String query){ - return commonClassDao.getDataByQuery(query); + public List getDataByQuery(String query, SimpleBindings params){ + return commonClassDao.getDataByQuery(query, params); } @@ -391,8 +392,8 @@ public class PolicyController extends RestrictedBaseController { public Object getEntityItem(Class className, String columname, String key){ return commonClassDao.getEntityItem(className, columname, key); } - - + + public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){ PolicyNotificationMail email = new PolicyNotificationMail(); try { @@ -413,8 +414,11 @@ public class PolicyController extends RestrictedBaseController { dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); } String[] splitDBCheckName = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName like'"+splitDBCheckName[1]+"%' and scope ='"+splitDBCheckName[0]+"'"; - List policyEntity = commonClassDao.getDataByQuery(query); + 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 policyEntity = commonClassDao.getDataByQuery(query, params); List av = new ArrayList<>(); for(Object entity : policyEntity){ PolicyEntity pEntity = (PolicyEntity) entity; @@ -448,7 +452,7 @@ public class PolicyController extends RestrictedBaseController { public static void setSystemAlertTableLimit(String systemAlertTableLimit) { PolicyController.systemAlertTableLimit = systemAlertTableLimit; } - + public static CommonClassDao getCommonClassDao() { return commonClassDao; } @@ -693,4 +697,3 @@ public class PolicyController extends RestrictedBaseController { return file; } } - diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java index d26781c0f..bb6f38b8e 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java @@ -32,6 +32,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Set; +import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -279,8 +280,11 @@ public class PolicyExportAndImportController extends RestrictedBaseController { if(finalColumn){ scope = policyEntity.getScope().replace(".", File.separator); - String query = "FROM PolicyEntity where policyName = '"+policyEntity.getPolicyName()+"' and scope ='"+policyEntity.getScope()+"'"; - List queryData = controller.getDataByQuery(query); + String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope"; + SimpleBindings params = new SimpleBindings(); + params.put("policyName", policyEntity.getPolicyName()); + params.put("policyScope", policyEntity.getScope()); + List queryData = controller.getDataByQuery(query, params); if(!queryData.isEmpty()){ continue; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java index f3291a79b..731217573 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java @@ -28,6 +28,7 @@ import java.io.File; import java.io.PrintWriter; import java.util.List; +import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -86,8 +87,11 @@ public class PolicyNotificationController extends RestrictedBaseController { if(finalName.contains("\\")){ finalName = finalName.replace("\\", "\\\\"); } - String query = "from WatchPolicyNotificationTable where POLICYNAME = '"+finalName+"' and LOGINIDS = '"+userId+"'"; - List watchList = commonClassDao.getDataByQuery(query); + String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + SimpleBindings params = new SimpleBindings(); + params.put("finalName", finalName); + params.put("userId", userId); + List watchList = commonClassDao.getDataByQuery(query, params); if(watchList.isEmpty()){ if(finalName.contains("\\\\")){ finalName = finalName.replace("\\\\", File.separator); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java index 05bf50f1b..336c42ca8 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java @@ -22,6 +22,9 @@ package org.onap.policy.daoImp; import java.util.ArrayList; import java.util.List; +import java.util.Map; + +import javax.script.SimpleBindings; import org.hibernate.Criteria; import org.hibernate.Query; @@ -44,9 +47,26 @@ import org.springframework.stereotype.Service; public class CommonClassDaoImpl implements CommonClassDao{ private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class); + private static SessionFactory sessionfactory; + + public static SessionFactory getSessionfactory() { + return sessionfactory; + } + + public static void setSessionfactory(SessionFactory sessionfactory) { + CommonClassDaoImpl.sessionfactory = sessionfactory; + } + + @Autowired + private CommonClassDaoImpl(SessionFactory sessionfactory){ + CommonClassDaoImpl.sessionfactory = sessionfactory; + } + + public CommonClassDaoImpl(){ + //Default Constructor + } + - @Autowired - SessionFactory sessionfactory; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @@ -237,24 +257,29 @@ public class CommonClassDaoImpl implements CommonClassDao{ @Override public void deleteAll() {} - + @SuppressWarnings("unchecked") @Override - public List getDataByQuery(String query) { + public List getDataByQuery(String query, SimpleBindings params) { Session session = sessionfactory.openSession(); Transaction tx = session.beginTransaction(); List data = null; try { Query hbquery = session.createQuery(query); + for (Map.Entry paramPair : params.entrySet()) { + hbquery.setParameter(paramPair.getKey(), paramPair.getValue()); + } 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 + "Error While Querying Database Table"+e); + throw e; }finally{ try{ session.close(); }catch(Exception e1){ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + throw e1; } } return data; diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java index e3de43a83..a034c8ae9 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java @@ -28,6 +28,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import javax.script.SimpleBindings; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -150,7 +151,7 @@ public class PolicyManagerServletTest extends Mockito{ BufferedReader reader = new BufferedReader(new StringReader("{params: { mode: 'DESCRIBEPOLICYFILE', path: 'com.Config_SampleTest1206.1.xml'}}")); try { when(request.getReader()).thenReturn(reader); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'")).thenReturn(basePolicyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(basePolicyData); servlet.setPolicyController(controller); servlet.doPost(request, response); } catch (Exception e1) { @@ -175,9 +176,9 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("from PolicyEditorScopes")).thenReturn(policyEditorScopes); - when(controller.getDataByQuery("from PolicyEditorScopes where SCOPENAME like 'com%'")).thenReturn(policyEditorScopes); - when(controller.getDataByQuery("from PolicyVersion where POLICY_NAME like 'com%'")).thenReturn(policyVersion); + when(controller.getDataByQuery("from PolicyEditorScopes", new SimpleBindings())).thenReturn(policyEditorScopes); + when(controller.getDataByQuery("from PolicyEditorScopes where SCOPENAME like 'com%'", new SimpleBindings())).thenReturn(policyEditorScopes); + when(controller.getDataByQuery("from PolicyVersion where POLICY_NAME like 'com%'", new SimpleBindings())).thenReturn(policyVersion); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -202,7 +203,7 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'")).thenReturn(basePolicyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(basePolicyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -248,7 +249,7 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml' and scope ='com'")).thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -294,7 +295,7 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_BRMS_Raw_TestBRMSRawPolicy.1.xml' and scope ='com'")).thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_BRMS_Raw_TestBRMSRawPolicy.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -340,7 +341,7 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_Fault_TestClosedLoopPolicy.1.xml' and scope ='com'")).thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_Fault_TestClosedLoopPolicy.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -386,7 +387,7 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_PM_TestClosedLoopPMPolicy.1.xml' and scope ='com'")).thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_PM_TestClosedLoopPMPolicy.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -440,7 +441,7 @@ public class PolicyManagerServletTest extends Mockito{ when(request.getReader()).thenReturn(reader); when(commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", "resource=SampleResource,service=SampleService,type=SampleType,closedLoopControlName=SampleClosedLoop")).thenReturn(groupListData); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_MS_vFirewall.1.xml' and scope ='com'")).thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_MS_vFirewall.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -486,7 +487,7 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_FW_TestFireWallPolicy.1.xml' and scope ='com'")).thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_FW_TestFireWallPolicy.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -530,7 +531,7 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Action_TestActionPolicy.1.xml' and scope ='com'")).thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Action_TestActionPolicy.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -568,7 +569,7 @@ public class PolicyManagerServletTest extends Mockito{ try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml' and scope ='com'")).thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java index 817a624b7..382637c1b 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java @@ -25,6 +25,8 @@ import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; +import javax.script.SimpleBindings; + import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; @@ -56,7 +58,7 @@ public class PolicyControllerTest { entity.setScope("com"); data.add(entity); - when(commonClassDao.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'")).thenReturn(data); + when(commonClassDao.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(data); } @Test diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java new file mode 100644 index 000000000..78dd20af2 --- /dev/null +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java @@ -0,0 +1,385 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * 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.daoImp; + +import static org.junit.Assert.*; + +import java.io.File; +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.daoImp.CommonClassDaoImpl; +import org.onap.policy.rest.jpa.OnapName; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.rest.jpa.WatchPolicyNotificationTable; +import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; +import org.springframework.test.annotation.Rollback; +import org.springframework.transaction.annotation.Transactional; + +public class CommonClassDaoImplTest{ + + private static Logger logger = FlexLogger.getLogger(CommonClassDaoImplTest.class); + + SessionFactory sessionFactory; + Server server; + CommonClassDaoImpl 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 CommonClassDaoImpl(); + CommonClassDaoImpl.setSessionfactory(sessionFactory); + + // 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(); + } + } + + + @After + public void deleteDB(){ + sessionFactory.close(); + server.stop(); + + } +} -- cgit 1.2.3-korg