cd9e644b90754ed46fe2d347977b53b5c1e57799
[portal/sdk.git] /
1 /*-
2  * ================================================================================
3  * eCOMP Portal SDK
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
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  * ================================================================================
19  */
20 package org.openecomp.portalsdk.core.dao.hibernate;
21
22 import java.io.Serializable;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30
31 import org.hibernate.Criteria;
32 import org.hibernate.FetchMode;
33 import org.hibernate.Query;
34 import org.hibernate.SQLQuery;
35 import org.hibernate.Session;
36 import org.hibernate.criterion.Criterion;
37 import org.hibernate.criterion.Order;
38 import org.hibernate.criterion.ProjectionList;
39 import org.hibernate.type.LongType;
40 import org.openecomp.portalsdk.core.dao.support.FusionDao;
41 import org.openecomp.portalsdk.core.domain.Lookup;
42 import org.openecomp.portalsdk.core.domain.support.DomainVo;
43 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
44 import org.openecomp.portalsdk.core.util.SystemProperties;
45
46 public abstract class ModelOperationsCommon extends FusionDao {
47
48         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ModelOperationsCommon.class);
49
50         @SuppressWarnings({ "rawtypes", "unchecked" })
51         public List _getList(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, String orderBy) {
52                 List list = null;
53                 String className = domainClass.getName();
54
55                 Session session = getSessionFactory().getCurrentSession();
56
57                 logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records"
58                                 + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "")
59                                 + "...");
60
61
62                 if (filterClause != null && filterClause.length() > 0) {
63                         logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause);
64
65                 }
66
67                 list = session.createQuery("from " + className + Utilities.nvl(filterClause, "")
68                                 + ((orderBy != null) ? " order by " + orderBy : "")).list();
69                 list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list;
70
71                 if (orderBy == null && list != null) {
72                         Collections.sort(list);
73                 }
74
75                 return list;
76         }
77
78         public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
79                         List<Order> orderByList) {
80                 return _getList(domainClass, projectionsList, restrictionsList, orderByList, null);
81         }
82
83         public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
84                         List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) {
85
86                 Session session = getSessionFactory().getCurrentSession();
87
88                 Criteria criteria = session.createCriteria(domainClass);
89
90                 if (projectionsList != null) {
91                         criteria.setProjection(projectionsList);
92                 }
93
94                 if (restrictionsList != null && !restrictionsList.isEmpty()) {
95                         for (Criterion criterion : restrictionsList)
96                                 criteria.add(criterion);
97                 }
98
99                 if (orderByList != null && !orderByList.isEmpty()) {
100                         for (Order order : orderByList)
101                                 criteria.addOrder(order);
102                 }
103
104                 if (fetchModeMap != null) {
105                         Iterator<String> itr = fetchModeMap.keySet().iterator();
106                         String key = null;
107                         while (itr.hasNext()) {
108                                 key = itr.next();
109                                 criteria.setFetchMode(key, fetchModeMap.get(key));
110                         }
111
112                 }
113                 return criteria.list();
114         }
115
116         @SuppressWarnings("rawtypes")
117         public DomainVo _get(Class domainClass, Serializable id) {
118                 DomainVo vo = null;
119
120                 Session session = getSessionFactory().getCurrentSession();
121
122                 logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString());
123
124
125                 vo = (DomainVo) session.get(domainClass, id);
126
127                 if (vo == null) {
128                         try {
129                                 vo = (DomainVo) domainClass.newInstance();
130                         } catch (Exception e) {
131                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed while instantiating a class of " + domainClass.getName() + e.getMessage());
132
133                         }
134                 }
135
136                 return vo;
137         }
138
139         @SuppressWarnings("rawtypes")
140         public List _getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy,
141                         HashMap additionalParams) {
142                 logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list...");
143
144                 List list = null;
145                 String dbOrderByCol = dbOrderBy;
146
147                 Session session = getSessionFactory().getCurrentSession();
148
149                 // default the orderBy if null;
150                 if (Utilities.nvl(dbOrderBy).length() == 0) {
151                         dbOrderByCol = dbLabelCol;
152                         dbOrderBy = dbLabelCol;
153                 } else {
154                         if (dbOrderBy.lastIndexOf(" ") > -1) {
155                                 dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" "));
156                         }
157                 }
158
159                 StringBuffer sql = new StringBuffer();
160
161                 sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ")
162                                 .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ")
163                                 .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ")
164                                 .append(dbOrderBy);
165
166                 try {
167                         list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list();
168                 } catch (Exception e) {
169                         list = null;
170                         logger.info(EELFLoggerDelegate.debugLogger, "The results for the lookup list query [" + sql + "] were empty.");
171                 }
172
173                 return list;
174         } // getLookupList
175
176         /* This method is used to execute SQL queries */
177         @SuppressWarnings("rawtypes")
178         protected final List _executeSQLQuery(String sql, Class domainClass) {
179                 return _executeSQLQuery(sql, domainClass, null, null);
180         }
181
182         /* This method is used to execute SQL queries with paging */
183         @SuppressWarnings("rawtypes")
184         protected final List _executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex) {
185                 Session session = getSessionFactory().getCurrentSession();
186
187                 SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass);
188
189                 if (fromIndex != null && toIndex != null) {
190                         query.setFirstResult(fromIndex.intValue());
191                         int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
192                         query.setMaxResults(pageSize);
193                 }
194
195                 return query.list();
196         }
197
198         /* This method is used to execute HQL queries */
199         @SuppressWarnings("rawtypes")
200         protected final List _executeQuery(String sql) {
201                 return _executeQuery(sql, null, null);
202         }
203
204         /* This method is used to execute HQL queries with paging */
205         @SuppressWarnings("rawtypes")
206         protected final List _executeQuery(String sql, Integer fromIndex, Integer toIndex) {
207                 Session session = getSessionFactory().getCurrentSession();
208
209                 Query query = session.createQuery(sql);
210
211                 if (fromIndex != null && toIndex != null) {
212                         query.setFirstResult(fromIndex.intValue());
213                         int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
214                         query.setMaxResults(pageSize);
215                 }
216
217                 return query.list();
218         }
219
220         /*
221          * This method can be used to execute both HQL or SQL named queries. The
222          * distinction will come in the hbm.xml mapping file defining the named
223          * query. Named HQL queries use the <query> tag while named SQL queries use
224          * the <sql-query> tag.
225          */
226         @SuppressWarnings("rawtypes")
227         protected final List _executeNamedQuery(String queryName, Map params) {
228                 return _executeNamedQuery(queryName, params, null, null);
229         }
230
231         /*
232          * This method can be used to execute both HQL or SQL named queries with
233          * paging. The distinction will come in the hbm.xml mapping file defining
234          * the named query. Named HQL queries use the <query> tag while named SQL
235          * queries use the <sql-query> tag.
236          */
237         @SuppressWarnings("rawtypes")
238         protected final List _executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex) {
239                 Session session = getSessionFactory().getCurrentSession();
240                 Query query = session.getNamedQuery(queryName);
241                 bindQueryParameters(query, params);
242                 if (fromIndex != null && toIndex != null) {
243                         query.setFirstResult(fromIndex.intValue());
244                         int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
245                         query.setMaxResults(pageSize);
246                 }
247                 return query.list();
248         }
249
250         // RAPTOR ZK
251         /*
252          * This method can be used to execute both HQL or SQL named queries with
253          * paging. The distinction will come in the hbm.xml mapping file defining
254          * the named query. Named HQL queries use the <query> tag while named SQL
255          * queries use the <sql-query> tag.
256          */
257         @SuppressWarnings("rawtypes")
258         protected final List _executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) {
259                 Session session = getSessionFactory().getCurrentSession();
260                 Query query = session.getNamedQuery(queryName);
261                 String queryStr = query.getQueryString();
262                 StringBuffer modifiedSql = new StringBuffer(" select count(*) as countRows from (" + queryStr + " ) al ");
263                 if (whereClause != null && whereClause.length() > 0)
264                         modifiedSql.append("where " + whereClause);
265                 // SQLQuery sqlQuery = session.createSQLQuery(" select count(*) as
266                 // {reportSearch.countRows} from ("+ modifiedSql.toString()+")");
267                 SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
268                 bindQueryParameters(sqlQuery, params);
269                 sqlQuery.addScalar("countRows", LongType.INSTANCE);
270                 // sqlQuery.addEntity("reportSearch", entity);
271                 // sqlQuery.setResultTransformer(new
272                 // AliasToBeanResultTransformer(SearchCount.class));
273                 return sqlQuery.list();
274
275         }
276
277         /*
278          * This method can be used to execute both HQL or SQL named queries with
279          * paging. The distinction will come in the hbm.xml mapping file defining
280          * the named query. Named HQL queries use the <query> tag while named SQL
281          * queries use the <sql-query> tag. It is modified to test ZK filter.
282          */
283         @SuppressWarnings("rawtypes")
284         protected final List _executeNamedQuery(Class entity, String queryName, String whereClause, Map params,
285                         Integer fromIndex, Integer toIndex) {
286                 Session session = getSessionFactory().getCurrentSession();
287                 Query query = session.getNamedQuery(queryName);
288                 bindQueryParameters(query, params);
289                 String queryStr = query.getQueryString();
290                 StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al ");
291                 if (whereClause != null && whereClause.length() > 0)
292                         modifiedSql.append("where " + whereClause);
293
294                 SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
295                 bindQueryParameters(sqlQuery, params);
296                 sqlQuery.addEntity("reportSearch", entity);
297
298                 if (fromIndex != null && toIndex != null) {
299                         sqlQuery.setFirstResult(fromIndex.intValue());
300                         int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
301                         sqlQuery.setMaxResults(pageSize);
302                 }
303                 return sqlQuery.list();
304         }
305
306         /*
307          * This method can be used to execute both HQL or SQL named queries with
308          * paging. The distinction will come in the hbm.xml mapping file defining
309          * the named query. Named HQL queries use the <query> tag while named SQL
310          * queries use the <sql-query> tag.
311          */
312         @SuppressWarnings("rawtypes")
313         protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy,
314                         boolean asc, Integer fromIndex, Integer toIndex) {
315                 Session session = getSessionFactory().getCurrentSession();
316                 Query query = session.getNamedQuery(queryName);
317                 bindQueryParameters(query, params);
318                 String queryStr = query.getQueryString();
319                 queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC");
320                 SQLQuery sqlQuery = session.createSQLQuery(queryStr);
321                 bindQueryParameters(sqlQuery, params);
322                 sqlQuery.addEntity("reportSearch", entity);
323                 if (fromIndex != null && toIndex != null) {
324                         sqlQuery.setFirstResult(fromIndex.intValue());
325                         int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
326                         sqlQuery.setMaxResults(pageSize);
327                 }
328                 return sqlQuery.list();
329         }
330
331         // Where Clause
332         @SuppressWarnings("rawtypes")
333         protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params,
334                         String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
335                 Session session = getSessionFactory().getCurrentSession();
336                 Query query = session.getNamedQuery(queryName);
337                 bindQueryParameters(query, params);
338                 String queryStr = query.getQueryString();
339                 queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC");
340                 // StringBuffer modifiedSql = new StringBuffer(queryStr );
341                 StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al ");
342                 // modifiedSql.insert(queryStr.lastIndexOf("order by"), " " +
343                 // whereClause + " ");
344                 if (whereClause != null && whereClause.length() > 0)
345                         modifiedSql.append("where " + whereClause);
346                 SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
347                 bindQueryParameters(sqlQuery, params);
348                 sqlQuery.addEntity("reportSearch", entity);
349                 if (fromIndex != null && toIndex != null) {
350                         sqlQuery.setFirstResult(fromIndex.intValue());
351                         int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
352                         sqlQuery.setMaxResults(pageSize);
353                 }
354                 return sqlQuery.list();
355         }
356
357         // RAPTOR ZK END
358
359         /* Processes custom Insert/Update/Delete SQL statements */
360         protected final int _executeUpdateQuery(String sql) throws Exception {
361                 Session session = getSessionFactory().getCurrentSession();
362                 Query query = session.createSQLQuery(sql);
363                 return query.executeUpdate();
364         }
365
366         /* Processes Insert/Update/Delete Named SQL statements */
367         @SuppressWarnings("rawtypes")
368         protected final int _executeNamedUpdateQuery(String queryName, Map params) throws Exception {
369                 Session session = getSessionFactory().getCurrentSession();
370                 Query query = session.getNamedQuery(queryName);
371                 bindQueryParameters(query, params);
372                 return query.executeUpdate();
373         }
374
375         protected final void _update(DomainVo vo, Integer userId) {
376                 _update(vo, ((userId != null) ? userId.intValue() : 0));
377         }
378
379         protected final void _update(DomainVo vo, int userId) {
380                 Date timestamp = new Date();
381
382                 Session session = getSessionFactory().getCurrentSession();
383
384                 if (vo.getId() == null || vo.getId().intValue() == 0) { // add new
385                         vo.setCreated(timestamp);
386                         vo.setModified(timestamp);
387
388                         if (userId != 0
389                                         && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
390                                 vo.setCreatedId(new Long(userId));
391                                 vo.setModifiedId(new Long(userId));
392                         }
393                 } else { // update existing
394                         vo.setModified(timestamp);
395
396                         if (userId != 0
397                                         && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
398                                 vo.setModifiedId(new Long(userId));
399                         }
400                 }
401
402                 session.saveOrUpdate(vo);
403         }
404
405         protected final void _remove(DomainVo vo) {
406                 Session session = getSessionFactory().getCurrentSession();
407                 session.delete(vo);
408         }
409
410         @SuppressWarnings("rawtypes")
411         protected final int _remove(Class domainClass, String whereClause) {
412                 int rowsAffected = 0;
413
414                 Session session = getSessionFactory().getCurrentSession();
415
416                 StringBuffer sql = new StringBuffer("delete from ");
417
418                 sql.append(domainClass.getName()).append(" where ").append(whereClause);
419
420                 rowsAffected = session.createQuery(sql.toString()).executeUpdate();
421
422                 return rowsAffected;
423         }
424
425         protected final void _flush() {
426                 Session session = getSessionFactory().getCurrentSession();
427                 session.flush();
428         }
429
430         @SuppressWarnings("rawtypes")
431         private void bindQueryParameters(Query query, Map params) {
432                 if (params != null) {
433                         for (Iterator i = params.entrySet().iterator(); i.hasNext();) {
434                                 Map.Entry entry = (Map.Entry) i.next();
435
436                                 Object parameterValue = entry.getValue();
437
438                                 if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) {
439                                         query.setParameter((String) entry.getKey(), parameterValue);
440                                 } else {
441                                         if (parameterValue instanceof Collection) {
442                                                 query.setParameterList((String) entry.getKey(), (Collection) parameterValue);
443                                         } else {
444                                                 if (parameterValue instanceof Object[]) {
445                                                         query.setParameterList((String) entry.getKey(), (Object[]) parameterValue);
446                                                 }
447                                         }
448                                 }
449                         }
450                 }
451         }
452
453 }