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