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