JUnit/SONAR/Checkstyle in ONAP-REST
[policy/engine.git] / ONAP-REST / src / main / java / org / onap / policy / rest / daoimpl / PolicyValidationDaoImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.rest.daoimpl;
23
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.script.SimpleBindings;
30
31 import org.hibernate.Criteria;
32 import org.hibernate.HibernateException;
33 import org.hibernate.Query;
34 import org.hibernate.Session;
35 import org.hibernate.SessionFactory;
36 import org.hibernate.Transaction;
37 import org.hibernate.criterion.Conjunction;
38 import org.hibernate.criterion.Disjunction;
39 import org.hibernate.criterion.Projections;
40 import org.hibernate.criterion.Restrictions;
41 import org.onap.policy.common.logging.flexlogger.FlexLogger;
42 import org.onap.policy.common.logging.flexlogger.Logger;
43 import org.onap.policy.rest.dao.CommonClassDao;
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.stereotype.Component;
48
49 @Component
50 public class PolicyValidationDaoImpl implements CommonClassDao {
51
52     private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationDaoImpl.class);
53     private static final String DB_CONNECTION_CLOSING_ERROR = "Error While Closing Connection/Statement";
54     private static final String DBTABLE_QUERY_ERROR = "Error While Querying Table";
55     private static SessionFactory sessionfactory;
56
57     @Autowired
58     private PolicyValidationDaoImpl(SessionFactory sessionfactory) {
59         PolicyValidationDaoImpl.sessionfactory = sessionfactory;
60     }
61
62     public PolicyValidationDaoImpl() {
63         // Default Constructor
64     }
65
66     public static SessionFactory getSessionfactory() {
67         return sessionfactory;
68     }
69
70     public static void setSessionfactory(SessionFactory sessionfactory) {
71         PolicyValidationDaoImpl.sessionfactory = sessionfactory;
72     }
73
74     @SuppressWarnings({ "unchecked", "rawtypes" })
75     @Override
76     public List<Object> getData(Class className) {
77         Session session = sessionfactory.openSession();
78         List<Object> data = null;
79         try {
80             Criteria cr = session.createCriteria(className);
81             data = cr.list();
82         } catch (Exception e) {
83             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
84         } finally {
85             try {
86                 session.close();
87             } catch (Exception e) {
88                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e);
89             }
90         }
91         return data;
92     }
93
94
95     @SuppressWarnings({ "rawtypes", "unchecked" })
96     @Override
97     public List<Object> getDataById(Class className, String columnName, String key) {
98         Session session = sessionfactory.openSession();
99         List<Object> data = null;
100         try {
101             Criteria cr = session.createCriteria(className);
102             if (columnName.contains(":") && key.contains(":")) {
103                 String[] columns = columnName.split(":");
104                 String[] keys = key.split(":");
105                 for (int i = 0; i < columns.length; i++) {
106                     cr.add(Restrictions.eq(columns[i], keys[i]));
107                 }
108             } else {
109                 cr.add(Restrictions.eq(columnName, key));
110             }
111             data = cr.list();
112         } catch (Exception e) {
113             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
114         } finally {
115             try {
116                 session.close();
117             } catch (Exception e1) {
118                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
119             }
120         }
121         return data;
122     }
123
124     @Override
125     public void save(Object entity) {
126         Session session = sessionfactory.openSession();
127         Transaction tx = session.beginTransaction();
128         try {
129             session.persist(entity);
130             tx.commit();
131         } catch (Exception e) {
132             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table" + e);
133         } finally {
134             try {
135                 session.close();
136             } catch (Exception e1) {
137                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
138             }
139         }
140
141     }
142
143     @Override
144     public void delete(Object entity) {
145         Session session = sessionfactory.openSession();
146         Transaction tx = session.beginTransaction();
147         try {
148             session.delete(entity);
149             tx.commit();
150         } catch (Exception e) {
151             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table" + e);
152         } finally {
153             try {
154                 session.close();
155             } catch (Exception e1) {
156                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
157             }
158         }
159
160     }
161
162
163     @Override
164     public void update(Object entity) {
165         Session session = sessionfactory.openSession();
166         Transaction tx = session.beginTransaction();
167         try {
168             session.update(entity);
169             tx.commit();
170         } catch (Exception e) {
171             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table" + e);
172         } finally {
173             try {
174                 session.close();
175             } catch (Exception e1) {
176                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
177             }
178         }
179
180     }
181
182
183     @SuppressWarnings({ "unchecked", "rawtypes" })
184     @Override
185     public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
186         Session session = sessionfactory.openSession();
187         Transaction tx = session.beginTransaction();
188         List<Object> data = null;
189         String[] columnNames = null;
190         if (columnName != null && columnName.contains(":")) {
191             columnNames = columnName.split(":");
192         }
193         String[] values = null;
194         if (value != null && value.contains(":")) {
195             values = value.split(":");
196         }
197         try {
198             Criteria cr = session.createCriteria(className);
199             if (columnNames != null && values != null && columnNames.length == values.length) {
200                 for (int i = 0; i < columnNames.length; i++) {
201                     cr.add(Restrictions.eq(columnNames[i], values[i]));
202                 }
203             } else {
204                 cr.add(Restrictions.eq(columnName, value));
205             }
206             data = cr.list();
207             tx.commit();
208         } catch (Exception e) {
209             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"
210                     + e + className);
211         } finally {
212             try {
213                 session.close();
214             } catch (Exception e1) {
215                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
216             }
217         }
218         return data;
219     }
220
221
222     @SuppressWarnings("unchecked")
223     @Override
224     public List<PolicyRoles> getUserRoles() {
225         Session session = sessionfactory.openSession();
226         Transaction tx = session.beginTransaction();
227         List<PolicyRoles> rolesData = null;
228         try {
229             final Criteria cr = session.createCriteria(PolicyRoles.class);
230             final Disjunction disjunction = Restrictions.disjunction();
231             Conjunction conjunction1 = Restrictions.conjunction();
232             conjunction1.add(Restrictions.eq("role", "admin"));
233             Conjunction conjunction2 = Restrictions.conjunction();
234             conjunction2.add(Restrictions.eq("role", "editor"));
235             Conjunction conjunction3 = Restrictions.conjunction();
236             conjunction3.add(Restrictions.eq("role", "guest"));
237             disjunction.add(conjunction1);
238             disjunction.add(conjunction2);
239             disjunction.add(conjunction3);
240             rolesData = cr.add(disjunction).list();
241             tx.commit();
242         } catch (Exception e) {
243             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table" + e);
244         } finally {
245             try {
246                 session.close();
247             } catch (Exception e1) {
248                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
249             }
250         }
251         return rolesData;
252     }
253
254
255     @Override
256     public List<Object> checkExistingGroupListforUpdate(String arg0, String arg1) {
257         return Collections.emptyList();
258     }
259
260
261     @Override
262     public void deleteAll() {
263         // Do nothing because this method is not used and is a placeholder to avoid 'Unimplemented Method' error
264     }
265
266
267     @SuppressWarnings("unchecked")
268     @Override
269     public List<Object> getDataByQuery(String query, SimpleBindings params) {
270         Session session = sessionfactory.openSession();
271         Transaction tx = session.beginTransaction();
272         List<Object> data = null;
273         try {
274             Query hbquery = session.createQuery(query);
275             for (Map.Entry<String, Object> paramPair : params.entrySet()) {
276                 if (paramPair.getValue() instanceof java.lang.Long) {
277                     hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
278                 } else {
279                     hbquery.setParameter(paramPair.getKey(), paramPair.getValue());
280                 }
281             }
282             data = hbquery.list();
283             tx.commit();
284         } catch (Exception e) {
285             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
286             throw e;
287         } finally {
288             try {
289                 session.close();
290             } catch (HibernateException e1) {
291                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
292             }
293         }
294         return data;
295     }
296
297
298     @SuppressWarnings("rawtypes")
299     @Override
300     public Object getEntityItem(Class className, String columnName, String key) {
301         Session session = sessionfactory.openSession();
302         Transaction tx = session.beginTransaction();
303         Object data = null;
304         try {
305             Criteria cr = session.createCriteria(className);
306             if (columnName.contains(":") && key.contains(":")) {
307                 String[] columns = columnName.split(":");
308                 String[] keys = key.split(":");
309                 for (int i = 0; i < columns.length; i++) {
310                     cr.add(Restrictions.eq(columns[i], keys[i]));
311                 }
312             } else {
313                 cr.add(Restrictions.eq(columnName, key));
314             }
315             data = cr.list().get(0);
316             tx.commit();
317         } catch (Exception e) {
318             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
319         } finally {
320             try {
321                 session.close();
322             } catch (Exception e1) {
323                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
324             }
325         }
326         return data;
327     }
328
329
330     @Override
331     public void updateClAlarms(String arg0, String arg1) {
332         // Do nothing because this method is not used and is a placeholder to avoid 'Unimplemented Method' error
333     }
334
335
336     @Override
337     public void updateClYaml(String arg0, String arg1) {
338         // Do nothing because this method is not used and is a placeholder to avoid 'Unimplemented Method' error
339     }
340
341
342     @Override
343     public void updateQuery(String query) {
344         Session session = sessionfactory.openSession();
345         Transaction tx = session.beginTransaction();
346         try {
347             Query hbquery = session.createQuery(query);
348             hbquery.executeUpdate();
349             tx.commit();
350         } catch (Exception e) {
351             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table" + e);
352         } finally {
353             try {
354                 session.close();
355             } catch (Exception e1) {
356                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
357             }
358         }
359
360     }
361
362
363     @SuppressWarnings({ "rawtypes", "unchecked" })
364     @Override
365     public List<String> getDataByColumn(Class className, String columnName) {
366         Session session = sessionfactory.openSession();
367         List<String> data = null;
368         try {
369             Criteria cr = session.createCriteria(className);
370             cr.setProjection(Projections.property(columnName));
371             data = cr.list();
372         } catch (Exception e) {
373             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
374         } finally {
375             try {
376                 session.close();
377             } catch (Exception e) {
378                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e);
379             }
380         }
381         return data;
382     }
383
384
385     @SuppressWarnings({ "rawtypes", "unchecked" })
386     @Override
387     public List<Object> getMultipleDataOnAddingConjunction(Class className, String columnName, List<String> data) {
388         Session session = sessionfactory.openSession();
389         Transaction tx = session.beginTransaction();
390         List<Object> entityData = null;
391         try {
392             Criteria cr = session.createCriteria(className);
393             Disjunction disjunction = Restrictions.disjunction();
394             List<Conjunction> conjunctionList = new ArrayList<>();
395             String[] columNames = columnName.split(":");
396             for (int i = 0; i < data.size(); i++) {
397                 String[] entiySplit = data.get(i).split(":");
398                 Conjunction conjunction = Restrictions.conjunction();
399                 conjunction.add(Restrictions.eq(columNames[0], entiySplit[0]));
400                 conjunction.add(Restrictions.eq(columNames[1], entiySplit[1]));
401                 conjunctionList.add(conjunction);
402             }
403             for (int j = 0; j < conjunctionList.size(); j++) {
404                 disjunction.add(conjunctionList.get(j));
405             }
406             entityData = cr.add(disjunction).list();
407             tx.commit();
408         } catch (Exception e) {
409             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + className + e);
410         } finally {
411             try {
412                 session.close();
413             } catch (Exception e1) {
414                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
415             }
416         }
417         return entityData;
418     }
419
420 }