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