2 * ================================================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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 * ================================================================================
20 package org.openecomp.portalsdk.core.dao.hibernate;
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;
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;
46 public abstract class ModelOperationsCommon extends FusionDao {
48 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ModelOperationsCommon.class);
50 @SuppressWarnings({ "rawtypes", "unchecked" })
51 public List _getList(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, String orderBy) {
53 String className = domainClass.getName();
55 Session session = getSessionFactory().getCurrentSession();
57 logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records"
58 + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "")
62 if (filterClause != null && filterClause.length() > 0) {
63 logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause);
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;
71 if (orderBy == null && list != null) {
72 Collections.sort(list);
78 public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
79 List<Order> orderByList) {
80 return _getList(domainClass, projectionsList, restrictionsList, orderByList, null);
83 public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
84 List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) {
86 Session session = getSessionFactory().getCurrentSession();
88 Criteria criteria = session.createCriteria(domainClass);
90 if (projectionsList != null) {
91 criteria.setProjection(projectionsList);
94 if (restrictionsList != null && !restrictionsList.isEmpty()) {
95 for (Criterion criterion : restrictionsList)
96 criteria.add(criterion);
99 if (orderByList != null && !orderByList.isEmpty()) {
100 for (Order order : orderByList)
101 criteria.addOrder(order);
104 if (fetchModeMap != null) {
105 Iterator<String> itr = fetchModeMap.keySet().iterator();
107 while (itr.hasNext()) {
109 criteria.setFetchMode(key, fetchModeMap.get(key));
113 return criteria.list();
116 @SuppressWarnings("rawtypes")
117 public DomainVo _get(Class domainClass, Serializable id) {
120 Session session = getSessionFactory().getCurrentSession();
122 logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString());
125 vo = (DomainVo) session.get(domainClass, id);
129 vo = (DomainVo) domainClass.newInstance();
130 } catch (Exception e) {
131 logger.error(EELFLoggerDelegate.errorLogger, "Failed while instantiating a class of " + domainClass.getName() + e.getMessage());
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...");
145 String dbOrderByCol = dbOrderBy;
147 Session session = getSessionFactory().getCurrentSession();
149 // default the orderBy if null;
150 if (Utilities.nvl(dbOrderBy).length() == 0) {
151 dbOrderByCol = dbLabelCol;
152 dbOrderBy = dbLabelCol;
154 if (dbOrderBy.lastIndexOf(" ") > -1) {
155 dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" "));
159 StringBuffer sql = new StringBuffer();
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 ")
167 list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list();
168 } catch (Exception e) {
170 logger.info(EELFLoggerDelegate.debugLogger, "The results for the lookup list query [" + sql + "] were empty.");
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);
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();
187 SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass);
189 if (fromIndex != null && toIndex != null) {
190 query.setFirstResult(fromIndex.intValue());
191 int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
192 query.setMaxResults(pageSize);
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);
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();
209 Query query = session.createQuery(sql);
211 if (fromIndex != null && toIndex != null) {
212 query.setFirstResult(fromIndex.intValue());
213 int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
214 query.setMaxResults(pageSize);
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.
226 @SuppressWarnings("rawtypes")
227 protected final List _executeNamedQuery(String queryName, Map params) {
228 return _executeNamedQuery(queryName, params, null, null);
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.
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);
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.
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();
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.
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);
294 SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
295 bindQueryParameters(sqlQuery, params);
296 sqlQuery.addEntity("reportSearch", entity);
298 if (fromIndex != null && toIndex != null) {
299 sqlQuery.setFirstResult(fromIndex.intValue());
300 int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
301 sqlQuery.setMaxResults(pageSize);
303 return sqlQuery.list();
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.
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);
328 return sqlQuery.list();
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);
354 return sqlQuery.list();
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();
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();
375 protected final void _update(DomainVo vo, Integer userId) {
376 _update(vo, ((userId != null) ? userId.intValue() : 0));
379 protected final void _update(DomainVo vo, int userId) {
380 Date timestamp = new Date();
382 Session session = getSessionFactory().getCurrentSession();
384 if (vo.getId() == null || vo.getId().intValue() == 0) { // add new
385 vo.setCreated(timestamp);
386 vo.setModified(timestamp);
389 && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
390 vo.setCreatedId(new Long(userId));
391 vo.setModifiedId(new Long(userId));
393 } else { // update existing
394 vo.setModified(timestamp);
397 && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
398 vo.setModifiedId(new Long(userId));
402 session.saveOrUpdate(vo);
405 protected final void _remove(DomainVo vo) {
406 Session session = getSessionFactory().getCurrentSession();
410 @SuppressWarnings("rawtypes")
411 protected final int _remove(Class domainClass, String whereClause) {
412 int rowsAffected = 0;
414 Session session = getSessionFactory().getCurrentSession();
416 StringBuffer sql = new StringBuffer("delete from ");
418 sql.append(domainClass.getName()).append(" where ").append(whereClause);
420 rowsAffected = session.createQuery(sql.toString()).executeUpdate();
425 protected final void _flush() {
426 Session session = getSessionFactory().getCurrentSession();
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();
436 Object parameterValue = entry.getValue();
438 if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) {
439 query.setParameter((String) entry.getKey(), parameterValue);
441 if (parameterValue instanceof Collection) {
442 query.setParameterList((String) entry.getKey(), (Collection) parameterValue);
444 if (parameterValue instanceof Object[]) {
445 query.setParameterList((String) entry.getKey(), (Object[]) parameterValue);