Refactor to provide Common Policy Validation
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / daoimpl / CommonClassDaoImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-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
21 package org.onap.policy.pap.xacml.rest.daoimpl;
22
23 import java.util.List;
24 import java.util.Map;
25
26 import javax.script.SimpleBindings;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.hibernate.Criteria;
31 import org.hibernate.HibernateException;
32 import org.hibernate.Query;
33 import org.hibernate.Session;
34 import org.hibernate.SessionFactory;
35 import org.hibernate.Transaction;
36 import org.hibernate.criterion.Conjunction;
37 import org.hibernate.criterion.Criterion;
38 import org.hibernate.criterion.Disjunction;
39 import org.hibernate.criterion.Projections;
40 import org.hibernate.criterion.Restrictions;
41 import org.onap.policy.rest.dao.CommonClassDao;
42 import org.onap.policy.rest.jpa.ClosedLoops;
43 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
44 import org.onap.policy.rest.jpa.PolicyRoles;
45 import org.onap.policy.xacml.api.XACMLErrorConstants;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.context.annotation.Primary;
48 import org.springframework.stereotype.Component;
49 import org.springframework.stereotype.Service;
50
51 @Service("CommonClassDao")
52 @Primary
53 public class CommonClassDaoImpl implements CommonClassDao{
54
55         private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class);
56         
57         
58         private static SessionFactory sessionFactory;
59         
60         
61         @Autowired
62         private CommonClassDaoImpl(SessionFactory sessionFactory){
63                 CommonClassDaoImpl.sessionFactory = sessionFactory;
64         }
65         
66         public CommonClassDaoImpl(){
67                 //Default Constructor
68         }
69         
70         @SuppressWarnings({ "unchecked", "rawtypes" })
71         @Override
72         public List<Object> getData(Class className) {
73                 Session session = sessionFactory.openSession();
74                 List<Object> data = null;
75                 try{
76                         Criteria cr = session.createCriteria(className);
77                         data = cr.list();
78                 }catch(Exception e){
79                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);  
80                 }finally{
81                         try{
82                                 session.close();
83                         }catch(Exception e){
84                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e);
85                         }
86                 }
87                 return data;
88         }
89
90
91         @SuppressWarnings({ "rawtypes", "unchecked" })
92         @Override
93         public List<Object> getDataById(Class className, String columnName, String key) {
94                 Session session = sessionFactory.openSession();
95                 List<Object> data = null;
96                 try {
97                         Criteria cr = session.createCriteria(className);
98                         if(columnName.contains(":") && key.contains(":")){
99                                 String[] columns = columnName.split(":");
100                                 String[] keys = key.split(":");
101                                 for(int i=0; i < columns.length; i++){
102                                         cr.add(Restrictions.eq(columns[i], keys[i]));
103                                 }
104                         }else{
105                                 cr.add(Restrictions.eq(columnName, key));       
106                         }
107                         data = cr.list();
108                 } catch (Exception e) {
109                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);          
110                 }finally{
111                         try{
112                                 session.close();
113                         }catch(Exception e1){
114                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
115                         }
116                 }
117                 return data;
118         }
119         
120         @SuppressWarnings({ "unchecked", "rawtypes" })
121         @Override
122         public List<String> getDataByColumn(Class className, String columnName) {
123                 Session session = sessionFactory.openSession();
124                 List<String> data = null;
125                 try{
126                         Criteria cr = session.createCriteria(className);
127                         cr.setProjection(Projections.property(columnName));
128                         data = cr.list();
129                 }catch(Exception e){
130                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);  
131                 }finally{
132                         try{
133                                 session.close();
134                         }catch(Exception e){
135                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e);
136                         }
137                 }
138                 return data;
139         }
140         
141         @Override
142         public void save(Object entity) {
143                 Session session = sessionFactory.openSession();
144                 Transaction tx = session.beginTransaction();
145                 try {
146                         session.persist(entity);
147                         tx.commit();    
148                 }catch(Exception e){
149                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving  data to Table"+e);   
150                 }finally{
151                         try{
152                                 session.close();
153                         }catch(Exception e1){
154                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
155                         }
156                 }
157                 
158         }
159
160         @Override
161         public void delete(Object entity) {
162                 Session session = sessionFactory.openSession();
163                 Transaction tx = session.beginTransaction();
164                 try {
165                         session.delete(entity);
166                         tx.commit();    
167                 }catch(Exception e){
168                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e);        
169                 }finally{
170                         try{
171                                 session.close();
172                         }catch(Exception e1){
173                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
174                         }
175                 }
176                 
177         }
178
179
180         @Override
181         public void update(Object entity) {
182                 Session session = sessionFactory.openSession();
183                 Transaction tx = session.beginTransaction();
184                 try {
185                         session.update(entity);
186                         tx.commit();    
187                 }catch(Exception e){
188                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e);  
189                 }finally{
190                         try{
191                                 session.close();
192                         }catch(Exception e1){
193                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
194                         }
195                 }
196                 
197         }
198
199
200         @SuppressWarnings({ "unchecked", "rawtypes" })
201         @Override
202         public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
203                 Session session = sessionFactory.openSession();
204                 Transaction tx = session.beginTransaction();
205                 List<Object> data = null;
206                 
207                 String[] columnNames = null;
208                 if(columnName != null && columnName.contains(":")){
209                         columnNames = columnName.split(":");
210                 }
211                 String[] values = null;
212                 if(value != null && value.contains(":")){
213                         values = value.split(":");
214                 }               
215                 try {
216                         Criteria cr = session.createCriteria(className);
217                         if(columnNames != null && values != null && columnNames.length == values.length){
218                                 for (int i = 0; i < columnNames.length; i++){
219                                         cr.add(Restrictions.eq(columnNames[i],values[i]));
220                                 }
221                         }else{
222                                 cr.add(Restrictions.eq(columnName,value));
223                         }
224
225                         data = cr.list();
226                         tx.commit();
227                 } catch (Exception e) {
228                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className);    
229                 }finally{
230                         try{
231                                 session.close();
232                         }catch(Exception e1){
233                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
234                         }
235                 }
236                 return data;
237         }
238
239         
240         @SuppressWarnings("unchecked")
241         @Override
242         public List<Object> getDataByQuery(String query, SimpleBindings params) {
243                 Session session = sessionFactory.openSession();
244                 Transaction tx = session.beginTransaction();
245                 List<Object> data = null;
246                 try {
247                         Query hbquery = session.createQuery(query);
248                         for (Map.Entry<String, Object> paramPair : params.entrySet()) {
249                                 if(paramPair.getValue() instanceof java.lang.Long){
250                                         hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
251                                 }
252                                 else{
253                                         hbquery.setParameter(paramPair.getKey(), paramPair.getValue());
254                                 }
255                         }
256                         data = hbquery.list();
257                         tx.commit();
258                 } catch (Exception e) {
259                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e);
260                         throw e;
261                 }finally{
262                         try{
263                                 session.close();
264                         }catch(HibernateException e1){
265                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement",e1);
266                         }
267                 }
268                 return data;
269         }
270
271
272         @Override
273         public void updateQuery(String query) {
274                 Session session = sessionFactory.openSession();
275                 Transaction tx = session.beginTransaction();    
276                 try {
277                         Query hbquery = session.createQuery(query);
278                         hbquery.executeUpdate();
279                         tx.commit();
280                 } catch (Exception e) {
281                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); 
282                 }finally{
283                         try{
284                                 session.close();
285                         }catch(Exception e1){
286                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
287                         }
288                 }
289         }
290
291
292         @SuppressWarnings("rawtypes")
293         @Override
294         public Object getEntityItem(Class className, String columnName, String key) {
295                 Session session = sessionFactory.openSession();
296                 Transaction tx = session.beginTransaction();
297                 Object data = null;
298                 try {
299                         Criteria cr = session.createCriteria(className);
300                         if(columnName.contains(":") && key.contains(":")){
301                                 String[] columns = columnName.split(":");
302                                 String[] keys = key.split(":");
303                                 for(int i=0; i < columns.length; i++){
304                                         cr.add(Restrictions.eq(columns[i], keys[i]));
305                                 }
306                         }else{
307                                 cr.add(Restrictions.eq(columnName, key));       
308                         }
309                         data = cr.list().get(0);
310                         tx.commit();
311                 } catch (Exception e) {
312                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); 
313                 }finally{
314                         try{
315                                 session.close();
316                         }catch(Exception e1){
317                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
318                         }
319                 }
320                 return data;
321         }
322
323
324         @SuppressWarnings("unchecked")
325         @Override
326         public List<PolicyRoles> getUserRoles() {
327                 Session session = sessionFactory.openSession();
328                 Transaction tx = session.beginTransaction();
329                 List<PolicyRoles> rolesData = null;
330                 try {
331                         Criteria cr = session.createCriteria(PolicyRoles.class);                
332                         Disjunction disjunction = Restrictions.disjunction(); 
333                         Conjunction conjunction1  = Restrictions.conjunction();
334                         conjunction1.add(Restrictions.eq("role", "admin"));
335                         Conjunction conjunction2  = Restrictions.conjunction();
336                         conjunction2.add(Restrictions.eq("role", "editor"));    
337                         Conjunction conjunction3  = Restrictions.conjunction();
338                         conjunction3.add(Restrictions.eq("role", "guest"));     
339                         disjunction.add(conjunction1);
340                         disjunction.add(conjunction2);
341                         disjunction.add(conjunction3);
342                         rolesData = cr.add(disjunction).list();
343                         tx.commit();
344                 } catch (Exception e) {
345                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e);      
346                 }finally{
347                         try{
348                                 session.close();
349                         }catch(Exception e1){
350                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
351                         }
352                 }
353                 return rolesData;
354         }
355
356
357         @SuppressWarnings("unchecked")
358         @Override
359         public void updateClAlarms(String clName, String alarms) {
360                 Session session = sessionFactory.openSession();
361                 List<ClosedLoops> closedloopsdata = null;
362                 Transaction tx = session.beginTransaction();
363                 try {
364                 Criteria cr = session.createCriteria(ClosedLoops.class);
365                 cr.add(Restrictions.eq("closedLoopControlName",clName));
366             closedloopsdata = cr.list();
367                         ClosedLoops closedloop = closedloopsdata.get(0);
368                         closedloop.setAlarmConditions(alarms);
369                         session.update(closedloop);
370                         tx.commit();    
371                 }catch(Exception e){
372                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e);      
373                 }finally{
374                         session.close();
375                 }
376         }
377
378
379         @SuppressWarnings("unchecked")
380         @Override
381         public void updateClYaml(String clName, String yaml) {
382                 Session session = sessionFactory.openSession();
383         List<ClosedLoops> closedloopsdata = null;
384                 Transaction tx = session.beginTransaction();
385                 try {
386                 Criteria cr = session.createCriteria(ClosedLoops.class);
387                 cr.add(Restrictions.eq("closedLoopControlName",clName));
388             closedloopsdata = cr.list();
389                         ClosedLoops closedloop = closedloopsdata.get(0);
390                         closedloop.setYaml(yaml);
391                         session.update(closedloop);
392                         tx.commit();    
393                 }catch(Exception e){
394                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e);      
395                 }finally{
396                         session.close();
397                 }
398         }
399
400
401         @SuppressWarnings("unchecked")
402         @Override
403         public void deleteAll() {
404                 Session session = sessionFactory.openSession();
405                 Transaction tx = session.beginTransaction();
406                 List<ClosedLoops> closedloopsdata = null;
407                 try {
408                         Criteria cr = session.createCriteria(ClosedLoops.class);
409                         closedloopsdata = cr.list();
410
411                         if(closedloopsdata!=null && !closedloopsdata.isEmpty()) {
412                                 LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache().");
413                                 for(int i=0; i < closedloopsdata.size(); i++) {
414                                         ClosedLoops cl = closedloopsdata.get(i);
415                                         session.delete(cl);
416                                 }
417                         } else {
418                                 LOGGER.info("No ClosedLoops exist in the database, no need to delete.");
419                         }
420
421                         tx.commit();
422                 }catch(Exception e) {
423                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e);
424                 }finally{
425                         session.close();
426                 }
427         }
428
429         @SuppressWarnings({ "unchecked"})
430         @Override
431         public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) {
432                 Session session = sessionFactory.openSession();
433                 Transaction tx = session.beginTransaction();
434                 List<Object> data = null;
435                 try {
436                         Criteria cr = session.createCriteria(GroupPolicyScopeList.class);
437                         cr.add(Restrictions.eq("groupList",groupListValue));    
438                         Criterion expression = Restrictions.eq("name", groupNameValue);
439                         cr.add(Restrictions.not(expression));
440                         data = cr.list();
441                         tx.commit();
442                 } catch (Exception e) {
443                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table"+e);   
444                 }finally{
445                         try{
446                                 session.close();
447                         }catch(Exception e1){
448                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
449                         }
450                 }
451                 return data;
452         }
453
454
455         @Override
456         public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) {
457                 return null;
458         }
459
460     public static void setSessionfactory(SessionFactory sessionfactory) {
461         sessionFactory = sessionfactory;
462     }
463
464 }