Unit/SONAR/Checkstyle in ONAP-REST
[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 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.assertTrue;
28 import static org.junit.Assert.fail;
29
30 import java.io.File;
31 import java.util.ArrayList;
32 import java.util.Date;
33 import java.util.List;
34 import java.util.Properties;
35
36 import javax.script.SimpleBindings;
37
38 import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
39 import org.h2.tools.Server;
40 import org.hibernate.SessionFactory;
41 import org.junit.After;
42 import org.junit.Before;
43 import org.junit.Test;
44 import org.onap.policy.common.logging.flexlogger.FlexLogger;
45 import org.onap.policy.common.logging.flexlogger.Logger;
46 import org.onap.policy.conf.HibernateSession;
47 import org.onap.policy.controller.PolicyController;
48 import org.onap.policy.rest.jpa.OnapName;
49 import org.onap.policy.rest.jpa.PolicyEntity;
50 import org.onap.policy.rest.jpa.PolicyRoles;
51 import org.onap.policy.rest.jpa.PolicyVersion;
52 import org.onap.policy.rest.jpa.SystemLogDB;
53 import org.onap.policy.rest.jpa.UserInfo;
54 import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
55 import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
56 import org.springframework.test.annotation.Rollback;
57 import org.springframework.transaction.annotation.Transactional;
58
59 public class CommonClassDaoImplTest {
60
61     private static Logger logger = FlexLogger.getLogger(CommonClassDaoImplTest.class);
62
63     SessionFactory sessionFactory;
64     Server server;
65     CommonClassDaoImpl commonClassDao;
66
67     /**
68      * setUp.
69      *
70      * @throws Exception Exception
71      */
72     @Before
73     public void setUp() throws Exception {
74         try {
75             BasicDataSource dataSource = new BasicDataSource();
76             dataSource.setDriverClassName("org.h2.Driver");
77             // In-memory DB for testing
78             dataSource.setUrl("jdbc:h2:mem:test");
79             dataSource.setUsername("sa");
80             dataSource.setPassword("");
81             LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
82             sessionBuilder.scanPackages("org.onap.*", "com.*");
83
84             Properties properties = new Properties();
85             properties.put("hibernate.show_sql", "false");
86             properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
87             properties.put("hibernate.hbm2ddl.auto", "drop");
88             properties.put("hibernate.hbm2ddl.auto", "create");
89
90             sessionBuilder.addProperties(properties);
91             sessionFactory = sessionBuilder.buildSessionFactory();
92
93             // Set up dao with SessionFactory
94             commonClassDao = new CommonClassDaoImpl();
95             CommonClassDaoImpl.setSessionfactory(sessionFactory);
96             PolicyController.setLogTableLimit("1");
97             HibernateSession.setSession(sessionFactory);
98             SystemLogDB data1 = new SystemLogDB();
99             data1.setDate(new Date());
100             data1.setLogtype("INFO");
101             data1.setRemote("Test");
102             data1.setSystem("Test");
103             data1.setType("Test");
104             SystemLogDB data2 = new SystemLogDB();
105             data2.setDate(new Date());
106             data2.setLogtype("error");
107             data2.setRemote("Test");
108             data2.setSystem("Test");
109             data2.setType("Test");
110             HibernateSession.getSession().save(data1);
111             HibernateSession.getSession().save(data2);
112             // Create TCP server for troubleshooting
113             server = Server.createTcpServer("-tcpAllowOthers").start();
114             System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
115
116         } catch (Exception e) {
117             System.err.println(e);
118             fail();
119         }
120     }
121
122     @Test
123     @Transactional
124     @Rollback(true)
125     public void testDB() {
126         try {
127             // Add data
128             UserInfo userinfo = new UserInfo();
129             userinfo.setUserLoginId("Test");
130             userinfo.setUserName("Test");
131             commonClassDao.save(userinfo);
132             OnapName onapName = new OnapName();
133             onapName.setName("Test");
134             onapName.setUserCreatedBy(userinfo);
135             onapName.setUserModifiedBy(userinfo);
136             onapName.setModifiedDate(new Date());
137             commonClassDao.save(onapName);
138
139             List<Object> list = commonClassDao.getData(OnapName.class);
140             assertTrue(list.size() == 1);
141             logger.debug(list.size());
142             logger.debug(list.get(0));
143         } catch (Exception e) {
144             logger.debug("Exception Occured" + e);
145             fail();
146         }
147     }
148
149     @Test
150     @Transactional
151     @Rollback(true)
152     public void testUser() {
153         try {
154             // Add data
155             UserInfo userinfo = new UserInfo();
156             String loginIdUserName = "Test";
157             userinfo.setUserLoginId(loginIdUserName);
158             userinfo.setUserName(loginIdUserName);
159             commonClassDao.save(userinfo);
160
161             List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
162
163             assertEquals(1, dataCur.size());
164             UserInfo cur = (UserInfo) dataCur.get(0);
165             assertEquals(loginIdUserName, cur.getUserLoginId());
166             assertEquals(loginIdUserName, cur.getUserName());
167
168             assertFalse(dataCur.isEmpty());
169
170         } catch (Exception e) {
171             logger.debug("Exception Occured" + e);
172             fail();
173         }
174     }
175
176     @Test
177     @Transactional
178     @Rollback(true)
179     public void getDataByQuery_DashboardController() {
180         try {
181             // Add data
182             PolicyEntity pe = new PolicyEntity();
183             String name = "TestPolicy";
184             pe.setPolicyName(name);
185             pe.setPolicyData("dummyData");
186             pe.prePersist();
187             pe.setScope("dummyScope");
188             pe.setDescription("descr");
189             pe.setDeleted(false);
190             pe.setCreatedBy("Test");
191             commonClassDao.save(pe);
192
193             List<Object> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
194
195             assertTrue(1 == dataCur.size());
196             assertTrue(dataCur.get(0) instanceof PolicyEntity);
197             assertEquals(name, ((PolicyEntity) dataCur.get(0)).getPolicyName());
198             assertEquals(pe, (dataCur.get(0)));
199
200         } catch (Exception e) {
201             logger.debug("Exception Occured" + e);
202             fail();
203         }
204     }
205
206     @Test
207     @Transactional
208     @Rollback(true)
209     public void getDataByQuery_AutoPushController() {
210         try {
211             // Add data
212             PolicyVersion pv = new PolicyVersion();
213             pv.setActiveVersion(2);
214             pv.setPolicyName("myPname");
215             pv.prePersist();
216             pv.setCreatedBy("Test");
217             pv.setModifiedBy("Test");
218
219             PolicyVersion pv2 = new PolicyVersion();
220             pv2.setActiveVersion(1);
221             pv2.setPolicyName("test");
222             pv2.prePersist();
223             pv2.setCreatedBy("Test");
224             pv2.setModifiedBy("Test");
225
226             commonClassDao.save(pv);
227             commonClassDao.save(pv2);
228
229             String scope = "my";
230             scope += "%";
231             String query = "From PolicyVersion where policy_name like :scope and id > 0";
232             SimpleBindings params = new SimpleBindings();
233             params.put("scope", scope);
234             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
235
236             assertTrue(1 == dataCur.size());
237             assertEquals(pv, dataCur.get(0));
238
239         } catch (Exception e) {
240             logger.debug("Exception Occured" + e);
241             fail();
242         }
243     }
244
245     @Test
246     @Transactional
247     @Rollback(true)
248     public void getDataByQuery_PolicyNotificationMail() {
249         try {
250             // Add data
251             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
252             watch.setLoginIds("Test");
253             watch.setPolicyName("bananaWatch");
254             commonClassDao.save(watch);
255
256             String policyFileName = "banana";
257             if (policyFileName.contains("/")) {
258                 policyFileName = policyFileName.substring(0, policyFileName.indexOf("/"));
259                 policyFileName = policyFileName.replace("/", File.separator);
260             }
261             if (policyFileName.contains("\\")) {
262                 policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\"));
263                 policyFileName = policyFileName.replace("\\", "\\\\");
264             }
265
266             // Current Implementation
267             policyFileName += "%";
268             String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
269             SimpleBindings params = new SimpleBindings();
270             params.put("policyFileName", policyFileName);
271             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
272
273             // Assertions
274             assertTrue(dataCur.size() == 1);
275             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
276             assertEquals(watch, dataCur.get(0));
277
278         } catch (Exception e) {
279             logger.debug("Exception Occured" + e);
280             fail();
281         }
282     }
283
284     @Test
285     @Transactional
286     @Rollback(true)
287     public void getDataByQuery_PolicyController() {
288         try {
289             // Add data
290             PolicyEntity pe = new PolicyEntity();
291             String name = "actionDummy";
292             pe.setPolicyName(name);
293             pe.setPolicyData("dummyData");
294             pe.prePersist();
295             pe.setScope("dummyScope");
296             pe.setDescription("descr");
297             pe.setDeleted(false);
298             pe.setCreatedBy("Test");
299             commonClassDao.save(pe);
300
301             String dbCheckName = "dummyScope:action";
302
303             // Current Implementation
304             String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
305             SimpleBindings params = new SimpleBindings();
306             String[] splitDbCheckName = dbCheckName.split(":");
307             params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
308             params.put("splitDBCheckName0", splitDbCheckName[0]);
309             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
310
311             // Assertions
312             assertTrue(dataCur.size() == 1);
313             assertTrue(dataCur.get(0) instanceof PolicyEntity);
314             assertEquals(pe, dataCur.get(0));
315
316         } catch (Exception e) {
317             logger.debug("Exception Occured" + e);
318             fail();
319         }
320     }
321
322     @Test
323     @Transactional
324     @Rollback(true)
325     public void getDataByQuery_PolicyNotificationController() {
326         try {
327             // Add data
328             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
329             String finalName = "banana"; // Policy File Name
330             String userId = "Test";
331             watch.setLoginIds(userId);
332             watch.setPolicyName(finalName);
333             commonClassDao.save(watch);
334
335             // Current Implementation
336             String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
337             SimpleBindings params = new SimpleBindings();
338             params.put("finalName", finalName);
339             params.put("userId", userId);
340             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
341
342             // Assertions
343             assertTrue(dataCur.size() == 1);
344             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
345             assertEquals(watch, dataCur.get(0));
346
347         } catch (Exception e) {
348             logger.debug("Exception Occured" + e);
349             fail();
350         }
351     }
352
353     /*
354      * Test for SQL Injection Protection
355      */
356
357     @Test
358     @Transactional
359     @Rollback(true)
360     public void getDataByQuery_PolicyNotificationController_Injection() {
361         try {
362             // Add data
363             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
364             String userId = "Test";
365             watch.setLoginIds(userId);
366             watch.setPolicyName("banana");
367             commonClassDao.save(watch);
368
369             WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
370             watch2.setLoginIds(userId);
371             watch2.setPolicyName("banana2");
372             commonClassDao.save(watch2);
373
374             // SQL Injection attempt
375             String finalName = "banana' OR '1'='1";
376
377             // Current Implementation
378             String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
379             SimpleBindings params = new SimpleBindings();
380             params.put("finalName", finalName);
381             params.put("userId", userId);
382             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
383
384             // Assertions
385             assertTrue(dataCur.size() <= 1);
386
387             if (dataCur.size() >= 1) {
388                 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
389                 assertFalse(watch.equals(dataCur.get(0)));
390                 assertFalse(watch.equals(dataCur.get(0)));
391             }
392         } catch (Exception e) {
393             logger.debug("Exception Occured" + e);
394             fail();
395         }
396     }
397
398     @Test
399     public void testCommonClassDaoImplMethods() {
400         try {
401             UserInfo userInfo = new UserInfo();
402             userInfo.setUserLoginId("TestID");
403             userInfo.setUserName("Test");
404             commonClassDao.save(userInfo);
405             List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
406             assertTrue(data.size() == 1);
407             UserInfo userInfoUpdate = (UserInfo) data.get(0);
408             userInfoUpdate.setUserName("Test1");
409             commonClassDao.update(userInfoUpdate);
410             List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
411             assertTrue(data1.size() == 1);
412             UserInfo data2 =
413                     (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1");
414             assertTrue("TestID".equals(data2.getUserLoginId()));
415             List<Object> data3 =
416                     commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
417             assertTrue(data3.size() == 1);
418             PolicyRoles roles = new PolicyRoles();
419             roles.setRole("admin");
420             roles.setLoginId(userInfo);
421             roles.setScope("test");
422             commonClassDao.save(roles);
423             List<PolicyRoles> roles1 = commonClassDao.getUserRoles();
424             assertTrue(roles1.size() == 1);
425             List<String> multipleData = new ArrayList<>();
426             multipleData.add("TestID:Test1");
427             List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class,
428                     "userLoginId:userName", multipleData);
429             assertTrue(data4.size() == 1);
430             commonClassDao.delete(data2);
431         } catch (Exception e) {
432             logger.debug("Exception Occured" + e);
433             fail();
434         }
435     }
436
437     @Test
438     public final void testGetLoggingData() {
439         SystemLogDbDaoImpl system = new SystemLogDbDaoImpl();
440         PolicyController.setjUnit(true);
441         try {
442             assertTrue(system.getLoggingData() != null);
443         } catch (Exception e) {
444             fail();
445         }
446     }
447
448     @Test
449     public final void testGetSystemAlertData() {
450         SystemLogDbDaoImpl system = new SystemLogDbDaoImpl();
451         PolicyController.setjUnit(true);
452         try {
453             assertTrue(system.getSystemAlertData() != null);
454         } catch (Exception e) {
455             fail();
456         }
457     }
458
459     @After
460     public void deleteDB() {
461         sessionFactory.close();
462         server.stop();
463     }
464 }