2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021, 2023 Nordix Foundation.
4 * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.models.dao.impl;
24 import jakarta.persistence.EntityManager;
25 import jakarta.persistence.Persistence;
26 import jakarta.persistence.TypedQuery;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
30 import lombok.RequiredArgsConstructor;
31 import org.apache.commons.lang3.StringUtils;
32 import org.onap.policy.models.base.PfConcept;
33 import org.onap.policy.models.base.PfConceptKey;
34 import org.onap.policy.models.base.PfModelException;
35 import org.onap.policy.models.base.PfReferenceKey;
36 import org.onap.policy.models.base.PfReferenceTimestampKey;
37 import org.onap.policy.models.base.PfTimestampKey;
38 import org.onap.policy.models.base.PfUtils;
39 import org.onap.policy.models.dao.DaoParameters;
40 import org.onap.policy.models.dao.PfDao;
41 import org.onap.policy.models.dao.PfFilter;
42 import org.onap.policy.models.dao.PfFilterFactory;
43 import org.onap.policy.models.dao.PfFilterParametersIntfc;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * The Class ProxyDao is an JPA implementation of the {@link ProxyDao} class for Policy Framework concepts
49 * ({@link PfConcept}). It uses the default JPA implementation in the jakarta {@link Persistence} class.
51 @RequiredArgsConstructor
52 public class ProxyDao implements PfDao {
53 private static final Logger LOGGER = LoggerFactory.getLogger(ProxyDao.class);
56 private static final String NAME = "name";
57 private static final String VERSION = "version";
58 private static final String TIMESTAMP = "timeStamp";
59 private static final String PARENT_NAME = "parentname";
60 private static final String PARENT_VERSION = "parentversion";
61 private static final String LOCAL_NAME = "localname";
63 private static final String TABLE_TOKEN = "__TABLE__";
65 private static final String DELETE_FROM_TABLE = "DELETE FROM __TABLE__ c";
67 private static final String SELECT_FROM_TABLE = "SELECT c FROM __TABLE__ c";
69 private static final String WHERE = " WHERE ";
70 private static final String AND = " AND ";
71 private static final String ORDER_BY = " ORDER BY c.";
73 private static final String NAME_FILTER = "c.key.name = :name";
74 private static final String VERSION_FILTER = "c.key.version = :version";
75 private static final String TIMESTAMP_FILTER = "c.key.timeStamp = :timeStamp";
76 private static final String PARENT_NAME_FILTER = "c.key.parentKeyName = :parentname";
77 private static final String PARENT_VERSION_FILTER = "c.key.parentKeyVersion = :parentversion";
78 private static final String LOCAL_NAME_FILTER = "c.key.localName = :localname";
80 private static final String CLONE_ERR_MSG = "Could not clone object of class \"{}\"";
82 private static final String DELETE_BY_CONCEPT_KEY =
83 DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER;
85 private static final String DELETE_BY_TIMESTAMP_KEY =
86 DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + TIMESTAMP_FILTER;
88 private static final String DELETE_BY_REFERENCE_KEY =
89 DELETE_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER;
91 private static final String SELECT_ALL_FOR_PARENT =
92 SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER;
94 private static final String SELECT_ALL_VERSIONS_FOR_PARENT =
95 SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER;
97 private static final String SELECT_ALL_VERSIONS = SELECT_FROM_TABLE + WHERE + NAME_FILTER;
99 private static final String SELECT_BY_CONCEPT_KEY =
100 SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER;
102 private static final String SELECT_BY_REFERENCE_KEY =
103 SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER;
106 // Entity manager for JPA
107 private final EntityManager mg;
110 public void init(final DaoParameters daoParameters) throws PfModelException {
111 // Entity manager for JPA should be created at Service level
115 public final void close() {
116 // Entity manager for JPA should be close at Service level
120 public <T extends PfConcept> void create(final T obj) {
129 public <T extends PfConcept> void delete(final T obj) {
133 mg.remove(mg.contains(obj) ? obj : mg.merge(obj));
137 public <T extends PfConcept> void delete(final Class<T> someClass, final PfConceptKey key) {
142 mg.createQuery(setQueryTable(DELETE_BY_CONCEPT_KEY, someClass), someClass)
143 .setParameter(NAME, key.getName())
144 .setParameter(VERSION, key.getVersion())
150 public <T extends PfConcept> void delete(final Class<T> someClass, final PfReferenceKey key) {
155 mg.createQuery(setQueryTable(DELETE_BY_REFERENCE_KEY, someClass), someClass)
156 .setParameter(PARENT_NAME, key.getParentKeyName())
157 .setParameter(PARENT_VERSION, key.getParentKeyVersion())
158 .setParameter(LOCAL_NAME, key.getLocalName())
164 public <T extends PfConcept> void delete(final Class<T> someClass, final PfTimestampKey key) {
170 mg.createQuery(setQueryTable(DELETE_BY_TIMESTAMP_KEY, someClass), someClass)
171 .setParameter(NAME, key.getName())
172 .setParameter(VERSION, key.getVersion())
173 .setParameter(TIMESTAMP, key.getTimeStamp())
179 public <T extends PfConcept> void createCollection(final Collection<T> objs) {
180 if (objs == null || objs.isEmpty()) {
184 for (final T t : objs) {
190 public <T extends PfConcept> void deleteCollection(final Collection<T> objs) {
191 if (objs == null || objs.isEmpty()) {
195 for (final T t : objs) {
196 mg.remove(mg.contains(t) ? t : mg.merge(t));
201 public <T extends PfConcept> int deleteByConceptKey(final Class<T> someClass, final Collection<PfConceptKey> keys) {
202 if (keys == null || keys.isEmpty()) {
205 var deletedCount = 0;
207 for (final PfConceptKey key : keys) {
209 deletedCount += mg.createQuery(setQueryTable(DELETE_BY_CONCEPT_KEY, someClass), someClass)
210 .setParameter(NAME, key.getName())
211 .setParameter(VERSION, key.getVersion())
220 public <T extends PfConcept> int deleteByReferenceKey(final Class<T> someClass,
221 final Collection<PfReferenceKey> keys) {
222 if (keys == null || keys.isEmpty()) {
225 var deletedCount = 0;
227 for (final PfReferenceKey key : keys) {
229 deletedCount += mg.createQuery(setQueryTable(DELETE_BY_REFERENCE_KEY, someClass), someClass)
230 .setParameter(PARENT_NAME, key.getParentKeyName())
231 .setParameter(PARENT_VERSION, key.getParentKeyVersion())
232 .setParameter(LOCAL_NAME, key.getLocalName())
240 public <T extends PfConcept> void deleteAll(final Class<T> someClass) {
241 mg.createQuery(setQueryTable(DELETE_FROM_TABLE, someClass), someClass).executeUpdate();
245 public <T extends PfConcept> List<T> getFiltered(final Class<T> someClass, final String name,
246 final String version) {
248 return getAll(someClass);
251 if (version == null) {
252 return getAllVersions(someClass, name);
255 var foundConcept = get(someClass, new PfConceptKey(name, version));
257 return (foundConcept == null ? Collections.emptyList() : Collections.singletonList(foundConcept));
261 public <T extends PfConcept> List<T> getFiltered(final Class<T> someClass, PfFilterParametersIntfc filterParams) {
263 PfFilter filter = new PfFilterFactory().createFilter(someClass);
264 var filterQueryString =
265 SELECT_FROM_TABLE + filter.genWhereClause(filterParams) + filter.genOrderClause(filterParams);
267 TypedQuery<T> query = mg.createQuery(setQueryTable(filterQueryString, someClass), someClass);
268 filter.setParams(query, filterParams);
270 LOGGER.debug("filterQueryString is \"{}\"", filterQueryString);
271 return query.getResultList();
275 public <T extends PfConcept> T get(final Class<T> someClass, final PfConceptKey key) {
276 return genericGet(someClass, key);
280 public <T extends PfConcept> T get(final Class<T> someClass, final PfReferenceKey key) {
281 return genericGet(someClass, key);
285 public <T extends PfConcept> T get(final Class<T> someClass, final PfTimestampKey key) {
286 return genericGet(someClass, key);
290 public <T extends PfConcept> T get(final Class<T> someClass, final PfReferenceTimestampKey key) {
291 return genericGet(someClass, key);
294 private <T extends PfConcept> T genericGet(final Class<T> someClass, final Object key) {
295 if (someClass == null) {
299 final var t = mg.find(someClass, key);
300 return checkAndReturn(someClass, t);
304 public <T extends PfConcept> List<T> getAll(final Class<T> someClass) {
305 if (someClass == null) {
306 return Collections.emptyList();
309 return mg.createQuery(setQueryTable(SELECT_FROM_TABLE, someClass), someClass).getResultList();
313 public <T extends PfConcept> List<T> getAll(final Class<T> someClass, final PfConceptKey parentKey) {
314 if (someClass == null) {
315 return Collections.emptyList();
319 return mg.createQuery(setQueryTable(SELECT_ALL_FOR_PARENT, someClass), someClass)
320 .setParameter(PARENT_NAME, parentKey.getName())
321 .setParameter(PARENT_VERSION, parentKey.getVersion())
327 public <T extends PfConcept> List<T> getAll(Class<T> someClass, String orderBy, Integer numRecords) {
329 if (someClass == null) {
330 return Collections.emptyList();
333 String query = setQueryTable(SELECT_FROM_TABLE, someClass);
335 if (StringUtils.isNotBlank(orderBy)) {
336 query = query.concat(ORDER_BY).concat(orderBy);
339 return mg.createQuery(query, someClass).setMaxResults(numRecords).getResultList();
343 public <T extends PfConcept> List<T> getAllVersionsByParent(final Class<T> someClass, final String parentKeyName) {
344 if (someClass == null || parentKeyName == null) {
345 return Collections.emptyList();
349 return mg.createQuery(setQueryTable(SELECT_ALL_VERSIONS_FOR_PARENT, someClass), someClass)
350 .setParameter(PARENT_NAME, parentKeyName)
356 public <T extends PfConcept> List<T> getAllVersions(final Class<T> someClass, final String conceptName) {
357 if (someClass == null || conceptName == null) {
358 return Collections.emptyList();
362 return mg.createQuery(setQueryTable(SELECT_ALL_VERSIONS, someClass), someClass)
363 .setParameter(NAME, conceptName)
369 public <T extends PfConcept> T getConcept(final Class<T> someClass, final PfConceptKey key) {
370 if (someClass == null || key == null) {
375 var ret = mg.createQuery(setQueryTable(SELECT_BY_CONCEPT_KEY, someClass), someClass)
376 .setParameter(NAME, key.getName())
377 .setParameter(VERSION, key.getVersion())
381 return getSingleResult(someClass, key.getId(), ret);
385 public <T extends PfConcept> T getConcept(final Class<T> someClass, final PfReferenceKey key) {
386 if (someClass == null || key == null) {
391 var ret = mg.createQuery(setQueryTable(SELECT_BY_REFERENCE_KEY, someClass), someClass)
392 .setParameter(PARENT_NAME, key.getParentKeyName())
393 .setParameter(PARENT_VERSION, key.getParentKeyVersion())
394 .setParameter(LOCAL_NAME, key.getLocalName())
398 return getSingleResult(someClass, key.getId(), ret);
402 public <T extends PfConcept> T update(final T obj) {
403 var ret = mg.merge(obj);
409 public <T extends PfConcept> long size(final Class<T> someClass) {
410 if (someClass == null) {
416 * The invoking code only passes well-known classes into this method, thus
417 * disabling the sonar about SQL injection.
419 size = mg.createQuery("SELECT COUNT(c) FROM " + someClass.getSimpleName() + " c", Long.class) // NOSONAR
425 * Add the table to a query string.
427 * @param queryString the query string
428 * @param tableClass the class name of the table
429 * @return the updated query string
431 private <T extends PfConcept> String setQueryTable(final String queryString, final Class<T> tableClass) {
432 return queryString.replace(TABLE_TOKEN, tableClass.getSimpleName());
436 * Check that a query returned one and only one entry and return that entry.
438 * @param someClass the class being searched for
439 * @param searchFilter the search filter
440 * @param resultList the result list returned by the query
441 * @return the single unique result
443 private <T extends PfConcept> T getSingleResult(final Class<T> someClass, final String searchFilter,
444 List<T> resultList) {
445 if (resultList == null || resultList.isEmpty()) {
448 if (resultList.size() > 1) {
449 throw new IllegalArgumentException("More than one result was returned query on " + someClass
450 + " with filter " + searchFilter + ": " + resultList);
452 return resultList.get(0);
456 * check the result get from database and return the object.
458 * @param <T> the type of the object to get, a subclass of {@link PfConcept}
459 * @param someClass the class of the object to get, a subclass of {@link PfConcept}
460 * @param objToCheck the object that was retrieved from the database
461 * @return the checked object or null
463 private <T extends PfConcept> T checkAndReturn(final Class<T> someClass, final T objToCheck) {
464 if (objToCheck != null) {
466 return PfUtils.makeCopy(objToCheck);
467 } catch (final Exception e) {
468 LOGGER.warn(CLONE_ERR_MSG, someClass.getName(), e);