Add fix for SQL injection. 67/7367/3
authorRodriguez, Cuauhtemoctzin (cr056n) <cr056n@us.att.com>
Fri, 4 Aug 2017 21:02:20 +0000 (16:02 -0500)
committerTemoc Rodriguez <cr056n@att.com>
Mon, 14 Aug 2017 18:26:18 +0000 (18:26 +0000)
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 <cr056n@att.com>
20 files changed:
ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java
ONAP-REST/src/main/java/org/onap/policy/rest/dao/CommonClassDao.java
ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionBodyEntity.java
ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConfigurationDataEntity.java
ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java
ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyVersion.java
ONAP-REST/src/main/java/org/onap/policy/rest/jpa/WatchPolicyNotificationTable.java
POLICY-SDK-APP/pom.xml
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java
POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java
POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java [new file with mode: 0644]

index 047342a..923e528 100644 (file)
@@ -38,6 +38,8 @@ import java.util.UUID;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import javax.script.SimpleBindings;
+
 import org.apache.commons.io.FilenameUtils;
 import org.onap.policy.common.logging.eelf.MessageCodes;
 import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -189,8 +191,10 @@ public class CreateBrmsParamPolicy extends Policy {
        private String getValueFromDictionary(String templateName){
                String ruleTemplate = null;
                CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
-               String queryString="from BRMSParamTemplate where param_template_name= '"+templateName+"'";
-               List<Object> result = dbConnection.getDataByQuery(queryString);
+               String queryString="from BRMSParamTemplate where param_template_name= :templateName";
+               SimpleBindings params = new SimpleBindings();
+               params.put("templateName", templateName);
+               List<Object> result = dbConnection.getDataByQuery(queryString, params);
                if(!result.isEmpty()){
                        BRMSParamTemplate template = (BRMSParamTemplate) result.get(0);
                        ruleTemplate = template.getRule();
index 2cc2117..7b50397 100644 (file)
@@ -21,6 +21,9 @@
 package org.onap.policy.pap.xacml.rest.daoimpl;
 
 import java.util.List;
+import java.util.Map;
+
+import javax.script.SimpleBindings;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -228,24 +231,29 @@ public class CommonClassDaoImpl implements CommonClassDao{
                return data;
        }
 
-
+       
        @SuppressWarnings("unchecked")
        @Override
-       public List<Object> getDataByQuery(String query) {
+       public List<Object> getDataByQuery(String query, SimpleBindings params) {
                Session session = sessionFactory.openSession();
                Transaction tx = session.beginTransaction();
                List<Object> data = null;
                try {
                        Query hbquery = session.createQuery(query);
+                       for (Map.Entry<String, Object> 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;
index c486f53..4d0fd40 100644 (file)
@@ -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.
@@ -23,6 +23,7 @@ package org.onap.policy.rest.dao;
 import java.util.List;
 
 import org.onap.policy.rest.jpa.PolicyRoles;
+import javax.script.SimpleBindings;
 
 public interface CommonClassDao {
 
@@ -32,26 +33,26 @@ public interface CommonClassDao {
        List<String> getDataByColumn(@SuppressWarnings("rawtypes") Class className, String columnName);
        List<Object> checkDuplicateEntry(String value, String columnName,  @SuppressWarnings("rawtypes") Class className);
        Object getEntityItem(@SuppressWarnings("rawtypes") Class className, String columnName, String key);
-       List<Object>  getDataByQuery(String query);
+       List<Object>  getDataByQuery(String query, SimpleBindings params);
        List<Object>  getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List<String> data);
        void save(Object entity);
        void delete(Object entity);
        void update(Object entity);
        void updateQuery(String query);
-       
+
        //Group Policy Scope
        List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue);
-       
-       
+
+
        //Roles
        List<PolicyRoles> getUserRoles();
-       
-       
+
+
        //ClosedLoops
        void updateClAlarms(String clName, String alarms);
        void updateClYaml(String clName, String yaml);
        void deleteAll();
-        
-       
-       
+
+
+
 }
index e65b317..1c1c3f4 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.rest.jpa;
  */
 import java.io.Serializable;
 import java.util.Date;
+import java.util.Objects;
 
 import javax.persistence.Column;
 import javax.persistence.Entity;
@@ -41,6 +42,7 @@ import javax.persistence.Version;
  * The Entity class to persist a policy object Action Body
  */
 
+
 import com.fasterxml.jackson.annotation.JsonBackReference;
 
 @Entity
@@ -192,4 +194,35 @@ public class ActionBodyEntity implements Serializable {
        public void setDeleted(boolean deleted) {
                this.deleted = deleted;
        }
+       
+       @Override
+       public int hashCode() {
+       return Objects.hash(actionBodyId, actionBodyName, version, actionBody,
+                       createdBy, createdDate, modifiedBy, modifiedDate, deleted);
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               if(obj == null){
+                       return false;
+               }
+               if(obj == this){
+                       return true;
+               }
+               if(!(obj instanceof ActionBodyEntity)){
+                       return false;
+               }
+
+               return (
+                               actionBodyId == ((ActionBodyEntity) obj).actionBodyId &&
+                               actionBodyName.equals(((ActionBodyEntity) obj).actionBodyName) && 
+                               version == ((ActionBodyEntity) obj).version && 
+                               actionBody.equals(((ActionBodyEntity) obj).actionBody) && 
+                               createdBy.equals(((ActionBodyEntity) obj).createdBy) && 
+                               createdDate.equals(((ActionBodyEntity) obj).createdDate) && 
+                               modifiedBy.equals(((ActionBodyEntity) obj).modifiedBy) &&
+                               modifiedDate.equals(((ActionBodyEntity) obj).modifiedDate) &&
+                               deleted == ((ActionBodyEntity) obj).deleted
+                               );
+       }
 }
index e755d6f..3386e9a 100644 (file)
@@ -23,6 +23,7 @@ package org.onap.policy.rest.jpa;
  */
 import java.io.Serializable;
 import java.util.Date;
+import java.util.Objects;
 
 import javax.persistence.Column;
 import javax.persistence.Entity;
@@ -42,6 +43,7 @@ import javax.persistence.Version;
  * The Entity class to persist a policy object configuration data
  */
 
+
 import com.fasterxml.jackson.annotation.JsonBackReference;
 
 @Entity
@@ -221,4 +223,37 @@ public class ConfigurationDataEntity implements Serializable {
        public void setDeleted(boolean deleted) {
                this.deleted = deleted;
        }
+       
+       @Override
+       public int hashCode() {
+       return Objects.hash(configurationDataId, configurationName,     version, configType,
+                       configBody, createdBy, createdDate, description, modifiedBy, modifiedDate, deleted);
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               if(obj == null){
+                       return false;
+               }
+               if(obj == this){
+                       return true;
+               }
+               if(!(obj instanceof ConfigurationDataEntity)){
+                       return false;
+               }
+               
+               return (
+                               configurationDataId == ((ConfigurationDataEntity) obj).configurationDataId &&   
+                               configurationName.equals(((ConfigurationDataEntity) obj).configurationName) && 
+                               version == ((ConfigurationDataEntity) obj).version &&
+                               configType.equals(((ConfigurationDataEntity) obj).configType) &&
+                               configBody.equals(((ConfigurationDataEntity) obj).configBody) &&
+                               createdBy.equals(((ConfigurationDataEntity) obj).createdBy) &&
+                               createdDate.equals(((ConfigurationDataEntity) obj).createdDate) &&
+                               description.equals(((ConfigurationDataEntity) obj).description) &&
+                               modifiedBy.equals(((ConfigurationDataEntity) obj).modifiedBy) &&
+                               modifiedDate.equals(((ConfigurationDataEntity) obj).modifiedDate) &&
+                               deleted == ((ConfigurationDataEntity) obj).deleted
+                               );
+       }
 }
index 265d2f6..57daf7e 100644 (file)
@@ -23,6 +23,7 @@ package org.onap.policy.rest.jpa;
  */
 import java.io.Serializable;
 import java.util.Date;
+import java.util.Objects;
 
 import javax.persistence.Column;
 import javax.persistence.Entity;
@@ -288,6 +289,44 @@ public class PolicyEntity implements Serializable {
        public void setDeleted(boolean deleted) {
                this.deleted = deleted;
        }
+       
+       @Override
+       public int hashCode() {
+       return Objects.hash(policyId, policyName, scope, version, policyVersion, policyData, configurationDataEntity, 
+                       actionBodyEntity, createdBy, createdDate, description, modifiedBy, modifiedDate, deleted);
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               if(obj == null){
+                       return false;
+               }
+               if(obj == this){
+                       return true;
+               }
+               if(!(obj instanceof PolicyEntity)){
+                       return false;
+               }
+
+               PolicyEntity p = (PolicyEntity) obj;
+               
+               return (
+                               policyId == p.policyId &&
+                               policyName.equals(p.policyName) &&
+                               scope.equals(p.scope) &&
+                               version == p.version &&
+                               policyVersion == p.policyVersion &&
+                               policyData.equals(p.policyData) &&
+                               ((configurationDataEntity == null && p.configurationDataEntity == null) || configurationDataEntity.equals(p.configurationDataEntity)) &&
+                               ((actionBodyEntity == null && p.actionBodyEntity == null) || actionBodyEntity.equals(p.actionBodyEntity)) &&
+                               createdBy.equals(p.createdBy) &&
+                               createdDate.equals(p.createdDate) &&
+                               description.equals(p.description) &&
+                               modifiedBy.equals(p.modifiedBy) &&
+                               modifiedDate.equals(p.modifiedDate) &&
+                               deleted == p.deleted
+                               );
+       }
 
 
 }
index d098ee5..bc6ad99 100644 (file)
@@ -24,6 +24,7 @@ import java.io.Serializable;
 //import java.sql.Clob;
 import java.sql.Timestamp;
 import java.util.Date;
+import java.util.Objects;
 
 import javax.persistence.Column;
 import javax.persistence.Entity;
@@ -178,6 +179,38 @@ public class PolicyVersion implements Serializable {
        public void setModifiedBy(String modifiedBy) {
                this.modifiedBy = modifiedBy;
        }
+       
+       @Override
+       public int hashCode() {
+       return Objects.hash(id, policyName,     activeVersion, higherVersion, createdDate, 
+                       createdBy, modifiedDate, modifiedBy);
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               if(obj == null){
+                       return false;
+               }
+               if(obj == this){
+                       return true;
+               }
+               if(!(obj instanceof PolicyVersion)){
+                       return false;
+               }
+
+               PolicyVersion p = (PolicyVersion) obj;
+               
+               return (
+                               id == p.id &&
+                               policyName.equals(p.policyName) &&
+                               activeVersion == p.activeVersion &&
+                               higherVersion == p.higherVersion &&
+                               createdDate.equals(p.createdDate) &&
+                               createdBy.equals(p.createdBy) &&
+                               modifiedDate.equals(p.modifiedDate) &&
+                               modifiedBy.equals(p.modifiedBy)
+                               );
+       }
 
 }
        
index 297c1f6..71b3526 100644 (file)
@@ -25,6 +25,7 @@ package org.onap.policy.rest.jpa;
  * */
 
 import java.io.Serializable;
+import java.util.Objects;
 
 import javax.persistence.Column;
 import javax.persistence.Entity;
@@ -77,4 +78,29 @@ public class WatchPolicyNotificationTable implements Serializable{
        public void setLoginIds(String loginIds) {
                this.loginIds = loginIds;
        }
+
+       @Override
+       public int hashCode() {
+               return Objects.hash(id, policyName, loginIds);
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               if(obj == null){
+                       return false;
+               }
+               if(obj == this){
+                       return true;
+               }
+               if(!(obj instanceof WatchPolicyNotificationTable)){
+                       return false;
+               }
+               
+               return(id == ((WatchPolicyNotificationTable)obj).id &&
+               policyName.equals(((WatchPolicyNotificationTable)obj).policyName) && 
+               loginIds.equals(((WatchPolicyNotificationTable)obj).loginIds)
+               );
+       }
+       
+       
 }
index b8ac94b..fe861fe 100644 (file)
                    <artifactId>snakeyaml</artifactId>
                    <version>1.16</version>
                </dependency>
+               <dependency>
+                       <groupId>org.apache.tomcat</groupId>
+                       <artifactId>tomcat-jdbc</artifactId>
+                       <version>8.0.24</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.apache.tomcat</groupId>
+                       <artifactId>tomcat-dbcp</artifactId>
+                       <version>8.5.9</version>
+               </dependency>
        </dependencies>
 </project>
index 6fab5a6..b481714 100644 (file)
@@ -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<Object> 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<Object> 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<Object> 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<Object> 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<Object> 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<Object> 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<Object> 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<Object> scopesList = controller.getDataByQuery(scopeNamequery);
+               List<Object> 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<Object> activePolicies = controller.getDataByQuery(query);
-               List<Object> 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<Object> activePolicies = controller.getDataByQuery(query, params);
+               List<Object> 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<Object> activePolicies = controller.getDataByQuery(query);
-                               List<Object> 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<Object> activePolicies = controller.getDataByQuery(query, pvParams);
+                               List<Object> 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<Object> 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<Object> 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<Object> 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<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
                        if(!oldEntityData.isEmpty()){
                                String groupQuery = "FROM PolicyGroupEntity where (";
+                               SimpleBindings geParams = new SimpleBindings();
                                for(int i=0; i<oldEntityData.size(); i++){
                                        entity = (PolicyEntity) oldEntityData.get(i);
                                        if(i == 0){
-                                               groupQuery = groupQuery +  "policyid ="  + entity.getPolicyId();
+                                               groupQuery = groupQuery +  "policyid = :policyId";
+                                               geParams.put("policyId", entity.getPolicyId());
                                        }else{
-                                               groupQuery = groupQuery +  " or policyid ="  + entity.getPolicyId();
+                                               groupQuery = groupQuery +  " or policyid = :policyId" + i;
+                                               geParams.put("policyId" + i, entity.getPolicyId());
                                        }
                                }
                                groupQuery = groupQuery + ")";
-                               List<Object> groupEntityData = controller.getDataByQuery(groupQuery);
+                               List<Object> 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<Object> 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<Object> 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<Object> policyEntityobjects = controller.getDataByQuery(query);
+                       List<Object> 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<Object> groupobject = controller.getDataByQuery(groupEntityquery);
+                                                       String groupEntityquery = "from PolicyGroupEntity where policyid = :policyId";
+                                                       SimpleBindings pgeParams = new SimpleBindings();
+                                                       pgeParams.put("policyId", policyEntity.getPolicyId());
+                                                       List<Object> 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<Object> 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<Object> 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<Object> groupobject = controller.getDataByQuery(groupEntityquery);
+                                               String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
+                                               SimpleBindings geParams = new SimpleBindings();
+                                               geParams.put("policyEntityId", policyEntity.getPolicyId());
+                                               List<Object> 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<Object> groupobject = controller.getDataByQuery(groupEntityquery);
+                                               String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
+                                               SimpleBindings geParams = new SimpleBindings();
+                                               geParams.put("policyEntityId", policyEntity.getPolicyId());
+                                               List<Object> 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<Object> 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<Object> queryData = controller.getDataByQuery(query, peParams);
                        PolicyEntity entity = (PolicyEntity) queryData.get(0);
                        InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
 
index bf89c01..a4e4762 100644 (file)
@@ -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<Object> watchList = policyNotificationDao.getDataByQuery(query);
+               SimpleBindings params = new SimpleBindings();
+               params.put("policyFileName", policyFileName);
+               List<Object> watchList = policyNotificationDao.getDataByQuery(query, params);
                if(watchList != null && !watchList.isEmpty()){
                        for(Object watch : watchList){
                                WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch;
index 7d601d6..b72993f 100644 (file)
@@ -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<Object> 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<Object> 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<Object> 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<Object> queryData = controller.getDataByQuery(query, policyParams);
                                        PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
                                        File temp = new File(name);
                                        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
index d6d4a2c..aedb943 100644 (file)
@@ -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<Object> pdpStatusData;
        private ArrayList<Object> papStatusData;
        private ArrayList<Object> 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<OnapPDPGroup> 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<Object> data = commonClassDao.getDataByQuery("from PolicyEntity");
+               List<Object> 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<String, String> 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;
        }
-       
+
 }
index 375ee2d..35b9b95 100644 (file)
@@ -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<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
                for (Datatype id : functionMap.keySet()) {
                        List<FunctionDefinition> functionDefinations = functionMap.get(id);
@@ -225,7 +226,7 @@ public class PolicyController extends RestrictedBaseController {
 
        }
 
-       public static  Map<Datatype, List<FunctionDefinition>>  getFunctionDatatypeMap() {                              
+       public static  Map<Datatype, List<FunctionDefinition>>  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<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);    
+               mapID2Function = new  HashMap<>();
+               List<Object> 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<Object> 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<String, Object> 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<Object> 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<Object> getDataByQuery(String query){
-               return commonClassDao.getDataByQuery(query);
+       public List<Object> 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<Object> 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<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
                List<String> 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;
        }
 }
-
index d26781c..bb6f38b 100644 (file)
@@ -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<Object> 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<Object> queryData = controller.getDataByQuery(query, params);
                                        if(!queryData.isEmpty()){
                                                continue;
                                        }
index f3291a7..7312175 100644 (file)
@@ -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<Object> 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<Object> watchList = commonClassDao.getDataByQuery(query, params);
                        if(watchList.isEmpty()){
                                if(finalName.contains("\\\\")){
                                        finalName = finalName.replace("\\\\", File.separator);
index 05bf50f..336c42c 100644 (file)
@@ -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<Object> getDataByQuery(String query) {
+       public List<Object> getDataByQuery(String query, SimpleBindings params) {
                Session session = sessionfactory.openSession();
                Transaction tx = session.beginTransaction();
                List<Object> data = null;
                try {
                        Query hbquery = session.createQuery(query);
+                       for (Map.Entry<String, Object> 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;
index e3de43a..a034c8a 100644 (file)
@@ -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);
index 817a624..382637c 100644 (file)
@@ -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 (file)
index 0000000..78dd20a
--- /dev/null
@@ -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<Object> 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<Object> 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<Object> 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<Object> 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<Object> 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<Object> 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<Object> 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<Object> 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();
+
+       }
+}