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