2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.onap.portalsdk.core.service;
40 import java.io.Serializable;
41 import java.util.Collection;
42 import java.util.Collections;
43 import java.util.Date;
44 import java.util.Iterator;
45 import java.util.List;
48 import org.hibernate.Criteria;
49 import org.hibernate.FetchMode;
50 import org.hibernate.Query;
51 import org.hibernate.SQLQuery;
52 import org.hibernate.Session;
53 import org.hibernate.SessionFactory;
54 import org.hibernate.criterion.Criterion;
55 import org.hibernate.criterion.Order;
56 import org.hibernate.criterion.ProjectionList;
57 import org.onap.portalsdk.core.domain.Lookup;
58 import org.onap.portalsdk.core.domain.support.DomainVo;
59 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
60 import org.onap.portalsdk.core.service.support.FusionService;
61 import org.onap.portalsdk.core.util.SystemProperties;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.transaction.annotation.Transactional;
66 * Provides implementations of methods in {@link DataAccessService}.
68 @SuppressWarnings("deprecation")
70 public class DataAccessServiceImpl extends FusionService implements DataAccessService {
72 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DataAccessServiceImpl.class);
75 private SessionFactory sessionFactory;
78 public DomainVo getDomainObject(Class domainClass, Serializable id, Map additionalParams) {
79 Session session = sessionFactory.getCurrentSession();
80 logger.info(EELFLoggerDelegate.debugLogger,
81 "Getting " + domainClass.getName() + " record for id - " + id.toString());
82 DomainVo vo = (DomainVo) session.get(domainClass, id);
85 vo = (DomainVo) domainClass.newInstance();
86 } catch (Exception e) {
87 logger.error(EELFLoggerDelegate.errorLogger,
88 "getDomainObject failed while instantiating class " + domainClass.getName(), e);
95 public void deleteDomainObject(DomainVo domainObject, Map additionalParams) {
96 Session session = sessionFactory.getCurrentSession();
97 session.delete(domainObject);
101 public void deleteDomainObjects(Class domainClass, String whereClause, Map additionalParams) {
102 Session session = sessionFactory.getCurrentSession();
103 StringBuffer sql = new StringBuffer("delete from ");
104 sql.append(domainClass.getName()).append(" where ").append(whereClause);
105 Query query = session.createQuery(sql.toString());
106 query.executeUpdate();
110 public void saveDomainObject(DomainVo vo, Map additionalParams) {
112 if (additionalParams != null) {
113 Object uid = additionalParams.get(Parameters.PARAM_USERID);
114 if (uid instanceof Integer) {
115 userId = (Integer) uid;
116 } else if (uid instanceof Long) {
117 userId = ((Long) uid).intValue();
124 * Creates or updates the specified virtual object. Uses the specified user ID
125 * as the creator and modifier if a new object is created; uses ID only as
126 * modifier if an object already exists.
130 * Ignored if value is zero.
132 protected final void _update(DomainVo vo, int userId) {
133 Date timestamp = new Date();
135 Session session = sessionFactory.getCurrentSession();
137 if (vo.getId() == null || vo.getId().intValue() == 0) { // add new
138 vo.setCreated(timestamp);
139 vo.setModified(timestamp);
142 && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
143 vo.setCreatedId(new Long(userId));
144 vo.setModifiedId(new Long(userId));
146 } else { // update existing
147 vo.setModified(timestamp);
150 && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
151 vo.setModifiedId(new Long(userId));
155 session.saveOrUpdate(vo);
159 * generic get list method
162 * This method may be vulnerable to SQL Injection attacks depending on the usage and is being deprecated. Please use
163 * getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
164 List<Order> orderByList) method instead
167 * @param filterClause
174 private List getListCommon(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex,
176 String className = domainClass.getName();
177 Session session = sessionFactory.getCurrentSession();
179 if (logger.isInfoEnabled()) {
180 logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records"
181 + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "")
183 if (filterClause != null && filterClause.length() > 0)
184 logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause);
187 List list = session.createQuery("from " + className + Utilities.nvl(filterClause, "")
188 + ((orderBy != null) ? " order by " + orderBy : "")).list();
189 list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list;
190 if (orderBy == null && list != null)
191 Collections.sort(list);
198 * This method may be vulnerable to SQL Injection attacks depending on the usage and is being deprecated. Please use
199 * getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
200 List<Order> orderByList) method instead
204 public List getList(Class domainClass, Map additionalParams) {
205 return getListCommon(domainClass, null, null, null, null);
210 * This method may be vulnerable to SQL Injection attacks depending on the usage and is being deprecated. Please use
211 * getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
212 List<Order> orderByList) method instead
216 public List getList(Class domainClass, String filter, String orderBy, Map additionalParams) {
217 return getListCommon(domainClass, filter, null, null, orderBy);
222 * This method may be vulnerable to SQL Injection attacks depending on the usage and is being deprecated. Please use
223 * getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
224 List<Order> orderByList) method instead
228 public List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy,
229 Map additionalParams) {
230 return getListCommon(domainClass, filter, new Integer(fromIndex), new Integer(toIndex), orderBy);
234 public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
235 List<Order> orderByList) {
237 Session session = sessionFactory.getCurrentSession();
239 Criteria criteria = session.createCriteria(domainClass);
241 if (projectionsList != null) {
242 criteria.setProjection(projectionsList);
245 if (restrictionsList != null && !restrictionsList.isEmpty()) {
246 for (Criterion criterion : restrictionsList)
247 criteria.add(criterion);
250 if (orderByList != null && !orderByList.isEmpty()) {
251 for (Order order : orderByList)
252 criteria.addOrder(order);
255 return criteria.list();
259 public List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy,
260 Map additionalParams) {
261 if (logger.isInfoEnabled())
262 logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list...");
263 String dbOrderByCol = dbOrderBy;
265 Session session = sessionFactory.getCurrentSession();
267 // default the orderBy if null
268 if (Utilities.nvl(dbOrderBy).length() == 0) {
269 dbOrderByCol = dbLabelCol;
270 dbOrderBy = dbLabelCol;
271 } else if (dbOrderBy.lastIndexOf(" ") > -1) {
272 dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" "));
275 StringBuilder sql = new StringBuilder();
276 sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ")
277 .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ")
278 .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ")
283 list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list();
284 } catch (Exception e) {
285 logger.error(EELFLoggerDelegate.errorLogger, "getLookupList failed on query query [" + sql + "]", e);
291 * methods accepting a Map of additional params to passed to the DAO (for
292 * extensibility, just in case)
296 public List executeSQLQuery(String sql, Class domainClass, Map additionalParams) {
297 return executeSQLQuery(sql, domainClass, null, null, additionalParams);
301 public List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,
302 Map additionalParams) {
303 Session session = sessionFactory.getCurrentSession();
305 SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass);
307 if (fromIndex != null && toIndex != null) {
308 query.setFirstResult(fromIndex.intValue());
309 int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
310 query.setMaxResults(pageSize);
317 public List executeQuery(String sql, Map additionalParams) {
318 return executeQuery(sql, null, null, additionalParams);
322 public List executeQuery(String sql, Integer fromIndex, Integer toIndex, Map additionalParams) {
323 Session session = sessionFactory.getCurrentSession();
325 Query query = session.createQuery(sql);
327 if (fromIndex != null && toIndex != null) {
328 query.setFirstResult(fromIndex.intValue());
329 int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
330 query.setMaxResults(pageSize);
337 public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, Map additionalParams) {
338 return executeNamedQuery(queryName, null, fromIndex, toIndex, additionalParams);
342 public List executeNamedQuery(String queryName, Map params, Map additionalParams) {
343 return executeNamedQuery(queryName, params, null, null, additionalParams);
347 public List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex,
348 Map additionalParams) {
349 Session session = sessionFactory.getCurrentSession();
350 Query query = session.getNamedQuery(queryName);
351 bindQueryParameters(query, params);
352 if (fromIndex != null && toIndex != null) {
353 query.setFirstResult(fromIndex.intValue());
354 int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
355 query.setMaxResults(pageSize);
361 * Stores parameters into the query using String keys from the map. Gives
362 * special treatment to map values of Collection and array type.
365 * Query with parameters
367 * Map of String to Object.
369 private void bindQueryParameters(Query query, Map params) {
370 if (params != null) {
371 for (Iterator i = params.entrySet().iterator(); i.hasNext();) {
372 Map.Entry entry = (Map.Entry) i.next();
373 Object parameterValue = entry.getValue();
374 if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) {
375 query.setParameter((String) entry.getKey(), parameterValue);
376 } else if (parameterValue instanceof Collection) {
377 query.setParameterList((String) entry.getKey(), (Collection) parameterValue);
378 } else if (parameterValue instanceof Object[]) {
379 query.setParameterList((String) entry.getKey(), (Object[]) parameterValue);
381 logger.error(EELFLoggerDelegate.errorLogger, "bindQueryParameters: no match for value {}",
388 // With Where Clause & RAPTOR's ZK
391 public List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String orderBy, boolean asc,
392 Integer fromIndex, Integer toIndex, Map additionalParams) {
393 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
394 throw new UnsupportedOperationException();
398 public List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) {
399 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
400 throw new UnsupportedOperationException();
404 public List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex,
405 Integer toIndex, Map additionalParams) {
406 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
407 throw new UnsupportedOperationException();
411 public List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params,
412 String orderBy, boolean asc, Integer fromIndex, Integer toIndex, Map additionalParams) {
413 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
414 throw new UnsupportedOperationException();
418 public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
419 List<Order> orderByList, Map<String, FetchMode> fetchModeMap) {
420 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
421 throw new UnsupportedOperationException();
425 public int executeUpdateQuery(String sql, Map additionalParams) {
426 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
427 throw new UnsupportedOperationException();
431 public int executeNamedUpdateQuery(String queryName, Map params, Map additionalParams) {
432 Session session = sessionFactory.getCurrentSession();
433 Query query = session.getNamedQuery(queryName);
434 bindQueryParameters(query,params);
435 return query.executeUpdate();
439 public void synchronize(Map additionalParams) {
440 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
441 throw new UnsupportedOperationException();