2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Modifications Copyright (C) 2019 Samsung
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.daoImp;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.assertTrue;
30 import static org.junit.Assert.fail;
31 import static org.mockito.Mockito.doThrow;
32 import static org.mockito.Mockito.when;
35 import java.util.ArrayList;
36 import java.util.Date;
37 import java.util.List;
38 import java.util.Properties;
39 import javax.script.SimpleBindings;
40 import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
41 import org.h2.tools.Server;
42 import org.hibernate.Criteria;
43 import org.hibernate.HibernateException;
44 import org.hibernate.Session;
45 import org.hibernate.SessionFactory;
46 import org.hibernate.Transaction;
47 import org.junit.After;
48 import org.junit.Before;
49 import org.junit.Test;
50 import org.mockito.Mockito;
51 import org.onap.policy.common.logging.flexlogger.FlexLogger;
52 import org.onap.policy.common.logging.flexlogger.Logger;
53 import org.onap.policy.conf.HibernateSession;
54 import org.onap.policy.controller.PolicyController;
55 import org.onap.policy.rest.jpa.OnapName;
56 import org.onap.policy.rest.jpa.PolicyEntity;
57 import org.onap.policy.rest.jpa.PolicyRoles;
58 import org.onap.policy.rest.jpa.PolicyVersion;
59 import org.onap.policy.rest.jpa.SystemLogDb;
60 import org.onap.policy.rest.jpa.UserInfo;
61 import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
62 import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
63 import org.springframework.test.annotation.Rollback;
64 import org.springframework.transaction.annotation.Transactional;
66 public class CommonClassDaoImplTest {
68 private static Logger logger = FlexLogger.getLogger(CommonClassDaoImplTest.class);
70 SessionFactory sessionFactory;
72 CommonClassDaoImpl commonClassDao;
77 * @throws Exception Exception
80 public void setUp() throws Exception {
82 BasicDataSource dataSource = new BasicDataSource();
83 dataSource.setDriverClassName("org.h2.Driver");
84 // In-memory DB for testing
85 dataSource.setUrl("jdbc:h2:mem:test");
86 dataSource.setUsername("sa");
87 dataSource.setPassword("");
88 LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
89 sessionBuilder.scanPackages("org.onap.*", "com.*");
91 Properties properties = new Properties();
92 properties.put("hibernate.show_sql", "false");
93 properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
94 properties.put("hibernate.hbm2ddl.auto", "drop");
95 properties.put("hibernate.hbm2ddl.auto", "create");
97 sessionBuilder.addProperties(properties);
98 sessionFactory = sessionBuilder.buildSessionFactory();
100 // Set up dao with SessionFactory
101 commonClassDao = new CommonClassDaoImpl();
102 CommonClassDaoImpl.setSessionfactory(sessionFactory);
103 PolicyController.setLogTableLimit("1");
104 HibernateSession.setSession(sessionFactory);
105 SystemLogDb data1 = new SystemLogDb();
106 data1.setDate(new Date());
107 data1.setLogtype("INFO");
108 data1.setRemote("Test");
109 data1.setSystem("Test");
110 data1.setType("Test");
111 SystemLogDb data2 = new SystemLogDb();
112 data2.setDate(new Date());
113 data2.setLogtype("error");
114 data2.setRemote("Test");
115 data2.setSystem("Test");
116 data2.setType("Test");
117 HibernateSession.getSession().save(data1);
118 HibernateSession.getSession().save(data2);
119 // Create TCP server for troubleshooting
120 server = Server.createTcpServer("-tcpAllowOthers").start();
121 System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
123 } catch (Exception e) {
124 System.err.println(e);
132 public void testDB() {
135 UserInfo userinfo = new UserInfo();
136 userinfo.setUserLoginId("Test");
137 userinfo.setUserName("Test");
138 commonClassDao.save(userinfo);
139 OnapName onapName = new OnapName();
140 onapName.setName("Test");
141 onapName.setUserCreatedBy(userinfo);
142 onapName.setUserModifiedBy(userinfo);
143 onapName.setModifiedDate(new Date());
144 commonClassDao.save(onapName);
146 List<?> list = commonClassDao.getData(OnapName.class);
147 assertTrue(list.size() == 1);
148 logger.debug(list.size());
149 logger.debug(list.get(0));
150 } catch (Exception e) {
151 logger.debug("Exception Occured" + e);
159 public void testUser() {
162 UserInfo userinfo = new UserInfo();
163 String loginIdUserName = "Test";
164 userinfo.setUserLoginId(loginIdUserName);
165 userinfo.setUserName(loginIdUserName);
166 commonClassDao.save(userinfo);
168 List<?> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
170 assertEquals(1, dataCur.size());
171 UserInfo cur = (UserInfo) dataCur.get(0);
172 assertEquals(loginIdUserName, cur.getUserLoginId());
173 assertEquals(loginIdUserName, cur.getUserName());
175 assertFalse(dataCur.isEmpty());
177 } catch (Exception e) {
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<?> 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, (dataCur.get(0)));
207 } catch (Exception e) {
208 logger.debug("Exception Occured" + e);
216 public void getDataByQuery_AutoPushController() {
219 PolicyVersion pv = new PolicyVersion();
220 pv.setActiveVersion(2);
221 pv.setPolicyName("myPname");
223 pv.setCreatedBy("Test");
224 pv.setModifiedBy("Test");
226 PolicyVersion pv2 = new PolicyVersion();
227 pv2.setActiveVersion(1);
228 pv2.setPolicyName("test");
230 pv2.setCreatedBy("Test");
231 pv2.setModifiedBy("Test");
233 commonClassDao.save(pv);
234 commonClassDao.save(pv2);
238 String query = "From PolicyVersion where policy_name like :scope and id > 0";
239 SimpleBindings params = new SimpleBindings();
240 params.put("scope", scope);
241 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
243 assertTrue(1 == dataCur.size());
244 assertEquals(pv, dataCur.get(0));
246 } catch (Exception e) {
247 logger.debug("Exception Occured" + e);
255 public void getDataByQuery_PolicyNotificationMail() {
258 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
259 watch.setLoginIds("Test");
260 watch.setPolicyName("bananaWatch");
261 commonClassDao.save(watch);
263 String policyFileName = "banana";
264 if (policyFileName.contains("/")) {
265 policyFileName = policyFileName.substring(0, policyFileName.indexOf("/"));
266 policyFileName = policyFileName.replace("/", File.separator);
268 if (policyFileName.contains("\\")) {
269 policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\"));
270 policyFileName = policyFileName.replace("\\", "\\\\");
273 // Current Implementation
274 policyFileName += "%";
275 String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
276 SimpleBindings params = new SimpleBindings();
277 params.put("policyFileName", policyFileName);
278 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
281 assertTrue(dataCur.size() == 1);
282 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
283 assertEquals(watch, dataCur.get(0));
285 } catch (Exception e) {
286 logger.debug("Exception Occured" + e);
294 public void getDataByQuery_PolicyController() {
297 PolicyEntity pe = new PolicyEntity();
298 String name = "actionDummy";
299 pe.setPolicyName(name);
300 pe.setPolicyData("dummyData");
302 pe.setScope("dummyScope");
303 pe.setDescription("descr");
304 pe.setDeleted(false);
305 pe.setCreatedBy("Test");
306 commonClassDao.save(pe);
308 String dbCheckName = "dummyScope:action";
310 // Current Implementation
311 String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
312 SimpleBindings params = new SimpleBindings();
313 String[] splitDbCheckName = dbCheckName.split(":");
314 params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
315 params.put("splitDBCheckName0", splitDbCheckName[0]);
316 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
319 assertTrue(dataCur.size() == 1);
320 assertTrue(dataCur.get(0) instanceof PolicyEntity);
321 assertEquals(pe, dataCur.get(0));
323 } catch (Exception e) {
324 logger.debug("Exception Occured" + e);
332 public void getDataByQuery_PolicyNotificationController() {
335 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
336 String finalName = "banana"; // Policy File Name
337 String userId = "Test";
338 watch.setLoginIds(userId);
339 watch.setPolicyName(finalName);
340 commonClassDao.save(watch);
342 // Current Implementation
343 String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
344 SimpleBindings params = new SimpleBindings();
345 params.put("finalName", finalName);
346 params.put("userId", userId);
347 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
350 assertTrue(dataCur.size() == 1);
351 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
352 assertEquals(watch, dataCur.get(0));
354 } catch (Exception e) {
355 logger.debug("Exception Occured" + e);
361 * Test for SQL Injection Protection
367 public void getDataByQuery_PolicyNotificationController_Injection() {
370 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
371 String userId = "Test";
372 watch.setLoginIds(userId);
373 watch.setPolicyName("banana");
374 commonClassDao.save(watch);
376 WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
377 watch2.setLoginIds(userId);
378 watch2.setPolicyName("banana2");
379 commonClassDao.save(watch2);
381 // SQL Injection attempt
382 String finalName = "banana' OR '1'='1";
384 // Current Implementation
385 String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
386 SimpleBindings params = new SimpleBindings();
387 params.put("finalName", finalName);
388 params.put("userId", userId);
389 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
392 assertTrue(dataCur.size() <= 1);
394 if (dataCur.size() >= 1) {
395 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
396 assertFalse(watch.equals(dataCur.get(0)));
397 assertFalse(watch.equals(dataCur.get(0)));
399 } catch (Exception e) {
400 logger.debug("Exception Occured" + e);
406 public void testCommonClassDaoImplMethods() {
408 UserInfo userInfo = new UserInfo();
409 userInfo.setUserLoginId("TestID");
410 userInfo.setUserName("Test");
411 commonClassDao.save(userInfo);
412 List<?> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
413 assertTrue(data.size() == 1);
414 UserInfo userInfoUpdate = (UserInfo) data.get(0);
415 userInfoUpdate.setUserName("Test1");
416 commonClassDao.update(userInfoUpdate);
417 List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
418 assertTrue(data1.size() == 1);
420 (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1");
421 assertTrue("TestID".equals(data2.getUserLoginId()));
422 List<?> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
423 assertTrue(data3.size() == 1);
424 PolicyRoles roles = new PolicyRoles();
425 roles.setRole("admin");
426 roles.setLoginId(userInfo);
427 roles.setScope("test");
428 commonClassDao.save(roles);
429 List<PolicyRoles> roles1 = commonClassDao.getUserRoles();
430 assertTrue(roles1.size() == 1);
431 List<String> multipleData = new ArrayList<>();
432 multipleData.add("TestID:Test1");
433 List<?> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName",
435 assertTrue(data4.size() == 1);
436 commonClassDao.delete(data2);
437 } catch (Exception e) {
438 logger.debug("Exception Occured" + e);
444 public final void testGetLoggingData() {
445 SystemLogDbDaoImpl system = new SystemLogDbDaoImpl();
446 PolicyController.setjUnit(true);
448 assertTrue(system.getLoggingData() != null);
449 } catch (Exception e) {
455 public final void testGetSystemAlertData() {
456 SystemLogDbDaoImpl system = new SystemLogDbDaoImpl();
457 PolicyController.setjUnit(true);
459 assertTrue(system.getSystemAlertData() != null);
460 } catch (Exception e) {
465 @SuppressWarnings("unchecked")
467 public void testExceptions() throws HibernateException {
468 SessionFactory sfMock = Mockito.mock(SessionFactory.class);
469 Session mockSession = Mockito.mock(Session.class);
470 Criteria crMock = Mockito.mock(Criteria.class);
471 Transaction mockTransaction = Mockito.mock(Transaction.class);
473 CommonClassDaoImpl.setSessionfactory(sfMock);
475 when(sfMock.openSession()).thenReturn(mockSession);
476 when(mockSession.createCriteria(OnapName.class)).thenReturn(crMock);
478 when(crMock.list()).thenThrow(HibernateException.class);
479 when(mockSession.close()).thenThrow(HibernateException.class);
481 when(mockSession.beginTransaction()).thenReturn(mockTransaction);
482 doThrow(HibernateException.class).when(mockTransaction).commit();
484 List<?> dataList = commonClassDao.getData(OnapName.class);
485 assertNull(dataList);
487 List<?> dataByIdList = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
488 assertNull(dataByIdList);
490 commonClassDao.save(null);
491 commonClassDao.delete(null);
492 commonClassDao.update(null);
494 List<?> dupEntryList =
495 commonClassDao.checkDuplicateEntry("TestID:Test", "userLoginId:userName", UserInfo.class);
496 assertNull(dupEntryList);
498 List<PolicyRoles> userRoles = commonClassDao.getUserRoles();
499 assertNull(userRoles);
501 Object entityItem = commonClassDao.getEntityItem(UserInfo.class, "testColName", "testKey");
502 assertNull(entityItem);
504 commonClassDao.updateQuery("testQueryString");
506 List<String> dataByColumn = commonClassDao.getDataByColumn(UserInfo.class, "testColName");
507 assertNull(dataByColumn);
509 List<?> entityData = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "", null);
510 assertNull(entityData);
514 public void testCheckExistingGroupListforUpdate() {
515 Object retObj = commonClassDao.checkExistingGroupListforUpdate("testString1", "testString2");
516 assertNotNull(retObj);
517 assertTrue(retObj instanceof List);
518 List<?> retList = (List<?>) retObj;
519 assertTrue(retList.isEmpty());
523 public void testEmptyMethods() {
524 commonClassDao.deleteAll();
525 commonClassDao.updateClAlarms("TestString1", "TestString2");
526 commonClassDao.updateClYaml("TestString1", "TestString2");
530 public void deleteDB() {
531 sessionFactory.close();