Convert tabs to spaces basic refactoring
[policy/engine.git] / ONAP-REST / src / test / java / org / onap / policy / rest / daoimpl / PolicyValidationDaoImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.onap.policy.rest.daoimpl;
21
22 import static org.junit.Assert.*;
23
24 import java.io.File;
25 import java.util.ArrayList;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.Properties;
29
30 import javax.script.SimpleBindings;
31
32 import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
33 import org.h2.tools.Server;
34 import org.hibernate.SessionFactory;
35 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Test;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 //import org.onap.policy.conf.HibernateSession;
41 //import org.onap.policy.controller.PolicyController;
42 import org.onap.policy.rest.jpa.OnapName;
43 import org.onap.policy.rest.jpa.PolicyEntity;
44 import org.onap.policy.rest.jpa.PolicyRoles;
45 import org.onap.policy.rest.jpa.PolicyVersion;
46 import org.onap.policy.rest.jpa.SystemLogDB;
47 import org.onap.policy.rest.jpa.UserInfo;
48 import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
49 import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
50 import org.springframework.transaction.annotation.Transactional;
51 import org.springframework.test.annotation.Rollback;
52
53
54 public class PolicyValidationDaoImplTest {
55
56     private static Logger logger = FlexLogger.getLogger(PolicyValidationDaoImplTest.class);
57
58     SessionFactory sessionFactory;
59     Server server;
60     PolicyValidationDaoImpl commonClassDao;
61
62     @Before
63     public void setUp() throws Exception{
64         try{
65             BasicDataSource dataSource = new BasicDataSource();
66             dataSource.setDriverClassName("org.h2.Driver");
67             // In-memory DB for testing
68             dataSource.setUrl("jdbc:h2:mem:test");
69             dataSource.setUsername("sa");
70             dataSource.setPassword("");
71             LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
72             sessionBuilder.scanPackages("org.onap.*", "com.*");
73
74             Properties properties = new Properties();
75             properties.put("hibernate.show_sql", "false");
76             properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
77             properties.put("hibernate.hbm2ddl.auto", "drop");
78             properties.put("hibernate.hbm2ddl.auto", "create");
79
80             sessionBuilder.addProperties(properties);
81             sessionFactory = sessionBuilder.buildSessionFactory();
82
83             // Set up dao with SessionFactory
84             commonClassDao = new PolicyValidationDaoImpl();
85             PolicyValidationDaoImpl.setSessionfactory(sessionFactory);
86             //PolicyController.setLogTableLimit("1");
87             //HibernateSession.setSession(sessionFactory);
88             SystemLogDB data1 = new SystemLogDB();
89             data1.setDate(new Date());
90             data1.setLogtype("INFO");
91             data1.setRemote("Test");
92             data1.setSystem("Test");
93             data1.setType("Test");
94             SystemLogDB data2 = new SystemLogDB();
95             data2.setDate(new Date());
96             data2.setLogtype("error");
97             data2.setRemote("Test");
98             data2.setSystem("Test");
99             data2.setType("Test");
100             //HibernateSession.getSession().save(data1);
101             //HibernateSession.getSession().save(data2);
102
103             // Create TCP server for troubleshooting
104             server = Server.createTcpServer("-tcpAllowOthers").start();
105             System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
106
107         }catch(Exception e){
108             System.err.println(e);
109             fail();
110         }
111     }
112
113     @Test
114     @Transactional
115     @Rollback(true)
116     public void testDB(){
117         try{
118             // Add data
119             UserInfo userinfo = new UserInfo();
120             userinfo.setUserLoginId("Test");
121             userinfo.setUserName("Test");
122             commonClassDao.save(userinfo);
123             OnapName onapName = new OnapName();
124             onapName.setOnapName("Test");
125             onapName.setUserCreatedBy(userinfo);
126             onapName.setUserModifiedBy(userinfo);
127             onapName.setModifiedDate(new Date());
128             commonClassDao.save(onapName);
129
130
131             List<Object> list = commonClassDao.getData(OnapName.class);
132             assertTrue(list.size() == 1);
133             logger.debug(list.size());
134             logger.debug(list.get(0));
135         }catch(Exception e){
136             logger.debug("Exception Occured"+e);
137             fail();
138         }
139     }
140
141     @Test
142     @Transactional
143     @Rollback(true)
144     public void testUser(){
145         try{
146             // Add data
147             UserInfo userinfo = new UserInfo();
148             String loginId_userName = "Test";
149             userinfo.setUserLoginId(loginId_userName);
150             userinfo.setUserName(loginId_userName);
151             commonClassDao.save(userinfo);
152
153
154             List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
155
156             assertEquals(1, dataCur.size());
157             UserInfo cur = (UserInfo) dataCur.get(0);
158             assertEquals(loginId_userName, cur.getUserLoginId());
159             assertEquals(loginId_userName, cur.getUserName());
160
161             assertFalse(dataCur.isEmpty());
162
163         }catch(Exception e){
164             logger.debug("Exception Occured"+e);
165             fail();
166         }
167     }
168
169     @Test
170     @Transactional
171     @Rollback(true)
172     public void getDataByQuery_DashboardController(){
173         try{
174             // Add data
175             PolicyEntity pe = new PolicyEntity();
176             String name = "TestPolicy";
177             pe.setPolicyName(name);
178             pe.setPolicyData("dummyData");
179             pe.prePersist();
180             pe.setScope("dummyScope");
181             pe.setDescription("descr");
182             pe.setDeleted(false);
183             pe.setCreatedBy("Test");
184             commonClassDao.save(pe);
185
186             List<Object> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
187
188             assertTrue(1 == dataCur.size());
189             assertTrue( dataCur.get(0) instanceof PolicyEntity);
190             assertEquals( name,  ((PolicyEntity)dataCur.get(0)).getPolicyName());
191             assertEquals( pe, ((PolicyEntity)dataCur.get(0)));
192
193
194         }catch(Exception e){
195             logger.debug("Exception Occured"+e);
196             fail();
197         }
198     }
199
200     @Test
201     @Transactional
202     @Rollback(true)
203     public void getDataByQuery_AutoPushController(){
204         try{
205             // Add data
206             PolicyVersion pv = new PolicyVersion();
207             pv.setActiveVersion(2);
208             pv.setPolicyName("myPname");
209             pv.prePersist();
210             pv.setCreatedBy("Test");
211             pv.setModifiedBy("Test");
212
213             PolicyVersion pv2 = new PolicyVersion();
214             pv2.setActiveVersion(1);
215             pv2.setPolicyName("test");
216             pv2.prePersist();
217             pv2.setCreatedBy("Test");
218             pv2.setModifiedBy("Test");
219
220             commonClassDao.save(pv);
221             commonClassDao.save(pv2);
222
223             String scope = "my";
224             scope += "%";
225             String query = "From PolicyVersion where policy_name like :scope and id > 0";
226             SimpleBindings params = new SimpleBindings();
227             params.put("scope", scope);
228             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
229
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
262             // Current Implementation
263             policyFileName += "%";
264             String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
265             SimpleBindings params = new SimpleBindings();
266             params.put("policyFileName", policyFileName);
267             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
268
269             // Assertions
270             assertTrue(dataCur.size() == 1);
271             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
272             assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0));
273
274         }catch(Exception e){
275             logger.debug("Exception Occured"+e);
276             fail();
277         }
278     }
279
280
281     @Test
282     @Transactional
283     @Rollback(true)
284     public void getDataByQuery_PolicyController(){
285         try{
286             // Add data
287             PolicyEntity pe = new PolicyEntity();
288             String name = "actionDummy";
289             pe.setPolicyName(name);
290             pe.setPolicyData("dummyData");
291             pe.prePersist();
292             pe.setScope("dummyScope");
293             pe.setDescription("descr");
294             pe.setDeleted(false);
295             pe.setCreatedBy("Test");
296             commonClassDao.save(pe);
297
298             String dbCheckName = "dummyScope:action";
299             String[] splitDBCheckName = dbCheckName.split(":");
300
301
302             // Current Implementation
303             String query =   "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
304             SimpleBindings params = new SimpleBindings();
305             params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
306             params.put("splitDBCheckName0", splitDBCheckName[0]);
307             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
308
309             // Assertions
310             assertTrue(dataCur.size() == 1);
311             assertTrue(dataCur.get(0) instanceof PolicyEntity);
312             assertEquals(pe, (PolicyEntity) dataCur.get(0));
313
314         }catch(Exception e){
315             logger.debug("Exception Occured"+e);
316             fail();
317         }
318     }
319
320     @Test
321     @Transactional
322     @Rollback(true)
323     public void getDataByQuery_PolicyNotificationController(){
324         try{
325             // Add data
326             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
327             String finalName = "banana"; // Policy File Name
328             String userId = "Test";
329             watch.setLoginIds(userId);
330             watch.setPolicyName(finalName);
331             commonClassDao.save(watch);
332
333
334             // Current Implementation
335             String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
336             SimpleBindings params = new SimpleBindings();
337             params.put("finalName", finalName);
338             params.put("userId", userId);
339             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
340
341             // Assertions
342             assertTrue(dataCur.size() == 1);
343             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
344             assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0) );
345
346         }catch(Exception e){
347             logger.debug("Exception Occured"+e);
348             fail();
349         }
350     }
351
352
353      /* Test for SQL Injection Protection
354      */
355
356     @Test
357     @Transactional
358     @Rollback(true)
359     public void getDataByQuery_PolicyNotificationController_Injection(){
360         try{
361             // Add data
362             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
363             String userId = "Test";
364             watch.setLoginIds(userId);
365             watch.setPolicyName("banana");
366             commonClassDao.save(watch);
367
368             WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
369             watch2.setLoginIds(userId);
370             watch2.setPolicyName("banana2");
371             commonClassDao.save(watch2);
372
373             // SQL Injection attempt
374             String finalName = "banana' OR '1'='1";
375
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((WatchPolicyNotificationTable) dataCur.get(0)));
390                 assertFalse(watch.equals((WatchPolicyNotificationTable) 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 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1");
413             assertTrue("TestID".equals(data2.getUserLoginId()));
414             List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
415             assertTrue(data3.size() == 1);
416             PolicyRoles roles = new PolicyRoles();
417             roles.setRole("admin");
418             roles.setLoginId(userInfo);
419             roles.setScope("test");
420             commonClassDao.save(roles);
421             List<PolicyRoles> roles1 = commonClassDao.getUserRoles();
422             assertTrue(roles1.size() == 1);
423             List<String> multipleData = new ArrayList<>();
424             multipleData.add("TestID:Test1");
425             List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName", multipleData);
426             assertTrue(data4.size() == 1);
427             commonClassDao.delete(data2);
428         }catch(Exception e){
429             logger.debug("Exception Occured"+e);
430             fail();
431         }
432     }
433
434     @After
435     public void deleteDB(){
436         sessionFactory.close();
437         server.stop();
438
439     }
440
441 }