pom, new modules changes
[portal/sdk.git] / ecomp-sdk / epsdk-core / src / main / java / org / onap / portalsdk / core / service / DataAccessServiceImpl.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
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
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
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
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
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.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalsdk.core.service;
39
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;
46 import java.util.Map;
47
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;
64
65 /**
66  * Provides implementations of methods in {@link DataAccessService}.
67  */
68 @SuppressWarnings("deprecation")
69 @Transactional
70 public class DataAccessServiceImpl extends FusionService implements DataAccessService {
71
72         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DataAccessServiceImpl.class);
73
74         @Autowired
75         private SessionFactory sessionFactory;
76
77         @Override
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);
83                 if (vo == null) {
84                         try {
85                                 vo = (DomainVo) domainClass.newInstance();
86                         } catch (Exception e) {
87                                 logger.error(EELFLoggerDelegate.errorLogger,
88                                                 "getDomainObject failed while instantiating class " + domainClass.getName(), e);
89                         }
90                 }
91                 return vo;
92         }
93
94         @Override
95         public void deleteDomainObject(DomainVo domainObject, Map additionalParams) {
96                 Session session = sessionFactory.getCurrentSession();
97                 session.delete(domainObject);
98         }
99
100         @Override
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();
107         }
108
109         @Override
110         public void saveDomainObject(DomainVo vo, Map additionalParams) {
111                 Integer userId = 1;
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();
118                         }
119                 }
120                 _update(vo, userId);
121         }
122
123         /**
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.
127          * 
128          * @param vo
129          * @param userId
130          *            Ignored if value is zero.
131          */
132         protected final void _update(DomainVo vo, int userId) {
133                 Date timestamp = new Date();
134
135                 Session session = sessionFactory.getCurrentSession();
136
137                 if (vo.getId() == null || vo.getId().intValue() == 0) { // add new
138                         vo.setCreated(timestamp);
139                         vo.setModified(timestamp);
140
141                         if (userId != 0
142                                         && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
143                                 vo.setCreatedId(new Long(userId));
144                                 vo.setModifiedId(new Long(userId));
145                         }
146                 } else { // update existing
147                         vo.setModified(timestamp);
148
149                         if (userId != 0
150                                         && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
151                                 vo.setModifiedId(new Long(userId));
152                         }
153                 }
154
155                 session.saveOrUpdate(vo);
156         }
157
158         /**
159          * generic get list method
160          * 
161          * @deprecated
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
165          * 
166          * @param domainClass
167          * @param filterClause
168          * @param fromIndex
169          * @param toIndex
170          * @param orderBy
171          * @return
172          */
173         @Deprecated
174         private List getListCommon(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex,
175                         String orderBy) {
176                 String className = domainClass.getName();
177                 Session session = sessionFactory.getCurrentSession();
178
179                 if (logger.isInfoEnabled()) {
180                         logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records"
181                                         + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "")
182                                         + "...");
183                         if (filterClause != null && filterClause.length() > 0)
184                                 logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause);
185                 }
186
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);
192
193                 return list;
194         }
195
196         /**
197           * @deprecated
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
201         */
202         @Override
203         @Deprecated
204         public List getList(Class domainClass, Map additionalParams) {
205                 return getListCommon(domainClass, null, null, null, null);
206         }
207
208          /**
209      * @deprecated
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
213      */
214         @Override
215         @Deprecated
216         public List getList(Class domainClass, String filter, String orderBy, Map additionalParams) {
217                 return getListCommon(domainClass, filter, null, null, orderBy);
218         }
219         
220         /**
221      * @deprecated
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
225      */
226         @Override
227         @Deprecated
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);
231         }
232
233         @Override
234         public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
235                         List<Order> orderByList) {
236
237                 Session session = sessionFactory.getCurrentSession();
238
239                 Criteria criteria = session.createCriteria(domainClass);
240
241                 if (projectionsList != null) {
242                         criteria.setProjection(projectionsList);
243                 }
244
245                 if (restrictionsList != null && !restrictionsList.isEmpty()) {
246                         for (Criterion criterion : restrictionsList)
247                                 criteria.add(criterion);
248                 }
249
250                 if (orderByList != null && !orderByList.isEmpty()) {
251                         for (Order order : orderByList)
252                                 criteria.addOrder(order);
253                 }
254
255                 return criteria.list();
256         }
257
258         @Override
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;
264
265                 Session session = sessionFactory.getCurrentSession();
266
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(" "));
273                 }
274
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 ")
279                                 .append(dbOrderBy);
280
281                 List list = null;
282                 try {
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);
286                 }
287                 return list;
288         }
289
290         /*
291          * methods accepting a Map of additional params to passed to the DAO (for
292          * extensibility, just in case)
293          */
294
295         @Override
296         public List executeSQLQuery(String sql, Class domainClass, Map additionalParams) {
297                 return executeSQLQuery(sql, domainClass, null, null, additionalParams);
298         }
299
300         @Override
301         public List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,
302                         Map additionalParams) {
303                 Session session = sessionFactory.getCurrentSession();
304
305                 SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass);
306
307                 if (fromIndex != null && toIndex != null) {
308                         query.setFirstResult(fromIndex.intValue());
309                         int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
310                         query.setMaxResults(pageSize);
311                 }
312
313                 return query.list();
314         }
315
316         @Override
317         public List executeQuery(String sql, Map additionalParams) {
318                 return executeQuery(sql, null, null, additionalParams);
319         }
320
321         @Override
322         public List executeQuery(String sql, Integer fromIndex, Integer toIndex, Map additionalParams) {
323                 Session session = sessionFactory.getCurrentSession();
324
325                 Query query = session.createQuery(sql);
326
327                 if (fromIndex != null && toIndex != null) {
328                         query.setFirstResult(fromIndex.intValue());
329                         int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
330                         query.setMaxResults(pageSize);
331                 }
332
333                 return query.list();
334         }
335
336         @Override
337         public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, Map additionalParams) {
338                 return executeNamedQuery(queryName, null, fromIndex, toIndex, additionalParams);
339         }
340
341         @Override
342         public List executeNamedQuery(String queryName, Map params, Map additionalParams) {
343                 return executeNamedQuery(queryName, params, null, null, additionalParams);
344         }
345
346         @Override
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);
356                 }
357                 return query.list();
358         }
359
360         /**
361          * Stores parameters into the query using String keys from the map. Gives
362          * special treatment to map values of Collection and array type.
363          * 
364          * @param query
365          *            Query with parameters
366          * @param params
367          *            Map of String to Object.
368          */
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);
380                                 } else {
381                                         logger.error(EELFLoggerDelegate.errorLogger, "bindQueryParameters: no match for value {}",
382                                                         parameterValue);
383                                 }
384                         }
385                 }
386         }
387
388         // With Where Clause & RAPTOR's ZK
389
390         @Override
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();
395         }
396
397         @Override
398         public List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) {
399                 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
400                 throw new UnsupportedOperationException();
401         }
402
403         @Override
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();
408         }
409
410         @Override
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();
415         }
416
417         @Override
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();
422         }
423
424         @Override
425         public int executeUpdateQuery(String sql, Map additionalParams) {
426                 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
427                 throw new UnsupportedOperationException();
428         }
429
430         @Override
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();
436         }
437
438         @Override
439         public void synchronize(Map additionalParams) {
440                 logger.error(EELFLoggerDelegate.errorLogger, "Not implemented");
441                 throw new UnsupportedOperationException();
442         }
443
444 }