Update css file name in conf.py
[policy/engine.git] / POLICY-SDK-APP / src / test / java / org / onap / policy / daoImp / CommonClassDaoImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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=========================================================
21  */
22
23 package org.onap.policy.daoImp;
24
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;
33
34 import java.io.File;
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;
65
66 public class CommonClassDaoImplTest {
67
68     private static Logger logger = FlexLogger.getLogger(CommonClassDaoImplTest.class);
69
70     SessionFactory sessionFactory;
71     Server server;
72     CommonClassDaoImpl commonClassDao;
73
74     /**
75      * setUp.
76      *
77      * @throws Exception Exception
78      */
79     @Before
80     public void setUp() throws Exception {
81         try {
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.*");
90
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");
96
97             sessionBuilder.addProperties(properties);
98             sessionFactory = sessionBuilder.buildSessionFactory();
99
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");
122
123         } catch (Exception e) {
124             System.err.println(e);
125             fail();
126         }
127     }
128
129     @Test
130     @Transactional
131     @Rollback(true)
132     public void testDB() {
133         try {
134             // Add data
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);
145
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);
152             fail();
153         }
154     }
155
156     @Test
157     @Transactional
158     @Rollback(true)
159     public void testUser() {
160         try {
161             // Add data
162             UserInfo userinfo = new UserInfo();
163             String loginIdUserName = "Test";
164             userinfo.setUserLoginId(loginIdUserName);
165             userinfo.setUserName(loginIdUserName);
166             commonClassDao.save(userinfo);
167
168             List<?> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
169
170             assertEquals(1, dataCur.size());
171             UserInfo cur = (UserInfo) dataCur.get(0);
172             assertEquals(loginIdUserName, cur.getUserLoginId());
173             assertEquals(loginIdUserName, cur.getUserName());
174
175             assertFalse(dataCur.isEmpty());
176
177         } catch (Exception e) {
178             logger.debug("Exception Occured" + e);
179             fail();
180         }
181     }
182
183     @Test
184     @Transactional
185     @Rollback(true)
186     public void getDataByQuery_DashboardController() {
187         try {
188             // Add data
189             PolicyEntity pe = new PolicyEntity();
190             String name = "TestPolicy";
191             pe.setPolicyName(name);
192             pe.setPolicyData("dummyData");
193             pe.prePersist();
194             pe.setScope("dummyScope");
195             pe.setDescription("descr");
196             pe.setDeleted(false);
197             pe.setCreatedBy("Test");
198             commonClassDao.save(pe);
199
200             List<?> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
201
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)));
206
207         } catch (Exception e) {
208             logger.debug("Exception Occured" + e);
209             fail();
210         }
211     }
212
213     @Test
214     @Transactional
215     @Rollback(true)
216     public void getDataByQuery_AutoPushController() {
217         try {
218             // Add data
219             PolicyVersion pv = new PolicyVersion();
220             pv.setActiveVersion(2);
221             pv.setPolicyName("myPname");
222             pv.prePersist();
223             pv.setCreatedBy("Test");
224             pv.setModifiedBy("Test");
225
226             PolicyVersion pv2 = new PolicyVersion();
227             pv2.setActiveVersion(1);
228             pv2.setPolicyName("test");
229             pv2.prePersist();
230             pv2.setCreatedBy("Test");
231             pv2.setModifiedBy("Test");
232
233             commonClassDao.save(pv);
234             commonClassDao.save(pv2);
235
236             String scope = "my";
237             scope += "%";
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);
242
243             assertTrue(1 == dataCur.size());
244             assertEquals(pv, dataCur.get(0));
245
246         } catch (Exception e) {
247             logger.debug("Exception Occured" + e);
248             fail();
249         }
250     }
251
252     @Test
253     @Transactional
254     @Rollback(true)
255     public void getDataByQuery_PolicyNotificationMail() {
256         try {
257             // Add data
258             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
259             watch.setLoginIds("Test");
260             watch.setPolicyName("bananaWatch");
261             commonClassDao.save(watch);
262
263             String policyFileName = "banana";
264             if (policyFileName.contains("/")) {
265                 policyFileName = policyFileName.substring(0, policyFileName.indexOf("/"));
266                 policyFileName = policyFileName.replace("/", File.separator);
267             }
268             if (policyFileName.contains("\\")) {
269                 policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\"));
270                 policyFileName = policyFileName.replace("\\", "\\\\");
271             }
272
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);
279
280             // Assertions
281             assertTrue(dataCur.size() == 1);
282             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
283             assertEquals(watch, dataCur.get(0));
284
285         } catch (Exception e) {
286             logger.debug("Exception Occured" + e);
287             fail();
288         }
289     }
290
291     @Test
292     @Transactional
293     @Rollback(true)
294     public void getDataByQuery_PolicyController() {
295         try {
296             // Add data
297             PolicyEntity pe = new PolicyEntity();
298             String name = "actionDummy";
299             pe.setPolicyName(name);
300             pe.setPolicyData("dummyData");
301             pe.prePersist();
302             pe.setScope("dummyScope");
303             pe.setDescription("descr");
304             pe.setDeleted(false);
305             pe.setCreatedBy("Test");
306             commonClassDao.save(pe);
307
308             String dbCheckName = "dummyScope:action";
309
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);
317
318             // Assertions
319             assertTrue(dataCur.size() == 1);
320             assertTrue(dataCur.get(0) instanceof PolicyEntity);
321             assertEquals(pe, dataCur.get(0));
322
323         } catch (Exception e) {
324             logger.debug("Exception Occured" + e);
325             fail();
326         }
327     }
328
329     @Test
330     @Transactional
331     @Rollback(true)
332     public void getDataByQuery_PolicyNotificationController() {
333         try {
334             // Add data
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);
341
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);
348
349             // Assertions
350             assertTrue(dataCur.size() == 1);
351             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
352             assertEquals(watch, dataCur.get(0));
353
354         } catch (Exception e) {
355             logger.debug("Exception Occured" + e);
356             fail();
357         }
358     }
359
360     /*
361      * Test for SQL Injection Protection
362      */
363
364     @Test
365     @Transactional
366     @Rollback(true)
367     public void getDataByQuery_PolicyNotificationController_Injection() {
368         try {
369             // Add data
370             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
371             String userId = "Test";
372             watch.setLoginIds(userId);
373             watch.setPolicyName("banana");
374             commonClassDao.save(watch);
375
376             WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
377             watch2.setLoginIds(userId);
378             watch2.setPolicyName("banana2");
379             commonClassDao.save(watch2);
380
381             // SQL Injection attempt
382             String finalName = "banana' OR '1'='1";
383
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);
390
391             // Assertions
392             assertTrue(dataCur.size() <= 1);
393
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)));
398             }
399         } catch (Exception e) {
400             logger.debug("Exception Occured" + e);
401             fail();
402         }
403     }
404
405     @Test
406     public void testCommonClassDaoImplMethods() {
407         try {
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);
419             UserInfo data2 =
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",
434                     multipleData);
435             assertTrue(data4.size() == 1);
436             commonClassDao.delete(data2);
437         } catch (Exception e) {
438             logger.debug("Exception Occured" + e);
439             fail();
440         }
441     }
442
443     @Test
444     public final void testGetLoggingData() {
445         SystemLogDbDaoImpl system = new SystemLogDbDaoImpl();
446         PolicyController.setjUnit(true);
447         try {
448             assertTrue(system.getLoggingData() != null);
449         } catch (Exception e) {
450             fail();
451         }
452     }
453
454     @Test
455     public final void testGetSystemAlertData() {
456         SystemLogDbDaoImpl system = new SystemLogDbDaoImpl();
457         PolicyController.setjUnit(true);
458         try {
459             assertTrue(system.getSystemAlertData() != null);
460         } catch (Exception e) {
461             fail();
462         }
463     }
464
465     @SuppressWarnings("unchecked")
466     @Test
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);
472
473         CommonClassDaoImpl.setSessionfactory(sfMock);
474
475         when(sfMock.openSession()).thenReturn(mockSession);
476         when(mockSession.createCriteria(OnapName.class)).thenReturn(crMock);
477
478         when(crMock.list()).thenThrow(HibernateException.class);
479         when(mockSession.close()).thenThrow(HibernateException.class);
480
481         when(mockSession.beginTransaction()).thenReturn(mockTransaction);
482         doThrow(HibernateException.class).when(mockTransaction).commit();
483
484         List<?> dataList = commonClassDao.getData(OnapName.class);
485         assertNull(dataList);
486
487         List<?> dataByIdList = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
488         assertNull(dataByIdList);
489
490         commonClassDao.save(null);
491         commonClassDao.delete(null);
492         commonClassDao.update(null);
493
494         List<?> dupEntryList =
495                 commonClassDao.checkDuplicateEntry("TestID:Test", "userLoginId:userName", UserInfo.class);
496         assertNull(dupEntryList);
497
498         List<PolicyRoles> userRoles = commonClassDao.getUserRoles();
499         assertNull(userRoles);
500
501         Object entityItem = commonClassDao.getEntityItem(UserInfo.class, "testColName", "testKey");
502         assertNull(entityItem);
503
504         commonClassDao.updateQuery("testQueryString");
505
506         List<String> dataByColumn = commonClassDao.getDataByColumn(UserInfo.class, "testColName");
507         assertNull(dataByColumn);
508
509         List<?> entityData = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "", null);
510         assertNull(entityData);
511     }
512
513     @Test
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());
520     }
521
522     @Test
523     public void testEmptyMethods() {
524         commonClassDao.deleteAll();
525         commonClassDao.updateClAlarms("TestString1", "TestString2");
526         commonClassDao.updateClYaml("TestString1", "TestString2");
527     }
528
529     @After
530     public void deleteDB() {
531         sessionFactory.close();
532         server.stop();
533     }
534 }