2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017, 2019 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.Session;
44 import org.hibernate.SessionFactory;
45 import org.hibernate.Transaction;
46 import org.junit.After;
47 import org.junit.Before;
48 import org.junit.Test;
49 import org.mockito.Mockito;
50 import org.onap.policy.common.logging.flexlogger.FlexLogger;
51 import org.onap.policy.common.logging.flexlogger.Logger;
52 import org.onap.policy.conf.HibernateSession;
53 import org.onap.policy.controller.PolicyController;
54 import org.onap.policy.rest.jpa.OnapName;
55 import org.onap.policy.rest.jpa.PolicyEntity;
56 import org.onap.policy.rest.jpa.PolicyRoles;
57 import org.onap.policy.rest.jpa.PolicyVersion;
58 import org.onap.policy.rest.jpa.SystemLogDb;
59 import org.onap.policy.rest.jpa.UserInfo;
60 import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
61 import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
62 import org.springframework.test.annotation.Rollback;
63 import org.springframework.transaction.annotation.Transactional;
65 public class CommonClassDaoImplTest {
67 private static Logger logger = FlexLogger.getLogger(CommonClassDaoImplTest.class);
69 SessionFactory sessionFactory;
71 CommonClassDaoImpl commonClassDao;
76 * @throws Exception Exception
79 public void setUp() throws Exception {
81 BasicDataSource dataSource = new BasicDataSource();
82 dataSource.setDriverClassName("org.h2.Driver");
83 // In-memory DB for testing
84 dataSource.setUrl("jdbc:h2:mem:test");
85 dataSource.setUsername("sa");
86 dataSource.setPassword("");
87 LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
88 sessionBuilder.scanPackages("org.onap.*", "com.*");
90 Properties properties = new Properties();
91 properties.put("hibernate.show_sql", "false");
92 properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
93 properties.put("hibernate.hbm2ddl.auto", "drop");
94 properties.put("hibernate.hbm2ddl.auto", "create");
96 sessionBuilder.addProperties(properties);
97 sessionFactory = sessionBuilder.buildSessionFactory();
99 // Set up dao with SessionFactory
100 commonClassDao = new CommonClassDaoImpl();
101 CommonClassDaoImpl.setSessionfactory(sessionFactory);
102 PolicyController.setLogTableLimit("1");
103 HibernateSession.setSession(sessionFactory);
104 SystemLogDb data1 = new SystemLogDb();
105 data1.setDate(new Date());
106 data1.setLogtype("INFO");
107 data1.setRemote("Test");
108 data1.setSystem("Test");
109 data1.setType("Test");
110 SystemLogDb data2 = new SystemLogDb();
111 data2.setDate(new Date());
112 data2.setLogtype("error");
113 data2.setRemote("Test");
114 data2.setSystem("Test");
115 data2.setType("Test");
116 HibernateSession.getSession().save(data1);
117 HibernateSession.getSession().save(data2);
118 // Create TCP server for troubleshooting
119 server = Server.createTcpServer("-tcpAllowOthers").start();
120 System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
122 } catch (Exception e) {
123 System.err.println(e);
131 public void testDB() {
134 UserInfo userinfo = new UserInfo();
135 userinfo.setUserLoginId("Test");
136 userinfo.setUserName("Test");
137 commonClassDao.save(userinfo);
138 OnapName onapName = new OnapName();
139 onapName.setName("Test");
140 onapName.setUserCreatedBy(userinfo);
141 onapName.setUserModifiedBy(userinfo);
142 onapName.setModifiedDate(new Date());
143 commonClassDao.save(onapName);
145 List<?> list = commonClassDao.getData(OnapName.class);
146 assertTrue(list.size() == 1);
147 logger.debug(list.size());
148 logger.debug(list.get(0));
149 } catch (Exception e) {
150 logger.debug("Exception Occured" + e);
158 public void testUser() {
161 UserInfo userinfo = new UserInfo();
162 String loginIdUserName = "Test";
163 userinfo.setUserLoginId(loginIdUserName);
164 userinfo.setUserName(loginIdUserName);
165 commonClassDao.save(userinfo);
167 List<?> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
169 assertEquals(1, dataCur.size());
170 UserInfo cur = (UserInfo) dataCur.get(0);
171 assertEquals(loginIdUserName, cur.getUserLoginId());
172 assertEquals(loginIdUserName, cur.getUserName());
174 assertFalse(dataCur.isEmpty());
176 } catch (Exception e) {
177 logger.debug("Exception Occured" + e);
185 public void getDataByQuery_DashboardController() {
188 PolicyEntity pe = new PolicyEntity();
189 String name = "TestPolicy";
190 pe.setPolicyName(name);
191 pe.setPolicyData("dummyData");
193 pe.setScope("dummyScope");
194 pe.setDescription("descr");
195 pe.setDeleted(false);
196 pe.setCreatedBy("Test");
197 commonClassDao.save(pe);
199 List<?> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
201 assertTrue(1 == dataCur.size());
202 assertTrue(dataCur.get(0) instanceof PolicyEntity);
203 assertEquals(name, ((PolicyEntity) dataCur.get(0)).getPolicyName());
204 assertEquals(pe, (dataCur.get(0)));
206 } catch (Exception e) {
207 logger.debug("Exception Occured" + e);
215 public void getDataByQuery_AutoPushController() {
218 PolicyVersion pv = new PolicyVersion();
219 pv.setActiveVersion(2);
220 pv.setPolicyName("myPname");
222 pv.setCreatedBy("Test");
223 pv.setModifiedBy("Test");
225 PolicyVersion pv2 = new PolicyVersion();
226 pv2.setActiveVersion(1);
227 pv2.setPolicyName("test");
229 pv2.setCreatedBy("Test");
230 pv2.setModifiedBy("Test");
232 commonClassDao.save(pv);
233 commonClassDao.save(pv2);
237 String query = "From PolicyVersion where policy_name like :scope and id > 0";
238 SimpleBindings params = new SimpleBindings();
239 params.put("scope", scope);
240 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
242 assertTrue(1 == dataCur.size());
243 assertEquals(pv, dataCur.get(0));
245 } catch (Exception e) {
246 logger.debug("Exception Occured" + e);
254 public void getDataByQuery_PolicyNotificationMail() {
257 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
258 watch.setLoginIds("Test");
259 watch.setPolicyName("bananaWatch");
260 commonClassDao.save(watch);
262 String policyFileName = "banana";
263 if (policyFileName.contains("/")) {
264 policyFileName = policyFileName.substring(0, policyFileName.indexOf("/"));
265 policyFileName = policyFileName.replace("/", File.separator);
267 if (policyFileName.contains("\\")) {
268 policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\"));
269 policyFileName = policyFileName.replace("\\", "\\\\");
272 // Current Implementation
273 policyFileName += "%";
274 String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
275 SimpleBindings params = new SimpleBindings();
276 params.put("policyFileName", policyFileName);
277 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
280 assertTrue(dataCur.size() == 1);
281 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
282 assertEquals(watch, dataCur.get(0));
284 } catch (Exception e) {
285 logger.debug("Exception Occured" + e);
293 public void getDataByQuery_PolicyController() {
296 PolicyEntity pe = new PolicyEntity();
297 String name = "actionDummy";
298 pe.setPolicyName(name);
299 pe.setPolicyData("dummyData");
301 pe.setScope("dummyScope");
302 pe.setDescription("descr");
303 pe.setDeleted(false);
304 pe.setCreatedBy("Test");
305 commonClassDao.save(pe);
307 String dbCheckName = "dummyScope:action";
309 // Current Implementation
310 String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
311 SimpleBindings params = new SimpleBindings();
312 String[] splitDbCheckName = dbCheckName.split(":");
313 params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
314 params.put("splitDBCheckName0", splitDbCheckName[0]);
315 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
318 assertTrue(dataCur.size() == 1);
319 assertTrue(dataCur.get(0) instanceof PolicyEntity);
320 assertEquals(pe, dataCur.get(0));
322 } catch (Exception e) {
323 logger.debug("Exception Occured" + e);
331 public void getDataByQuery_PolicyNotificationController() {
334 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
335 String finalName = "banana"; // Policy File Name
336 String userId = "Test";
337 watch.setLoginIds(userId);
338 watch.setPolicyName(finalName);
339 commonClassDao.save(watch);
341 // Current Implementation
342 String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
343 SimpleBindings params = new SimpleBindings();
344 params.put("finalName", finalName);
345 params.put("userId", userId);
346 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
349 assertTrue(dataCur.size() == 1);
350 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
351 assertEquals(watch, dataCur.get(0));
353 } catch (Exception e) {
354 logger.debug("Exception Occured" + e);
360 * Test for SQL Injection Protection
366 public void getDataByQuery_PolicyNotificationController_Injection() {
369 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
370 String userId = "Test";
371 watch.setLoginIds(userId);
372 watch.setPolicyName("banana");
373 commonClassDao.save(watch);
375 WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
376 watch2.setLoginIds(userId);
377 watch2.setPolicyName("banana2");
378 commonClassDao.save(watch2);
380 // SQL Injection attempt
381 String finalName = "banana' OR '1'='1";
383 // Current Implementation
384 String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
385 SimpleBindings params = new SimpleBindings();
386 params.put("finalName", finalName);
387 params.put("userId", userId);
388 List<?> dataCur = commonClassDao.getDataByQuery(query, params);
391 assertTrue(dataCur.size() <= 1);
393 if (dataCur.size() >= 1) {
394 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
395 assertFalse(watch.equals(dataCur.get(0)));
396 assertFalse(watch.equals(dataCur.get(0)));
398 } catch (Exception e) {
399 logger.debug("Exception Occured" + e);
405 public void testCommonClassDaoImplMethods() {
407 UserInfo userInfo = new UserInfo();
408 userInfo.setUserLoginId("TestID");
409 userInfo.setUserName("Test");
410 commonClassDao.save(userInfo);
411 List<?> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
412 assertTrue(data.size() == 1);
413 UserInfo userInfoUpdate = (UserInfo) data.get(0);
414 userInfoUpdate.setUserName("Test1");
415 commonClassDao.update(userInfoUpdate);
416 List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
417 assertTrue(data1.size() == 1);
419 (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1");
420 assertTrue("TestID".equals(data2.getUserLoginId()));
421 List<?> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
422 assertTrue(data3.size() == 1);
423 PolicyRoles roles = new PolicyRoles();
424 roles.setRole("admin");
425 roles.setLoginId(userInfo);
426 roles.setScope("test");
427 commonClassDao.save(roles);
428 List<PolicyRoles> roles1 = commonClassDao.getUserRoles();
429 assertTrue(roles1.size() == 1);
430 List<String> multipleData = new ArrayList<>();
431 multipleData.add("TestID:Test1");
432 List<?> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName",
434 assertTrue(data4.size() == 1);
435 commonClassDao.delete(data2);
436 } catch (Exception e) {
437 logger.debug("Exception Occured" + e);
443 public final void testGetLoggingData() {
444 SystemLogDbDaoImpl system = new SystemLogDbDaoImpl();
445 PolicyController.setjUnit(true);
447 assertTrue(system.getLoggingData() != null);
448 } catch (Exception e) {
454 public final void testGetSystemAlertData() {
455 SystemLogDbDaoImpl system = new SystemLogDbDaoImpl();
456 PolicyController.setjUnit(true);
458 assertTrue(system.getSystemAlertData() != null);
459 } catch (Exception e) {
464 @SuppressWarnings("unchecked")
466 public void testExceptions() {
467 SessionFactory sfMock = Mockito.mock(SessionFactory.class);
468 Session mockSession = Mockito.mock(Session.class);
469 Criteria crMock = Mockito.mock(Criteria.class);
470 Transaction mockTransaction = Mockito.mock(Transaction.class);
472 CommonClassDaoImpl.setSessionfactory(sfMock);
474 when(sfMock.openSession()).thenReturn(mockSession);
475 when(mockSession.createCriteria(OnapName.class)).thenReturn(crMock);
477 when(crMock.list()).thenThrow(Exception.class);
478 when(mockSession.close()).thenThrow(Exception.class);
480 when(mockSession.beginTransaction()).thenReturn(mockTransaction);
481 doThrow(Exception.class).when(mockTransaction).commit();
483 List<?> dataList = commonClassDao.getData(OnapName.class);
484 assertNull(dataList);
486 List<?> dataByIdList = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
487 assertNull(dataByIdList);
489 commonClassDao.save(null);
490 commonClassDao.delete(null);
491 commonClassDao.update(null);
493 List<?> dupEntryList =
494 commonClassDao.checkDuplicateEntry("TestID:Test", "userLoginId:userName", UserInfo.class);
495 assertNull(dupEntryList);
497 List<PolicyRoles> userRoles = commonClassDao.getUserRoles();
498 assertNull(userRoles);
500 Object entityItem = commonClassDao.getEntityItem(UserInfo.class, "testColName", "testKey");
501 assertNull(entityItem);
503 commonClassDao.updateQuery("testQueryString");
505 List<String> dataByColumn = commonClassDao.getDataByColumn(UserInfo.class, "testColName");
506 assertNull(dataByColumn);
508 List<?> entityData = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "", null);
509 assertNull(entityData);
513 public void testCheckExistingGroupListforUpdate() {
514 Object retObj = commonClassDao.checkExistingGroupListforUpdate("testString1", "testString2");
515 assertNotNull(retObj);
516 assertTrue(retObj instanceof List);
517 List<?> retList = (List<?>) retObj;
518 assertTrue(retList.isEmpty());
522 public void testEmptyMethods() {
523 commonClassDao.deleteAll();
524 commonClassDao.updateClAlarms("TestString1", "TestString2");
525 commonClassDao.updateClYaml("TestString1", "TestString2");
529 public void deleteDB() {
530 sessionFactory.close();