Fix Reference Key columns persistence issue in db
[policy/models.git] / models-dao / src / main / java / org / onap / policy / models / dao / impl / DefaultPfDao.java
index 0b32b51..ef86c17 100644 (file)
@@ -1,7 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
- *  Copyright (C) 2019-2020 Nordix Foundation.
- *  Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ *  Copyright (C) 2019-2021 Nordix Foundation.
+ *  Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.models.dao.impl;
 
+import java.sql.Timestamp;
+import java.time.Instant;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Date;
 import java.util.List;
 import java.util.Map;
-
 import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
 import javax.persistence.Persistence;
 import javax.persistence.TypedQuery;
 import javax.ws.rs.core.Response;
-
 import org.onap.policy.models.base.PfConcept;
 import org.onap.policy.models.base.PfConceptKey;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.base.PfModelRuntimeException;
 import org.onap.policy.models.base.PfReferenceKey;
+import org.onap.policy.models.base.PfReferenceTimestampKey;
 import org.onap.policy.models.base.PfTimestampKey;
 import org.onap.policy.models.base.PfUtils;
 import org.onap.policy.models.dao.DaoParameters;
@@ -79,6 +79,8 @@ public class DefaultPfDao implements PfDao {
     private static final String PARENT_VERSION_FILTER  = "c.key.parentKeyVersion = :parentversion";
     private static final String LOCAL_NAME_FILTER      = "c.key.localName = :localname";
 
+    private static final String PARENT_NAME_REF_FILTER     = "c.key.referenceKey.parentKeyName = :parentKeyName";
+
     private static final String CLONE_ERR_MSG = "Could not clone object of class \"{}\"";
 
     private static final String DELETE_BY_CONCEPT_KEY =
@@ -93,6 +95,9 @@ public class DefaultPfDao implements PfDao {
     private static final String SELECT_ALL_FOR_PARENT =
             SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER;
 
+    private static final String SELECT_ALL_VERSIONS_FOR_PARENT =
+            SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER;
+
     private static final String SELECT_ALL_VERSIONS = SELECT_FROM_TABLE + WHERE + NAME_FILTER;
 
     private static final String SELECT_BY_CONCEPT_KEY =
@@ -354,7 +359,7 @@ public class DefaultPfDao implements PfDao {
 
     @Override
     public <T extends PfConcept> List<T> getFiltered(final Class<T> someClass, final String name, final String version,
-            final Date startTime, final Date endTime, final Map<String, Object> filterMap, final String sortOrder,
+            final Instant startTime, final Instant endTime, final Map<String, Object> filterMap, final String sortOrder,
             final int getRecordNum) {
         final EntityManager mg = getEntityManager();
 
@@ -364,7 +369,8 @@ public class DefaultPfDao implements PfDao {
             if (filterMap != null) {
                 filterQueryString = buildFilter(filterMap, filterQueryString);
             }
-            filterQueryString = addKeyFilterString(filterQueryString, name, startTime, endTime);
+            filterQueryString = addKeyFilterString(filterQueryString, name, startTime, endTime,
+                isRefTimestampKey(someClass));
             if (getRecordNum > 0) {
                 filterQueryString += ORDER + " c.key.timeStamp " + sortOrder;
             }
@@ -376,31 +382,49 @@ public class DefaultPfDao implements PfDao {
                 }
             }
             if (name != null) {
-                query.setParameter("name", name);
+                if (isRefTimestampKey(someClass)) {
+                    query.setParameter("parentKeyName", name);
+                } else {
+                    query.setParameter("name", name);
+                }
             }
             if (startTime != null) {
                 if (endTime != null) {
-                    query.setParameter("startTime", startTime);
-                    query.setParameter("endTime", endTime);
+                    query.setParameter("startTime", Timestamp.from(startTime));
+                    query.setParameter("endTime", Timestamp.from(endTime));
                 } else {
-                    query.setParameter("startTime", startTime);
+                    query.setParameter("startTime", Timestamp.from(startTime));
                 }
             } else {
                 if (endTime != null) {
-                    query.setParameter("endTime", endTime);
+                    query.setParameter("endTime", Timestamp.from(endTime));
                 }
             }
             if (getRecordNum > 0) {
                 query.setMaxResults(getRecordNum);
             }
 
-            LOGGER.error("filterQueryString is  \"{}\"", filterQueryString);
+            LOGGER.debug("filterQueryString is  \"{}\"", filterQueryString);
             return query.getResultList();
-        } finally {
+        }  finally {
             mg.close();
         }
     }
 
+    /**
+     * This method checks if the class invoking the DAO is using PfReferenceTimestamp Key.
+     * @param someClass class that invoked Dao
+     * @return true if the key is PfReferenceTimestampKey.
+     */
+    private <T extends PfConcept> boolean isRefTimestampKey(final Class<T> someClass) {
+        try {
+            return PfReferenceTimestampKey.class.isAssignableFrom(someClass.getDeclaredField("key").getType());
+        } catch (NoSuchFieldException e) {
+            LOGGER.error("Error verifying the key for reference timestamp:", e);
+            return false;
+        }
+    }
+
     private String buildFilter(final Map<String, Object> filterMap, String filterQueryString) {
         StringBuilder bld = new StringBuilder(filterQueryString);
         for (String key : filterMap.keySet()) {
@@ -424,6 +448,11 @@ public class DefaultPfDao implements PfDao {
         return genericGet(someClass, key);
     }
 
+    @Override
+    public <T extends PfConcept> T get(final Class<T> someClass, final PfReferenceTimestampKey key) {
+        return genericGet(someClass, key);
+    }
+
     private <T extends PfConcept> T genericGet(final Class<T> someClass, final Object key) {
         if (someClass == null) {
             return null;
@@ -471,6 +500,23 @@ public class DefaultPfDao implements PfDao {
         }
     }
 
+    @Override
+    public <T extends PfConcept> List<T> getAllVersionsByParent(final Class<T> someClass, final String parentKeyName) {
+        if (someClass == null || parentKeyName == null) {
+            return Collections.emptyList();
+        }
+        final EntityManager mg = getEntityManager();
+        try {
+            // @formatter:off
+            return mg.createQuery(setQueryTable(SELECT_ALL_VERSIONS_FOR_PARENT, someClass), someClass)
+                    .setParameter(PARENT_NAME, parentKeyName)
+                    .getResultList();
+            // @formatter:on
+        } finally {
+            mg.close();
+        }
+    }
+
     @Override
     public <T extends PfConcept> List<T> getAllVersions(final Class<T> someClass, final String conceptName) {
         if (someClass == null || conceptName == null) {
@@ -554,11 +600,7 @@ public class DefaultPfDao implements PfDao {
         final EntityManager mg = getEntityManager();
         long size = 0;
         try {
-            /*
-             * Concatenation should be safe because the class name should be safe, thus
-             * disabling sonar.
-             */
-            size = mg.createQuery("SELECT COUNT(c) FROM " + someClass.getSimpleName() + " c", Long.class)   // NOSONAR
+            size = mg.createQuery("SELECT COUNT(c) FROM " + someClass.getSimpleName() + " c", Long.class)
                     .getSingleResult();
         } finally {
             mg.close();
@@ -604,25 +646,31 @@ public class DefaultPfDao implements PfDao {
      *        timeStamp <= endTime. null for ignore start time.
      * @param endTime the end timeStamp to filter from database, filter rule: startTime <= filteredRecord timeStamp <=
      *        endTime. null for ignore end time
+     * @param isRefTimestampKey boolean value, set to true if the query invoked for pfReferenceTimestampKey
      * @return the filter string to query database
      */
-    private String addKeyFilterString(String inputFilterString, final String name, final Date startTime,
-            final Date endTime) {
+    private String addKeyFilterString(String inputFilterString, final String name, final Instant startTime,
+            final Instant endTime, final boolean isRefTimestampKey) {
         String filterQueryString;
+        String inputFilter = inputFilterString;
         if (name != null) {
-            inputFilterString += NAME_FILTER + AND;
+            if (isRefTimestampKey) {
+                inputFilter += PARENT_NAME_REF_FILTER + AND;
+            } else {
+                inputFilter += NAME_FILTER + AND;
+            }
         }
         if (startTime != null) {
             if (endTime != null) {
-                filterQueryString = inputFilterString + TIMESTAMP_START_FILTER + AND + TIMESTAMP_END_FILTER;
+                filterQueryString = inputFilter + TIMESTAMP_START_FILTER + AND + TIMESTAMP_END_FILTER;
             } else {
-                filterQueryString = inputFilterString + TIMESTAMP_START_FILTER;
+                filterQueryString = inputFilter + TIMESTAMP_START_FILTER;
             }
         } else {
             if (endTime != null) {
-                filterQueryString = inputFilterString + TIMESTAMP_END_FILTER;
+                filterQueryString = inputFilter + TIMESTAMP_END_FILTER;
             } else {
-                filterQueryString = inputFilterString.substring(0, inputFilterString.length() - AND.length());
+                filterQueryString = inputFilter.substring(0, inputFilter.length() - AND.length());
             }
         }