2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 Nordix Foundation.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.models.dao.impl;
23 import java.sql.Timestamp;
24 import java.time.Instant;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
28 import javax.persistence.EntityManager;
29 import javax.persistence.Persistence;
30 import javax.persistence.TypedQuery;
31 import lombok.RequiredArgsConstructor;
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.policy.models.base.PfConcept;
34 import org.onap.policy.models.base.PfConceptKey;
35 import org.onap.policy.models.base.PfGeneratedIdKey;
36 import org.onap.policy.models.base.PfModelException;
37 import org.onap.policy.models.base.PfReferenceKey;
38 import org.onap.policy.models.base.PfReferenceTimestampKey;
39 import org.onap.policy.models.base.PfTimestampKey;
40 import org.onap.policy.models.base.PfUtils;
41 import org.onap.policy.models.dao.DaoParameters;
42 import org.onap.policy.models.dao.PfDao;
43 import org.onap.policy.models.dao.PfFilter;
44 import org.onap.policy.models.dao.PfFilterFactory;
45 import org.onap.policy.models.dao.PfFilterParametersIntfc;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * The Class ProxyDao is an JPA implementation of the {@link ProxyDao} class for Policy Framework concepts
51 * ({@link PfConcept}). It uses the default JPA implementation in the javax {@link Persistence} class.
53 @RequiredArgsConstructor
54 public class ProxyDao implements PfDao {
55 private static final Logger LOGGER = LoggerFactory.getLogger(ProxyDao.class);
58 private static final String NAME = "name";
59 private static final String VERSION = "version";
60 private static final String TIMESTAMP = "timeStamp";
61 private static final String GENERATEDID = "Id";
62 private static final String PARENT_NAME = "parentname";
63 private static final String PARENT_VERSION = "parentversion";
64 private static final String LOCAL_NAME = "localname";
66 private static final String TABLE_TOKEN = "__TABLE__";
68 private static final String DELETE_FROM_TABLE = "DELETE FROM __TABLE__ c";
70 private static final String SELECT_FROM_TABLE = "SELECT c FROM __TABLE__ c";
72 private static final String WHERE = " WHERE ";
73 private static final String AND = " AND ";
74 private static final String ORDER_BY = " ORDER BY c.";
76 private static final String NAME_FILTER = "c.key.name = :name";
77 private static final String VERSION_FILTER = "c.key.version = :version";
78 private static final String TIMESTAMP_FILTER = "c.key.timeStamp = :timeStamp";
79 private static final String TIMESTAMP_FILTER_NOKEY = "c.timeStamp = :timeStamp";
80 private static final String GENERATED_ID_FILTER = "c.key.generatedId = :Id";
81 private static final String PARENT_NAME_FILTER = "c.key.parentKeyName = :parentname";
82 private static final String PARENT_VERSION_FILTER = "c.key.parentKeyVersion = :parentversion";
83 private static final String LOCAL_NAME_FILTER = "c.key.localName = :localname";
85 private static final String CLONE_ERR_MSG = "Could not clone object of class \"{}\"";
87 private static final String DELETE_BY_CONCEPT_KEY =
88 DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER;
90 private static final String DELETE_BY_TIMESTAMP_KEY =
91 DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + TIMESTAMP_FILTER;
93 private static final String DELETE_BY_GENERATED_ID_KEY =
94 DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + GENERATED_ID_FILTER;
96 private static final String DELETE_BY_REFERENCE_KEY =
97 DELETE_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER;
99 private static final String SELECT_ALL_FOR_PARENT =
100 SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER;
102 private static final String SELECT_ALL_VERSIONS_FOR_PARENT =
103 SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER;
105 private static final String SELECT_ALL_VERSIONS = SELECT_FROM_TABLE + WHERE + NAME_FILTER;
107 private static final String SELECT_BY_CONCEPT_KEY =
108 SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER;
110 private static final String SELECT_BY_TIMESTAMP_NOKEY =
111 SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + TIMESTAMP_FILTER_NOKEY;
113 private static final String SELECT_BY_REFERENCE_KEY =
114 SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER;
117 // Entity manager for JPA
118 private final EntityManager mg;
121 public void init(final DaoParameters daoParameters) throws PfModelException {
122 // Entity manager for JPA should be created at Service level
126 public final void close() {
127 // Entity manager for JPA should be close at Service level
131 public <T extends PfConcept> void create(final T obj) {
140 public <T extends PfConcept> void delete(final T obj) {
144 mg.remove(mg.contains(obj) ? obj : mg.merge(obj));
148 public <T extends PfConcept> void delete(final Class<T> someClass, final PfConceptKey key) {
153 mg.createQuery(setQueryTable(DELETE_BY_CONCEPT_KEY, someClass), someClass)
154 .setParameter(NAME, key.getName())
155 .setParameter(VERSION, key.getVersion())
161 public <T extends PfConcept> void delete(final Class<T> someClass, final PfReferenceKey key) {
166 mg.createQuery(setQueryTable(DELETE_BY_REFERENCE_KEY, someClass), someClass)
167 .setParameter(PARENT_NAME, key.getParentKeyName())
168 .setParameter(PARENT_VERSION, key.getParentKeyVersion())
169 .setParameter(LOCAL_NAME, key.getLocalName())
175 public <T extends PfConcept> void delete(final Class<T> someClass, final PfTimestampKey key) {
181 mg.createQuery(setQueryTable(DELETE_BY_TIMESTAMP_KEY, someClass), someClass)
182 .setParameter(NAME, key.getName())
183 .setParameter(VERSION, key.getVersion())
184 .setParameter(TIMESTAMP, key.getTimeStamp())
190 public <T extends PfConcept> void delete(final Class<T> someClass, final PfGeneratedIdKey key) {
196 mg.createQuery(setQueryTable(DELETE_BY_GENERATED_ID_KEY, someClass), someClass)
197 .setParameter(NAME, key.getName())
198 .setParameter(VERSION, key.getVersion())
199 .setParameter(GENERATEDID, key.getGeneratedId())
205 public <T extends PfConcept> void createCollection(final Collection<T> objs) {
206 if (objs == null || objs.isEmpty()) {
210 for (final T t : objs) {
216 public <T extends PfConcept> void deleteCollection(final Collection<T> objs) {
217 if (objs == null || objs.isEmpty()) {
221 for (final T t : objs) {
222 mg.remove(mg.contains(t) ? t : mg.merge(t));
227 public <T extends PfConcept> int deleteByConceptKey(final Class<T> someClass, final Collection<PfConceptKey> keys) {
228 if (keys == null || keys.isEmpty()) {
231 var deletedCount = 0;
233 for (final PfConceptKey key : keys) {
235 deletedCount += mg.createQuery(setQueryTable(DELETE_BY_CONCEPT_KEY, someClass), someClass)
236 .setParameter(NAME, key.getName())
237 .setParameter(VERSION, key.getVersion())
246 public <T extends PfConcept> int deleteByReferenceKey(final Class<T> someClass,
247 final Collection<PfReferenceKey> keys) {
248 if (keys == null || keys.isEmpty()) {
251 var deletedCount = 0;
253 for (final PfReferenceKey key : keys) {
255 deletedCount += mg.createQuery(setQueryTable(DELETE_BY_REFERENCE_KEY, someClass), someClass)
256 .setParameter(PARENT_NAME, key.getParentKeyName())
257 .setParameter(PARENT_VERSION, key.getParentKeyVersion())
258 .setParameter(LOCAL_NAME, key.getLocalName())
266 public <T extends PfConcept> void deleteAll(final Class<T> someClass) {
267 mg.createQuery(setQueryTable(DELETE_FROM_TABLE, someClass), someClass).executeUpdate();
271 public <T extends PfConcept> List<T> getFiltered(final Class<T> someClass, final String name,
272 final String version) {
274 return getAll(someClass);
277 if (version == null) {
278 return getAllVersions(someClass, name);
281 var foundConcept = get(someClass, new PfConceptKey(name, version));
283 return (foundConcept == null ? Collections.emptyList() : Collections.singletonList(foundConcept));
287 public <T extends PfConcept> List<T> getFiltered(final Class<T> someClass, PfFilterParametersIntfc filterParams) {
289 PfFilter filter = new PfFilterFactory().createFilter(someClass);
290 var filterQueryString =
291 SELECT_FROM_TABLE + filter.genWhereClause(filterParams) + filter.genOrderClause(filterParams);
293 TypedQuery<T> query = mg.createQuery(setQueryTable(filterQueryString, someClass), someClass);
294 filter.setParams(query, filterParams);
296 LOGGER.debug("filterQueryString is \"{}\"", filterQueryString);
297 return query.getResultList();
301 public <T extends PfConcept> T get(final Class<T> someClass, final PfConceptKey key) {
302 return genericGet(someClass, key);
306 public <T extends PfConcept> T get(final Class<T> someClass, final PfReferenceKey key) {
307 return genericGet(someClass, key);
311 public <T extends PfConcept> T get(final Class<T> someClass, final PfGeneratedIdKey key) {
312 return genericGet(someClass, key);
316 public <T extends PfConcept> T get(final Class<T> someClass, final PfTimestampKey key) {
317 return genericGet(someClass, key);
321 public <T extends PfConcept> T get(final Class<T> someClass, final PfReferenceTimestampKey key) {
322 return genericGet(someClass, key);
325 private <T extends PfConcept> T genericGet(final Class<T> someClass, final Object key) {
326 if (someClass == null) {
330 final var t = mg.find(someClass, key);
331 return checkAndReturn(someClass, t);
335 public <T extends PfConcept> List<T> getAll(final Class<T> someClass) {
336 if (someClass == null) {
337 return Collections.emptyList();
340 return mg.createQuery(setQueryTable(SELECT_FROM_TABLE, someClass), someClass).getResultList();
344 public <T extends PfConcept> List<T> getAll(final Class<T> someClass, final PfConceptKey parentKey) {
345 if (someClass == null) {
346 return Collections.emptyList();
350 return mg.createQuery(setQueryTable(SELECT_ALL_FOR_PARENT, someClass), someClass)
351 .setParameter(PARENT_NAME, parentKey.getName())
352 .setParameter(PARENT_VERSION, parentKey.getVersion())
358 public <T extends PfConcept> List<T> getAll(Class<T> someClass, String orderBy, Integer numRecords) {
360 if (someClass == null) {
361 return Collections.emptyList();
364 String query = setQueryTable(SELECT_FROM_TABLE, someClass);
366 if (StringUtils.isNotBlank(orderBy)) {
367 query = query.concat(ORDER_BY).concat(orderBy);
370 return mg.createQuery(query, someClass).setMaxResults(numRecords).getResultList();
374 public <T extends PfConcept> List<T> getAllVersionsByParent(final Class<T> someClass, final String parentKeyName) {
375 if (someClass == null || parentKeyName == null) {
376 return Collections.emptyList();
380 return mg.createQuery(setQueryTable(SELECT_ALL_VERSIONS_FOR_PARENT, someClass), someClass)
381 .setParameter(PARENT_NAME, parentKeyName)
387 public <T extends PfConcept> List<T> getAllVersions(final Class<T> someClass, final String conceptName) {
388 if (someClass == null || conceptName == null) {
389 return Collections.emptyList();
393 return mg.createQuery(setQueryTable(SELECT_ALL_VERSIONS, someClass), someClass)
394 .setParameter(NAME, conceptName)
400 public <T extends PfConcept> List<T> getByTimestamp(final Class<T> someClass, final PfGeneratedIdKey key,
401 final Instant timeStamp) {
402 if (someClass == null || key == null || timeStamp == null) {
403 return Collections.emptyList();
407 return mg.createQuery(setQueryTable(SELECT_BY_TIMESTAMP_NOKEY, someClass), someClass)
408 .setParameter(NAME, key.getName())
409 .setParameter(VERSION, key.getVersion())
410 .setParameter(TIMESTAMP, Timestamp.from(timeStamp))
416 public <T extends PfConcept> T getConcept(final Class<T> someClass, final PfConceptKey key) {
417 if (someClass == null || key == null) {
422 var ret = mg.createQuery(setQueryTable(SELECT_BY_CONCEPT_KEY, someClass), someClass)
423 .setParameter(NAME, key.getName())
424 .setParameter(VERSION, key.getVersion())
428 return getSingleResult(someClass, key.getId(), ret);
432 public <T extends PfConcept> T getConcept(final Class<T> someClass, final PfReferenceKey key) {
433 if (someClass == null || key == null) {
438 var ret = mg.createQuery(setQueryTable(SELECT_BY_REFERENCE_KEY, someClass), someClass)
439 .setParameter(PARENT_NAME, key.getParentKeyName())
440 .setParameter(PARENT_VERSION, key.getParentKeyVersion())
441 .setParameter(LOCAL_NAME, key.getLocalName())
445 return getSingleResult(someClass, key.getId(), ret);
449 public <T extends PfConcept> T update(final T obj) {
450 var ret = mg.merge(obj);
456 public <T extends PfConcept> long size(final Class<T> someClass) {
457 if (someClass == null) {
463 * The invoking code only passes well-known classes into this method, thus
464 * disabling the sonar about SQL injection.
466 size = mg.createQuery("SELECT COUNT(c) FROM " + someClass.getSimpleName() + " c", Long.class) // NOSONAR
472 * Add the table to a query string.
474 * @param queryString the query string
475 * @param tableClass the class name of the table
476 * @return the updated query string
478 private <T extends PfConcept> String setQueryTable(final String queryString, final Class<T> tableClass) {
479 return queryString.replace(TABLE_TOKEN, tableClass.getSimpleName());
483 * Check that a query returned one and only one entry and return that entry.
485 * @param someClass the class being searched for
486 * @param searchFilter the search filter
487 * @param resultList the result list returned by the query
488 * @return the single unique result
490 private <T extends PfConcept> T getSingleResult(final Class<T> someClass, final String searchFilter,
491 List<T> resultList) {
492 if (resultList == null || resultList.isEmpty()) {
495 if (resultList.size() > 1) {
496 throw new IllegalArgumentException("More than one result was returned query on " + someClass
497 + " with filter " + searchFilter + ": " + resultList);
499 return resultList.get(0);
503 * check the result get from database and return the object.
505 * @param <T> the type of the object to get, a subclass of {@link PfConcept}
506 * @param someClass the class of the object to get, a subclass of {@link PfConcept}
507 * @param objToCheck the object that was retrieved from the database
508 * @return the checked object or null
510 private <T extends PfConcept> T checkAndReturn(final Class<T> someClass, final T objToCheck) {
511 if (objToCheck != null) {
513 return PfUtils.makeCopy(objToCheck);
514 } catch (final Exception e) {
515 LOGGER.warn(CLONE_ERR_MSG, someClass.getName(), e);