2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Modifications copyright (c) 2019 Nokia
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 package org.onap.policy.rest.daoimpl;
23 import static org.junit.Assert.*;
26 import java.util.ArrayList;
27 import java.util.Date;
28 import java.util.List;
29 import java.util.Properties;
31 import javax.script.SimpleBindings;
33 import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
34 import org.h2.tools.Server;
35 import org.hibernate.Query;
36 import org.hibernate.Session;
37 import org.hibernate.SessionFactory;
38 import org.hibernate.Transaction;
39 import org.junit.After;
40 import org.junit.AfterClass;
41 import org.junit.BeforeClass;
42 import org.junit.Test;
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.onap.policy.rest.jpa.OnapName;
46 import org.onap.policy.rest.jpa.PolicyEntity;
47 import org.onap.policy.rest.jpa.PolicyRoles;
48 import org.onap.policy.rest.jpa.PolicyVersion;
49 import org.onap.policy.rest.jpa.SystemLogDB;
50 import org.onap.policy.rest.jpa.UserInfo;
51 import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
52 import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
53 import org.springframework.transaction.annotation.Transactional;
54 import org.springframework.test.annotation.Rollback;
57 public class PolicyValidationDaoImplTest {
59 private static Logger logger = FlexLogger.getLogger(PolicyValidationDaoImplTest.class);
61 static SessionFactory sessionFactory;
63 static PolicyValidationDaoImpl commonClassDao;
66 public static void setupAll() {
68 BasicDataSource dataSource = new BasicDataSource();
69 dataSource.setDriverClassName("org.h2.Driver");
70 // In-memory DB for testing
71 dataSource.setUrl("jdbc:h2:mem:test");
72 dataSource.setUsername("sa");
73 dataSource.setPassword("");
74 LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
75 sessionBuilder.scanPackages("org.onap.*", "com.*");
77 Properties properties = new Properties();
78 properties.put("hibernate.show_sql", "false");
79 properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
80 properties.put("hibernate.hbm2ddl.auto", "drop");
81 properties.put("hibernate.hbm2ddl.auto", "create");
83 sessionBuilder.addProperties(properties);
84 sessionFactory = sessionBuilder.buildSessionFactory();
86 // Set up dao with SessionFactory
87 commonClassDao = new PolicyValidationDaoImpl();
88 PolicyValidationDaoImpl.setSessionfactory(sessionFactory);
89 //PolicyController.setLogTableLimit("1");
90 //HibernateSession.setSession(sessionFactory);
91 SystemLogDB data1 = new SystemLogDB();
92 data1.setDate(new Date());
93 data1.setLogtype("INFO");
94 data1.setRemote("Test");
95 data1.setSystem("Test");
96 data1.setType("Test");
97 SystemLogDB data2 = new SystemLogDB();
98 data2.setDate(new Date());
99 data2.setLogtype("error");
100 data2.setRemote("Test");
101 data2.setSystem("Test");
102 data2.setType("Test");
103 //HibernateSession.getSession().save(data1);
104 //HibernateSession.getSession().save(data2);
106 // Create TCP server for troubleshooting
107 server = Server.createTcpServer("-tcpAllowOthers").start();
108 System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
111 System.err.println(e);
117 public static void deleteDB() {
118 sessionFactory.close();
123 public void tearDown() {
130 public void testDB(){
133 UserInfo userinfo = new UserInfo();
134 userinfo.setUserLoginId("Test");
135 userinfo.setUserName("Test");
136 commonClassDao.save(userinfo);
137 OnapName onapName = new OnapName();
138 onapName.setOnapName("Test");
139 onapName.setUserCreatedBy(userinfo);
140 onapName.setUserModifiedBy(userinfo);
141 onapName.setModifiedDate(new Date());
142 commonClassDao.save(onapName);
145 List<Object> list = commonClassDao.getData(OnapName.class);
146 assertTrue(list.size() == 1);
147 logger.debug(list.size());
148 logger.debug(list.get(0));
150 logger.debug("Exception Occured"+e);
158 public void testUser(){
161 UserInfo userinfo = new UserInfo();
162 String loginId_userName = "Test";
163 userinfo.setUserLoginId(loginId_userName);
164 userinfo.setUserName(loginId_userName);
165 commonClassDao.save(userinfo);
168 List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
170 assertEquals(1, dataCur.size());
171 UserInfo cur = (UserInfo) dataCur.get(0);
172 assertEquals(loginId_userName, cur.getUserLoginId());
173 assertEquals(loginId_userName, cur.getUserName());
175 assertFalse(dataCur.isEmpty());
178 logger.debug("Exception Occured"+e);
186 public void getDataByQuery_DashboardController(){
189 PolicyEntity pe = new PolicyEntity();
190 String name = "TestPolicy";
191 pe.setPolicyName(name);
192 pe.setPolicyData("dummyData");
194 pe.setScope("dummyScope");
195 pe.setDescription("descr");
196 pe.setDeleted(false);
197 pe.setCreatedBy("Test");
198 commonClassDao.save(pe);
200 List<Object> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
202 assertTrue(1 == dataCur.size());
203 assertTrue( dataCur.get(0) instanceof PolicyEntity);
204 assertEquals( name, ((PolicyEntity)dataCur.get(0)).getPolicyName());
205 assertEquals( pe, ((PolicyEntity)dataCur.get(0)));
209 logger.debug("Exception Occured"+e);
217 public void getDataByQuery_AutoPushController(){
220 PolicyVersion pv = new PolicyVersion();
221 pv.setActiveVersion(2);
222 pv.setPolicyName("myPname");
224 pv.setCreatedBy("Test");
225 pv.setModifiedBy("Test");
227 PolicyVersion pv2 = new PolicyVersion();
228 pv2.setActiveVersion(1);
229 pv2.setPolicyName("test");
231 pv2.setCreatedBy("Test");
232 pv2.setModifiedBy("Test");
234 commonClassDao.save(pv);
235 commonClassDao.save(pv2);
239 String query = "From PolicyVersion where policy_name like :scope and id > 0";
240 SimpleBindings params = new SimpleBindings();
241 params.put("scope", scope);
242 List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
245 assertTrue(1 == dataCur.size());
246 assertEquals(pv, (PolicyVersion) dataCur.get(0));
249 logger.debug("Exception Occured"+e);
257 public void getDataByQuery_PolicyNotificationMail(){
260 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
261 String policyFileName = "banana";
262 watch.setLoginIds("Test");
263 watch.setPolicyName("bananaWatch");
264 commonClassDao.save(watch);
266 if(policyFileName.contains("/")){
267 policyFileName = policyFileName.substring(0, policyFileName.indexOf("/"));
268 policyFileName = policyFileName.replace("/", File.separator);
270 if(policyFileName.contains("\\")){
271 policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\"));
272 policyFileName = policyFileName.replace("\\", "\\\\");
276 // Current Implementation
277 policyFileName += "%";
278 String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
279 SimpleBindings params = new SimpleBindings();
280 params.put("policyFileName", policyFileName);
281 List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
284 assertTrue(dataCur.size() == 1);
285 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
286 assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0));
289 logger.debug("Exception Occured"+e);
298 public void getDataByQuery_PolicyController(){
301 PolicyEntity pe = new PolicyEntity();
302 String name = "actionDummy";
303 pe.setPolicyName(name);
304 pe.setPolicyData("dummyData");
306 pe.setScope("dummyScope");
307 pe.setDescription("descr");
308 pe.setDeleted(false);
309 pe.setCreatedBy("Test");
310 commonClassDao.save(pe);
312 String dbCheckName = "dummyScope:action";
313 String[] splitDBCheckName = dbCheckName.split(":");
316 // Current Implementation
317 String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
318 SimpleBindings params = new SimpleBindings();
319 params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
320 params.put("splitDBCheckName0", splitDBCheckName[0]);
321 List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
324 assertTrue(dataCur.size() == 1);
325 assertTrue(dataCur.get(0) instanceof PolicyEntity);
326 assertEquals(pe, (PolicyEntity) dataCur.get(0));
329 logger.debug("Exception Occured"+e);
337 public void getDataByQuery_PolicyNotificationController(){
340 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
341 String finalName = "banana"; // Policy File Name
342 String userId = "Test";
343 watch.setLoginIds(userId);
344 watch.setPolicyName(finalName);
345 commonClassDao.save(watch);
348 // Current Implementation
349 String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
350 SimpleBindings params = new SimpleBindings();
351 params.put("finalName", finalName);
352 params.put("userId", userId);
353 List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
356 assertTrue(dataCur.size() == 1);
357 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
358 assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0) );
361 logger.debug("Exception Occured"+e);
367 /* Test for SQL Injection Protection
373 public void getDataByQuery_PolicyNotificationController_Injection(){
376 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
377 String userId = "Test";
378 watch.setLoginIds(userId);
379 watch.setPolicyName("banana");
380 commonClassDao.save(watch);
382 WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
383 watch2.setLoginIds(userId);
384 watch2.setPolicyName("banana2");
385 commonClassDao.save(watch2);
387 // SQL Injection attempt
388 String finalName = "banana' OR '1'='1";
391 // Current Implementation
392 String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
393 SimpleBindings params = new SimpleBindings();
394 params.put("finalName", finalName);
395 params.put("userId", userId);
396 List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
399 assertTrue(dataCur.size() <= 1);
401 if(dataCur.size() >= 1){
402 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
403 assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
404 assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
407 logger.debug("Exception Occured"+e);
413 public void testCommonClassDaoImplMethods(){
415 UserInfo userInfo = new UserInfo();
416 userInfo.setUserLoginId("TestID");
417 userInfo.setUserName("Test");
418 commonClassDao.save(userInfo);
419 List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
420 assertTrue(data.size() == 1);
421 UserInfo userInfoUpdate = (UserInfo) data.get(0);
422 userInfoUpdate.setUserName("Test1");
423 commonClassDao.update(userInfoUpdate);
424 List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
425 assertTrue(data1.size() == 1);
426 UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1");
427 assertTrue("TestID".equals(data2.getUserLoginId()));
428 List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
429 assertTrue(data3.size() == 1);
430 PolicyRoles roles = new PolicyRoles();
431 roles.setRole("admin");
432 roles.setLoginId(userInfo);
433 roles.setScope("test");
434 commonClassDao.save(roles);
435 List<PolicyRoles> roles1 = commonClassDao.getUserRoles();
436 assertTrue(roles1.size() == 1);
437 List<String> multipleData = new ArrayList<>();
438 multipleData.add("TestID:Test1");
439 List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName", multipleData);
440 assertTrue(data4.size() == 1);
441 commonClassDao.delete(data2);
443 logger.debug("Exception Occured"+e);
449 private void truncateAllTables() {
450 Session session = sessionFactory.openSession();
451 Transaction transaction = session.beginTransaction();
452 sessionFactory.getAllClassMetadata().forEach((tableName, x) -> {
453 Query query = session.createQuery("DELETE FROM " + tableName);
454 query.executeUpdate();
456 transaction.commit();