diff options
Diffstat (limited to 'integrity-audit/src/main/java')
7 files changed, 343 insertions, 461 deletions
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java index 25335540..03fbdb57 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-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. @@ -22,7 +22,6 @@ package org.onap.policy.common.ia; import java.util.Collections; import java.util.Comparator; -import java.util.Date; import java.util.List; import java.util.Properties; import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; @@ -149,10 +148,12 @@ public class AuditThread extends Thread { */ runUntilInterrupted(); + } catch (InterruptedException e) { + handleAuditLoopException(e); + Thread.currentThread().interrupt(); + } catch (Exception e) { - String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + e.getMessage(); - logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); - integrityAudit.setThreadInitialized(false); + handleAuditLoopException(e); } dbDao.destroy(); @@ -160,16 +161,24 @@ public class AuditThread extends Thread { logger.info("AuditThread.run: Exiting"); } + private void handleAuditLoopException(Exception exception) { + String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + exception.getMessage(); + logger.error(MessageCodes.EXCEPTION_ERROR, exception, msg); + integrityAudit.setThreadInitialized(false); + } + private void runUntilInterrupted() throws InterruptedException { - boolean auditCompleted = false; + var auditCompleted = false; - DbAudit dbAudit = new DbAudit(dbDao); + var dbAudit = new DbAudit(dbDao); IntegrityAuditEntity entityCurrentlyDesignated; IntegrityAuditEntity thisEntity; integrityAudit.setThreadInitialized(true); // An exception will set it to false - while (true) { + var interrupted = false; + + while (!interrupted) { try { /* * It may have been awhile since we last cycled through this loop, so refresh @@ -208,16 +217,17 @@ public class AuditThread extends Thread { if (isInterruptedException(e)) { String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + "; Stopping."; logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); - break; - } + Thread.currentThread().interrupt(); + interrupted = true; - String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() - + "; Will try audit again in " + integrityAuditPeriodSeconds + " seconds"; - logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); - // Sleep and try again later - AuditorTime.getInstance().sleep(integrityAuditPeriodSeconds * 1000L); + } else { + String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + + "; Will try audit again in " + integrityAuditPeriodSeconds + " seconds"; + logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); + // Sleep and try again later + AuditorTime.getInstance().sleep(integrityAuditPeriodSeconds * 1000L); + } } - } } @@ -345,10 +355,10 @@ public class AuditThread extends Thread { IntegrityAuditEntity thisEntity = null; - int designatedEntityIndex = -1; - int entityIndex = 0; - int priorCandidateIndex = -1; - int subsequentCandidateIndex = -1; + var designatedEntityIndex = -1; + var entityIndex = 0; + var priorCandidateIndex = -1; + var subsequentCandidateIndex = -1; for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) { @@ -559,7 +569,7 @@ public class AuditThread extends Thread { */ List<IntegrityAuditEntity> integrityAuditEntityList = dbDao.getIntegrityAuditEntities(this.persistenceUnit, this.nodeType); - int listSize = integrityAuditEntityList.size(); + var listSize = integrityAuditEntityList.size(); if (logger.isDebugEnabled()) { logger.debug("getIntegrityAuditEntityList: Got " + listSize + " IntegrityAuditEntity records"); } @@ -632,10 +642,10 @@ public class AuditThread extends Thread { + integrityAuditEntity.getLastUpdated()); } - boolean stale = false; + var stale = false; - Date currentTime = AuditorTime.getInstance().getDate(); - Date lastUpdated = integrityAuditEntity.getLastUpdated(); + var currentTime = AuditorTime.getInstance().getDate(); + var lastUpdated = integrityAuditEntity.getLastUpdated(); /* * If lastUpdated is null, we assume that the audit never ran for that node. @@ -688,8 +698,8 @@ public class AuditThread extends Thread { long timeDifference; - Date currentTime = AuditorTime.getInstance().getDate(); - Date lastUpdated = thisEntity.getLastUpdated(); + var currentTime = AuditorTime.getInstance().getDate(); + var lastUpdated = thisEntity.getLastUpdated(); long lastUpdatedTime = lastUpdated.getTime(); timeDifference = currentTime.getTime() - lastUpdatedTime; diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java index 95eecbc3..5bfedaac 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,11 +21,14 @@ package org.onap.policy.common.ia; import java.util.function.Supplier; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; import org.onap.policy.common.utils.time.CurrentTime; /** * "Current" time used by IntegrityMonitor classes. */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class AuditorTime { /** @@ -41,15 +44,8 @@ public class AuditorTime { private static Supplier<CurrentTime> supplier = () -> currentTime; /** - * Constructor. - */ - private AuditorTime() { - super(); - } - - /** * Get instance. - * + * * @return the CurrentTime singleton */ public static CurrentTime getInstance() { diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java index 4e718a60..22ffa08e 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java @@ -1,8 +1,9 @@ -/* +/*-- * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +21,7 @@ package org.onap.policy.common.ia; +import jakarta.persistence.Table; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; @@ -29,7 +31,6 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; -import javax.persistence.Table; import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.builder.RecursiveToStringStyle; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; @@ -60,16 +61,11 @@ public class DbAudit { */ public DbAudit(DbDao dbDao) { - if (logger.isDebugEnabled()) { - logger.debug("Constructor: Entering"); - } + logger.debug("Constructor: Entering"); this.dbDao = dbDao; - if (logger.isDebugEnabled()) { - logger.debug("Constructor: Exiting"); - } - + logger.debug("Constructor: Exiting"); } /** @@ -128,7 +124,7 @@ public class DbAudit { * nodes. Since the audit is run in a round-robin, every instance will be compared against * every other instance. */ - IntegrityAuditEntity myIae = dbDao.getMyIntegrityAuditEntity(); + var myIae = dbDao.getMyIntegrityAuditEntity(); if (myIae == null) { @@ -153,8 +149,6 @@ public class DbAudit { if (logger.isDebugEnabled()) { logger.debug("dbAudit: Exiting"); } - - return; // all done } private void compareList(String persistenceUnit, List<IntegrityAuditEntity> iaeList, IntegrityAuditEntity myIae, @@ -181,22 +175,8 @@ public class DbAudit { compareMineWithTheirs(persistenceUnit, iaeList, myIae, misMatchedMap, clazzName, myEntries); // Time check - if ((AuditorTime.getInstance().getMillis() - startTime) >= DB_AUDIT_UPDATE_MS) { - // update the timestamp - dbDao.setLastUpdated(); - // reset the startTime - startTime = AuditorTime.getInstance().getMillis(); - } else { - // sleep a couple seconds to break up the activity - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Sleeping " + DB_AUDIT_SLEEP_MS + "ms"); - } - sleep(); - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Waking from sleep"); - } - } - } // end: for(String clazzName: classNameList) + startTime = timeCheck("First", startTime); + } // check if misMatchedMap is empty if (misMatchedMap.isEmpty()) { @@ -204,8 +184,6 @@ public class DbAudit { if (logger.isDebugEnabled()) { logger.debug("dbAudit: Exiting, misMatchedMap is empty"); } - // we are done - return; } else { if (logger.isDebugEnabled()) { logger.debug("dbAudit: Doing another comparison; misMatchedMap.size()=" + misMatchedMap.size()); @@ -246,7 +224,7 @@ public class DbAudit { * again for all nodes later. */ compareMineWithTheirs(myEntries, theirEntries, clazzName, misMatchedMap); - } // end for (IntegrityAuditEntity iae : iaeList) + } } private void compareMineWithTheirs(Map<Object, Object> myEntries, Map<Object, Object> theirEntries, @@ -265,13 +243,32 @@ public class DbAudit { } } + private long timeCheck(String type, long startTime) throws IntegrityAuditException { + if ((AuditorTime.getInstance().getMillis() - startTime) >= DB_AUDIT_UPDATE_MS) { + // update the timestamp + dbDao.setLastUpdated(); + // reset the startTime + return AuditorTime.getInstance().getMillis(); + } else { + // sleep a couple seconds to break up the activity + if (logger.isDebugEnabled()) { + logger.debug("dbAudit: " + type + " comparison; sleeping " + DB_AUDIT_SLEEP_MS + "ms"); + } + sleep(); + if (logger.isDebugEnabled()) { + logger.debug("dbAudit: " + type + " comparison; waking from sleep"); + } + return startTime; + } + } + /** * Creates properties for the other db node. * @param iae target DB node * @return DAO properties for the given DB node */ private Properties getTheirDaoProperties(IntegrityAuditEntity iae) { - Properties theirProperties = new Properties(); + var theirProperties = new Properties(); theirProperties.put(IntegrityAuditProperties.DB_DRIVER, iae.getJdbcDriver()); theirProperties.put(IntegrityAuditProperties.DB_URL, iae.getJdbcUrl()); @@ -298,7 +295,7 @@ public class DbAudit { logger.debug("dbAudit: Second comparison; traversing classNameSet, size=" + classNameSet.size()); } - int errorCount = 0; + var errorCount = 0; for (String clazzName : classNameSet) { @@ -317,24 +314,10 @@ public class DbAudit { errorCount += recompareMineWithTheirs(resourceName, persistenceUnit, iaeList, myIae, clazzName, keySet, myEntries); // Time check - if ((AuditorTime.getInstance().getMillis() - startTime) >= DB_AUDIT_UPDATE_MS) { - // update the timestamp - dbDao.setLastUpdated(); - // reset the startTime - startTime = AuditorTime.getInstance().getMillis(); - } else { - // sleep a couple seconds to break up the activity - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; sleeping " + DB_AUDIT_SLEEP_MS + "ms"); - } - sleep(); - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; waking from sleep"); - } - } - } // end: for(String clazzName: classNameList) + startTime = timeCheck("Second", startTime); + } - if (errorCount != 0) { + if (errorCount > 0) { String msg = " DB Audit: " + errorCount + " errors found. A large number of errors may indicate DB replication has stopped"; logger.error(MessageCodes.ERROR_AUDIT, msg); @@ -345,7 +328,7 @@ public class DbAudit { IntegrityAuditEntity myIae, String clazzName, Set<Object> keySet, Map<Object, Object> myEntries) throws IntegrityAuditException { - int errorCount = 0; + var errorCount = 0; for (IntegrityAuditEntity iae : iaeList) { if (iae.getId() == myIae.getId()) { if (logger.isDebugEnabled()) { @@ -381,7 +364,7 @@ public class DbAudit { return 0; } - StringBuilder keyBuilder = new StringBuilder(); + var keyBuilder = new StringBuilder(); for (Object key : misMatchedKeySet) { keyBuilder.append(key.toString()); keyBuilder.append(", "); @@ -477,13 +460,17 @@ public class DbAudit { String tableName = entityClass.getAnnotation(Table.class).name(); String msg = "\nDB Audit Error: " + "\n Table Name: " + tableName + "\n Entry 1 (short prefix style): " + resourceName1 + ": " - + new ReflectionToStringBuilder(entry1, ToStringStyle.SHORT_PREFIX_STYLE).toString() + + new ReflectionToStringBuilder(entry1, ToStringStyle.SHORT_PREFIX_STYLE) + "\n Entry 2 (short prefix style): " + resourceName2 + ": " - + new ReflectionToStringBuilder(entry2, ToStringStyle.SHORT_PREFIX_STYLE).toString() + + (entry2 != null + ? new ReflectionToStringBuilder(entry2, ToStringStyle.SHORT_PREFIX_STYLE).toString() + : "null") + "\n Entry 1 (recursive style): " + resourceName1 + ": " - + new ReflectionToStringBuilder(entry1, new RecursiveToStringStyle()).toString() + + new ReflectionToStringBuilder(entry1, new RecursiveToStringStyle()) + "\n Entry 2 (recursive style): " + resourceName2 + ": " - + new ReflectionToStringBuilder(entry2, new RecursiveToStringStyle()).toString(); + + (entry2 != null + ? new ReflectionToStringBuilder(entry2, new RecursiveToStringStyle()).toString() + : "null"); logger.debug(msg); } catch (ClassNotFoundException e) { diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java index 80177b30..ad96432d 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +21,15 @@ package org.onap.policy.common.ia; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import jakarta.persistence.Persistence; +import jakarta.persistence.Query; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.metamodel.ManagedType; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -27,28 +37,15 @@ import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.function.BiConsumer; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import javax.persistence.PersistenceUnitUtil; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import javax.persistence.metamodel.ManagedType; -import javax.persistence.metamodel.Metamodel; import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; /** * class DbDao provides the inteface to the DBs for the purpose of audits. - * */ public class DbDao { - private static final Logger logger = FlexLogger.getLogger(DbDao.class.getName()); + private static final Logger logger = FlexLogger.getLogger(); private String resourceName; private String persistenceUnit; @@ -59,7 +56,7 @@ public class DbDao { private String nodeType; private Properties properties = null; - private EntityManagerFactory emf; + private final EntityManagerFactory emf; /* * Supports designation serialization. @@ -78,14 +75,14 @@ public class DbDao { * DB SELECT String. */ private static final String SELECT_STRING = "Select i from IntegrityAuditEntity i " - + "where i.resourceName=:rn and i.persistenceUnit=:pu"; + + "where i.resourceName=:rn and i.persistenceUnit=:pu"; /** * DbDao Constructor. * - * @param resourceName the resource name + * @param resourceName the resource name * @param persistenceUnit the persistence unit - * @param properties the properties + * @param properties the properties * @throws IntegrityAuditException if an error occurs */ public DbDao(String resourceName, String persistenceUnit, Properties properties) throws IntegrityAuditException { @@ -95,15 +92,14 @@ public class DbDao { /** * DbDao Constructor. * - * @param resourceName the resource name + * @param resourceName the resource name * @param persistenceUnit the persistence unit - * @param properties the properties - * @param lastUpdateDate may be {@code null} - * @param altDbUrl may be {@code null} + * @param properties the properties + * @param altDbUrl may be {@code null} * @throws IntegrityAuditException if an error occurs */ protected DbDao(String resourceName, String persistenceUnit, Properties properties, String altDbUrl) - throws IntegrityAuditException { + throws IntegrityAuditException { logger.debug("DbDao contructor: enter"); validateProperties(resourceName, persistenceUnit, properties); @@ -125,14 +121,14 @@ public class DbDao { /** * validateProperties will validate the properties. * - * @param resourceName the rseource name + * @param resourceName the rseource name * @param persistenceUnit the persistence unit - * @param properties the properties + * @param properties the properties * @throws IntegrityAuditPropertiesException if an error occurs */ private void validateProperties(String resourceName, String persistenceUnit, Properties properties) - throws IntegrityAuditPropertiesException { - StringBuilder badparams = new StringBuilder(); + throws IntegrityAuditPropertiesException { + var badparams = new StringBuilder(); if (IntegrityAudit.parmsAreBad(resourceName, persistenceUnit, properties, badparams)) { String msg = "DbDao: Bad parameters: badparams" + badparams; throw new IntegrityAuditPropertiesException(msg); @@ -146,7 +142,7 @@ public class DbDao { this.nodeType = properties.getProperty(IntegrityAuditProperties.NODE_TYPE).trim().toLowerCase(); this.properties = properties; logger.debug("DbDao.assignProperties: exit:" + "\nresourceName: " + this.resourceName + "\npersistenceUnit: " - + this.persistenceUnit + "\nproperties: " + this.properties); + + this.persistenceUnit + "\nproperties: " + this.properties); } /** @@ -158,21 +154,9 @@ public class DbDao { public Map<Object, Object> getAllMyEntries(String className) { logger.debug("getAllMyEntries: Entering, className=" + className); HashMap<Object, Object> resultMap = new HashMap<>(); - EntityManager em = emf.createEntityManager(); + var em = emf.createEntityManager(); try { - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery<Object> cq = cb.createQuery(); - Root<?> rootEntry = cq.from(Class.forName(className)); - CriteriaQuery<Object> all = cq.select(rootEntry); - TypedQuery<Object> allQuery = em.createQuery(all); - List<Object> objectList = allQuery.getResultList(); - // Now create the map - - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - for (Object o : objectList) { - Object key = util.getIdentifier(o); - resultMap.put(key, o); - } + getObjectsFromCriteriaBuilder(className, emf, em, resultMap); } catch (Exception e) { logger.error("getAllEntries encountered exception: ", e); } @@ -185,14 +169,14 @@ public class DbDao { * getAllMyEntries gets all entries for a class. * * @param className the name of the class - * @param keySet the keys to get the entries for + * @param keySet the keys to get the entries for * @return the map of requested entries */ public Map<Object, Object> getAllMyEntries(String className, Set<Object> keySet) { logger.debug("getAllMyEntries: Entering, className=" + className + ",\n keySet=" + keySet); HashMap<Object, Object> resultMap = new HashMap<>(); - EntityManager em = emf.createEntityManager(); + var em = emf.createEntityManager(); try { Class<?> clazz = Class.forName(className); for (Object key : keySet) { @@ -209,11 +193,11 @@ public class DbDao { } /** - * getAllEntries gets all entriesfor a particular persistence unit adn className. + * getAllEntries gets all entries for a particular persistence unit adn className. * * @param persistenceUnit the persistence unit - * @param properties the properties - * @param className the class name + * @param properties the properties + * @param className the class name * @return the map of entries */ public Map<Object, Object> getAllEntries(String persistenceUnit, Properties properties, String className) { @@ -221,21 +205,11 @@ public class DbDao { logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n className=" + className); HashMap<Object, Object> resultMap = new HashMap<>(); - EntityManagerFactory theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = theEmf.createEntityManager(); + var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties); + var em = theEmf.createEntityManager(); + try { - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery<Object> cq = cb.createQuery(); - Root<?> rootEntry = cq.from(Class.forName(className)); - CriteriaQuery<Object> all = cq.select(rootEntry); - TypedQuery<Object> allQuery = em.createQuery(all); - List<Object> objectList = allQuery.getResultList(); - - PersistenceUnitUtil util = theEmf.getPersistenceUnitUtil(); - for (Object o : objectList) { - Object key = util.getIdentifier(o); - resultMap.put(key, o); - } + getObjectsFromCriteriaBuilder(className, theEmf, em, resultMap); } catch (Exception e) { logger.error("getAllEntries encountered exception:", e); } @@ -252,18 +226,18 @@ public class DbDao { * getAllEntries gets all entries for a persistence unit. * * @param persistenceUnit the persistence unit - * @param properties the properties - * @param className the class name - * @param keySet the keys + * @param properties the properties + * @param className the class name + * @param keySet the keys * @return the map of entries */ public Map<Object, Object> getAllEntries(String persistenceUnit, Properties properties, String className, - Set<Object> keySet) { + Set<Object> keySet) { logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n properties= " + properties - + ",\n className=" + className + ",\n keySet= " + keySet); - EntityManagerFactory theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = theEmf.createEntityManager(); + + ",\n className=" + className + ",\n keySet= " + keySet); + var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties); + var em = theEmf.createEntityManager(); HashMap<Object, Object> resultMap = new HashMap<>(); try { Class<?> clazz = Class.forName(className); @@ -286,34 +260,35 @@ public class DbDao { * unit and node type. * * @param persistenceUnit the persistence unit - * @param nodeType the node type + * @param nodeType the node type * @return the list of IntegrityAuditEntity * @throws DbDaoTransactionException if an error occurs */ @SuppressWarnings("unchecked") public List<IntegrityAuditEntity> getIntegrityAuditEntities(String persistenceUnit, String nodeType) - throws DbDaoTransactionException { + throws DbDaoTransactionException { logger.debug("getIntegrityAuditEntities: Entering, persistenceUnit=" + persistenceUnit + ",\n nodeType= " - + nodeType); + + nodeType); try { - EntityManager em = emf.createEntityManager(); - // Start a transaction - EntityTransaction et = em.getTransaction(); + List<IntegrityAuditEntity> iaeList; + try (var em = emf.createEntityManager()) { + // Start a transaction + EntityTransaction et = em.getTransaction(); - et.begin(); + et.begin(); - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not - // found, create a new entry - Query iaequery = em + // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not + // found, create a new entry + var iaequery = em .createQuery("Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt"); - iaequery.setParameter("pu", persistenceUnit); - iaequery.setParameter("nt", nodeType); + iaequery.setParameter("pu", persistenceUnit); + iaequery.setParameter("nt", nodeType); - List<IntegrityAuditEntity> iaeList = iaequery.getResultList(); + iaeList = iaequery.getResultList(); - // commit transaction - et.commit(); - em.close(); + // commit transaction + et.commit(); + } logger.debug("getIntegrityAuditEntities: Exit, iaeList=" + iaeList); return iaeList; } catch (Exception e) { @@ -332,17 +307,17 @@ public class DbDao { */ public IntegrityAuditEntity getMyIntegrityAuditEntity() throws DbDaoTransactionException { - return updateIae("getMyIntegrityAuditEntity", this.resourceName, this.persistenceUnit, (em,iae) -> { + return updateIae("getMyIntegrityAuditEntity", this.resourceName, this.persistenceUnit, (em, iae) -> { if (iae != null) { // refresh the object from DB in case cached data was returned em.refresh(iae); logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit - + " exists"); + + " exists"); } else { // If it does not exist, log an error logger.error("Attempting to setLastUpdated" + " on an entry that does not exist: resource " - + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit); + + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit); } }); } @@ -357,17 +332,18 @@ public class DbDao { */ public IntegrityAuditEntity getIntegrityAuditEntity(long id) throws DbDaoTransactionException { try { - EntityManager em = emf.createEntityManager(); + IntegrityAuditEntity iae; + try (var em = emf.createEntityManager()) { - // Start a transaction - EntityTransaction et = em.getTransaction(); + // Start a transaction + EntityTransaction et = em.getTransaction(); - et.begin(); + et.begin(); - IntegrityAuditEntity iae = em.find(IntegrityAuditEntity.class, id); + iae = em.find(IntegrityAuditEntity.class, id); - et.commit(); - em.close(); + et.commit(); + } return iae; } catch (Exception e) { @@ -385,7 +361,7 @@ public class DbDao { public Set<String> getPersistenceClassNames() { logger.debug("DbDao: getPersistenceClassNames() entry"); HashSet<String> returnList = new HashSet<>(); - final Metamodel mm = emf.getMetamodel(); + final var mm = emf.getMetamodel(); logger.debug("\n" + persistenceUnit + " persistence unit classes:"); for (final ManagedType<?> managedType : mm.getManagedTypes()) { Class<?> clazz = managedType.getJavaType(); @@ -400,11 +376,11 @@ public class DbDao { * Register the IntegrityAudit instance. * * @param altDbUrl alternate DB URL to be placed into the record, or {@code null} to use the - * default + * default */ private void register(String altDbUrl) throws DbDaoTransactionException { - updateIae("register", this.resourceName, this.persistenceUnit, (em,iae) -> { + updateIae("register", this.resourceName, this.persistenceUnit, (em, iae) -> { IntegrityAuditEntity iae2 = iae; // If it already exists, we just want to update the properties and lastUpdated date @@ -412,12 +388,12 @@ public class DbDao { // refresh the object from DB in case cached data was returned em.refresh(iae2); logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit - + " exists and entry be updated"); + + " exists and entry be updated"); } else { // If it does not exist, we also must add teh resourceName, persistenceUnit and // designated values logger.info("Adding resource " + resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit - + " to IntegrityAuditEntity table"); + + " to IntegrityAuditEntity table"); iae2 = new IntegrityAuditEntity(); iae2.setResourceName(this.resourceName); iae2.setPersistenceUnit(this.persistenceUnit); @@ -450,23 +426,23 @@ public class DbDao { /** * Set designated. * - * @param resourceName the resource name + * @param resourceName the resource name * @param persistenceUnit the persistence unit - * @param desig true if is designated + * @param desig true if is designated * @throws DbDaoTransactionException if an error occurs */ public void setDesignated(String resourceName, String persistenceUnit, boolean desig) - throws DbDaoTransactionException { + throws DbDaoTransactionException { logger.debug("setDesignated: enter, resourceName: " + resourceName + ", persistenceUnit: " + persistenceUnit - + ", designated: " + desig); + + ", designated: " + desig); - updateIae("setDesignated", resourceName, persistenceUnit, (em,iae) -> { + updateIae("setDesignated", resourceName, persistenceUnit, (em, iae) -> { if (iae != null) { // refresh the object from DB in case cached data was returned em.refresh(iae); logger.info(RESOURCE_MESSAGE + resourceName + WITH_PERSISTENCE_MESSAGE + persistenceUnit - + " exists and designated be updated"); + + " exists and designated be updated"); iae.setDesignated(desig); em.persist(iae); @@ -475,7 +451,7 @@ public class DbDao { } else { // If it does not exist, log an error logger.error("Attempting to setDesignated(" + desig + ") on an entry that does not exist:" - + " resource " + resourceName + WITH_PERSISTENCE_MESSAGE + persistenceUnit); + + " resource " + resourceName + WITH_PERSISTENCE_MESSAGE + persistenceUnit); } }); @@ -484,50 +460,49 @@ public class DbDao { /** * Queries for an audit entity and then updates it using an "updater" function. * - * @param methodName name of the method that invoked this - * @param resourceName the resource name + * @param methodName name of the method that invoked this + * @param resourceName the resource name * @param persistenceUnit the persistence unit - * @param updater function to update the entity; the argument will be the entity to be - * updated, or {@code null} if the entity is not found + * @param updater function to update the entity; the argument will be the entity to be + * updated, or {@code null} if the entity is not found * @return the entity that was found, or {@code null} if the entity is not found * @throws DbDaoTransactionException if an error occurs */ private IntegrityAuditEntity updateIae(String methodName, String resourceName, String persistenceUnit, - BiConsumer<EntityManager,IntegrityAuditEntity> updater) throws DbDaoTransactionException { + BiConsumer<EntityManager, IntegrityAuditEntity> updater) + throws DbDaoTransactionException { try { - EntityManager em = emf.createEntityManager(); + IntegrityAuditEntity iae; + try (var em = emf.createEntityManager()) { - // Start a transaction - EntityTransaction et = em.getTransaction(); + // Start a transaction + EntityTransaction et = em.getTransaction(); - et.begin(); + et.begin(); - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not - // found, create a new entry - Query iaequery = em.createQuery(SELECT_STRING); - iaequery.setParameter("rn", resourceName); - iaequery.setParameter("pu", persistenceUnit); + // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not + // found, create a new entry + TypedQuery<IntegrityAuditEntity> iaequery = em.createQuery(SELECT_STRING, IntegrityAuditEntity.class); + iaequery.setParameter("rn", resourceName); + iaequery.setParameter("pu", persistenceUnit); - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae; + List<IntegrityAuditEntity> iaeList = iaequery.getResultList(); - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); + if (!iaeList.isEmpty()) { + // ignores multiple results + iae = iaeList.get(0); - } else { - // If it does not exist - iae = null; - } + } else { + // If it does not exist + iae = null; + } - updater.accept(em, iae); + updater.accept(em, iae); - // close the transaction - et.commit(); - // close the EntityManager - em.close(); + // close the transaction + et.commit(); + } return iae; @@ -546,15 +521,15 @@ public class DbDao { */ public void setLastUpdated() throws DbDaoTransactionException { logger.debug("setLastUpdated: enter, resourceName: " + this.resourceName + ", persistenceUnit: " - + this.persistenceUnit); + + this.persistenceUnit); - updateIae("setLastUpdated", this.resourceName, this.persistenceUnit, (em,iae) -> { + updateIae("setLastUpdated", this.resourceName, this.persistenceUnit, (em, iae) -> { if (iae != null) { // refresh the object from DB in case cached data was returned em.refresh(iae); logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit - + " exists and lastUpdated be updated"); + + " exists and lastUpdated be updated"); iae.setLastUpdated(AuditorTime.getInstance().getDate()); em.persist(iae); @@ -563,7 +538,7 @@ public class DbDao { } else { // If it does not exist, log an error logger.error("Attempting to setLastUpdated" + " on an entry that does not exist:" + " resource " - + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit); + + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit); } }); } @@ -578,26 +553,27 @@ public class DbDao { if (!IntegrityAudit.isUnitTesting()) { String msg = DBDAO_MESSAGE + "deleteAllIntegrityAuditEntities() " - + "should only be invoked during JUnit testing"; + + "should only be invoked during JUnit testing"; logger.error(msg); throw new DbDaoTransactionException(msg); } - EntityManager em = emf.createEntityManager(); - // Start a transaction - EntityTransaction et = em.getTransaction(); + int returnCode; + try (var em = emf.createEntityManager()) { + // Start a transaction + EntityTransaction et = em.getTransaction(); - et.begin(); + et.begin(); - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not - // found, create a new entry - Query iaequery = em.createQuery("Delete from IntegrityAuditEntity"); + // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not + // found, create a new entry + var iaequery = em.createQuery("Delete from IntegrityAuditEntity"); - int returnCode = iaequery.executeUpdate(); + returnCode = iaequery.executeUpdate(); - // commit transaction - et.commit(); - em.close(); + // commit transaction + et.commit(); + } logger.info("deleteAllIntegrityAuditEntities: returnCode=" + returnCode); @@ -623,69 +599,65 @@ public class DbDao { * designations from interleaved changeDesignated() invocations from different resources * (entities), because it prevents "dirty" and "non-repeatable" reads. * - * <p>See http://www.objectdb.com/api/java/jpa/LockModeType + * <p>See www.objectdb.com/api/java/jpa/LockModeType * * <p>and * - * <p>http://stackoverflow.com/questions/2120248/how-to-synchronize-a-static- + * <p>stackoverflow.com/questions/2120248/how-to-synchronize-a-static- * variable-among-threads-running-different-instances-o */ public void changeDesignated(String resourceName, String persistenceUnit, String nodeType) - throws DbDaoTransactionException { + throws DbDaoTransactionException { if (logger.isDebugEnabled()) { logger.debug("changeDesignated: Entering, resourceName=" + resourceName + ", persistenceUnit=" - + persistenceUnit + ", nodeType=" + nodeType); + + persistenceUnit + ", nodeType=" + nodeType); } long startTime = AuditorTime.getInstance().getMillis(); synchronized (lock) { - - EntityManager em = null; - try { - - em = emf.createEntityManager(); - em.getTransaction().begin(); - - /* - * Define query - */ - Query query = em.createQuery( + try (var em = emf.createEntityManager()) { + try { + em.getTransaction().begin(); + + /* + * Define query + */ + var query = em.createQuery( "Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt"); - query.setParameter("pu", persistenceUnit); - query.setParameter("nt", nodeType); - - /* - * Execute query using pessimistic write lock. This ensures that if anyone else is - * currently reading the records we'll throw a LockTimeoutException. - */ - setDesignatedEntity(resourceName, query); - - if (logger.isDebugEnabled()) { - logger.debug("changeDesignated: Committing designation to resourceName=" + resourceName); - } - em.getTransaction().commit(); - - /* - * If we get a LockTimeoutException, no harm done really. We'll probably be - * successful on the next attempt. The odds of another DbDao instance on this entity - * or another entity attempting a simultaneous IntegrityAuditEntity table - * read/update are pretty slim (we're only in this method for two or three - * milliseconds) - */ - } catch (Exception e) { - if (em != null) { - em.getTransaction().rollback(); - - String msg = "DbDao: changeDesignated() caught Exception, message=" + e.getMessage(); - logger.error(msg + e); - throw new DbDaoTransactionException(msg, e); - } else { - String msg = "DbDao: changeDesignated() caught Exception, message=" + query.setParameter("pu", persistenceUnit); + query.setParameter("nt", nodeType); + + /* + * Execute query using pessimistic write lock. This ensures that if anyone else is + * currently reading the records we'll throw a LockTimeoutException. + */ + setDesignatedEntity(resourceName, query); + + if (logger.isDebugEnabled()) { + logger.debug("changeDesignated: Committing designation to resourceName=" + resourceName); + } + em.getTransaction().commit(); + + /* + * If we get a LockTimeoutException, no harm done really. We'll probably be + * successful on the next attempt. The odds of another DbDao instance on this entity + * or another entity attempting a simultaneous IntegrityAuditEntity table + * read/update are pretty slim (we're only in this method for two or three + * milliseconds) + */ + } catch (Exception e) { + String errorMsg; + try { + em.getTransaction().rollback(); + errorMsg = "DbDao: changeDesignated() caught Exception, message=" + e.getMessage(); + } catch (Exception rollbackException) { + errorMsg = "DbDao: changeDesignated() caught Exception, message=" + e.getMessage() + ". Error rolling back transaction."; - logger.error(msg + e); - throw new DbDaoTransactionException(msg, e); + } + logger.error(errorMsg + e); + throw new DbDaoTransactionException(errorMsg, e); } } @@ -693,32 +665,58 @@ public class DbDao { if (logger.isDebugEnabled()) { logger.debug("changeDesignated: Exiting; time expended=" - + (AuditorTime.getInstance().getMillis() - startTime) + "ms"); + + (AuditorTime.getInstance().getMillis() - startTime) + "ms"); } } private void setDesignatedEntity(String resourceName, Query query) { for (Object o : query.getResultList()) { - if (!(o instanceof IntegrityAuditEntity)) { + if (!(o instanceof IntegrityAuditEntity integrityAuditEntity)) { continue; } - IntegrityAuditEntity integrityAuditEntity = (IntegrityAuditEntity) o; if (integrityAuditEntity.getResourceName().equals(resourceName)) { if (logger.isDebugEnabled()) { logger.debug("changeDesignated: Designating resourceName=" - + integrityAuditEntity.getResourceName()); + + integrityAuditEntity.getResourceName()); } integrityAuditEntity.setDesignated(true); } else { if (logger.isDebugEnabled()) { logger.debug("changeDesignated: Removing designation from resourceName=" - + integrityAuditEntity.getResourceName()); + + integrityAuditEntity.getResourceName()); } integrityAuditEntity.setDesignated(false); } } } + /** + * Collects all objects from a criteria builder based on className. + * + * @param className type of objects for resultMap + * @param emf the entity manager factory to be used + * @param em entity manager to be used + * @param resultMap the result map for objects queried + * @throws ClassNotFoundException if class for criteria builder doesn't exist + */ + private void getObjectsFromCriteriaBuilder(String className, EntityManagerFactory emf, EntityManager em, + HashMap<Object, Object> resultMap) + throws ClassNotFoundException { + var cb = em.getCriteriaBuilder(); + CriteriaQuery<Object> cq = cb.createQuery(); + Root<?> rootEntry = cq.from(Class.forName(className)); + CriteriaQuery<Object> all = cq.select(rootEntry); + TypedQuery<Object> allQuery = em.createQuery(all); + List<Object> objectList = allQuery.getResultList(); + // Now create the map + + var util = emf.getPersistenceUnitUtil(); + for (Object o : objectList) { + Object key = util.getIdentifier(o); + resultMap.put(key, o); + } + } + } diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java index 41aea118..66ab307c 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-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. @@ -21,6 +21,8 @@ package org.onap.policy.common.ia; import java.util.Properties; +import lombok.Getter; +import lombok.Setter; import org.apache.commons.lang3.StringUtils; import org.onap.policy.common.ia.IntegrityAuditProperties.NodeTypeEnum; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -34,8 +36,12 @@ public class IntegrityAudit { private static final Logger logger = FlexLogger.getLogger(IntegrityAudit.class); - private static boolean isUnitTesting; - private boolean isThreadInitialized = false; + @Getter + @Setter + private static boolean unitTesting; + + @Getter + private boolean threadInitialized = false; AuditThread auditThread = null; @@ -54,6 +60,7 @@ public class IntegrityAudit { * indicated period * */ + @Getter private int integrityAuditPeriodSeconds; /** @@ -68,7 +75,7 @@ public class IntegrityAudit { throws IntegrityAuditException { logger.info("Constructor: Entering and checking for nulls"); - StringBuilder parmList = new StringBuilder(); + var parmList = new StringBuilder(); if (parmsAreBad(resourceName, persistenceUnit, properties, parmList)) { logger.error("Constructor: Parms contain nulls; cannot run audit for resourceName=" + resourceName + ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList); @@ -94,13 +101,6 @@ public class IntegrityAudit { } /** - * Used during JUnit testing by AuditPeriodTest.java - */ - public int getIntegrityAuditPeriodSeconds() { - return integrityAuditPeriodSeconds; - } - - /** * Determine if the nodeType conforms to the required node types. */ public static boolean isNodeTypeEnum(String nt) { @@ -237,21 +237,9 @@ public class IntegrityAudit { logger.info("stopAuditThread: Exiting"); } - public boolean isThreadInitialized() { - return isThreadInitialized; - } - public void setThreadInitialized(boolean isThreadInitialized) { logger.info("setThreadInitialized: Setting isThreadInitialized=" + isThreadInitialized); - this.isThreadInitialized = isThreadInitialized; - } - - public static boolean isUnitTesting() { - return isUnitTesting; - } - - public static void setUnitTesting(boolean isUnitTesting) { - IntegrityAudit.isUnitTesting = isUnitTesting; + this.threadInitialized = isThreadInitialized; } /** diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java index 365afd25..cd80f56f 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,14 +21,18 @@ package org.onap.policy.common.ia; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class IntegrityAuditProperties { public static final int DEFAULT_AUDIT_PERIOD_SECONDS = -1; // Audit does not run - public static final String DB_DRIVER = "javax.persistence.jdbc.driver"; - public static final String DB_URL = "javax.persistence.jdbc.url"; - public static final String DB_USER = "javax.persistence.jdbc.user"; - public static final String DB_PWD = "javax.persistence.jdbc.password"; //NOSONAR + public static final String DB_DRIVER = "jakarta.persistence.jdbc.driver"; + public static final String DB_URL = "jakarta.persistence.jdbc.url"; + public static final String DB_USER = "jakarta.persistence.jdbc.user"; + public static final String DB_PWD = "jakarta.persistence.jdbc.password"; //NOSONAR public static final String AUDIT_PERIOD_SECONDS = "integrity_audit_period_seconds"; @@ -38,9 +43,4 @@ public class IntegrityAuditProperties { PDP_XACML, PDP_DROOLS, PAP, PAP_ADMIN, LOGPARSER, BRMS_GATEWAY, ASTRA_GATEWAY, ELK_SERVER, PYPDP } - - private IntegrityAuditProperties() { - - } - } diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java index c1046828..64ec7fd0 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java @@ -2,14 +2,15 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,41 +21,48 @@ package org.onap.policy.common.ia.jpa; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.NamedQuery; +import jakarta.persistence.PrePersist; +import jakarta.persistence.PreUpdate; +import jakarta.persistence.Table; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; import java.io.IOException; import java.io.ObjectOutputStream; +import java.io.Serial; import java.io.Serializable; import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -/* - * The Entity class to for management of IntegrityAudits - */ +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.onap.policy.common.ia.AuditorTime; @Entity @Table(name = "IntegrityAuditEntity") -@NamedQueries({@NamedQuery(name = " IntegrityAuditEntity.findAll", query = "SELECT e FROM IntegrityAuditEntity e "), - @NamedQuery(name = "IntegrityAuditEntity.deleteAll", query = "DELETE FROM IntegrityAuditEntity WHERE 1=1")}) - +@NamedQuery(name = " IntegrityAuditEntity.findAll", query = "SELECT e FROM IntegrityAuditEntity e ") +@NamedQuery(name = "IntegrityAuditEntity.deleteAll", query = "DELETE FROM IntegrityAuditEntity WHERE 1=1") +@NoArgsConstructor +@Getter +@Setter public class IntegrityAuditEntity implements Serializable { + + @Serial private static final long serialVersionUID = 1L; - private static boolean isUnitTesting; + @Getter + @Setter + private static boolean unitTesting; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") + @Setter(AccessLevel.PRIVATE) private long id; @Column(name = "persistenceUnit", nullable = false) @@ -92,17 +100,12 @@ public class IntegrityAuditEntity implements Serializable { @Column(name = "lastUpdated") private Date lastUpdated; - - public IntegrityAuditEntity() { - // Empty constructor - } - /** * Pre persist. */ @PrePersist public void prePersist() { - Date date = AuditorTime.getInstance().getDate(); + var date = AuditorTime.getInstance().getDate(); this.createdDate = date; this.lastUpdated = date; } @@ -112,106 +115,6 @@ public class IntegrityAuditEntity implements Serializable { this.lastUpdated = AuditorTime.getInstance().getDate(); } - public long getId() { - return id; - } - - public String getPersistenceUnit() { - return persistenceUnit; - } - - public void setPersistenceUnit(String persistenceUnit) { - this.persistenceUnit = persistenceUnit; - } - - public String getSite() { - return site; - } - - public void setSite(String site) { - this.site = site; - } - - public String getNodeType() { - return nodeType; - } - - public void setNodeType(String nodeType) { - this.nodeType = nodeType; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public boolean isDesignated() { - return designated; - } - - public void setDesignated(boolean designated) { - this.designated = designated; - } - - public String getJdbcDriver() { - return jdbcDriver; - } - - public void setJdbcDriver(String jdbcDriver) { - this.jdbcDriver = jdbcDriver; - } - - public String getJdbcUrl() { - return jdbcUrl; - } - - public void setJdbcUrl(String jdbcUrl) { - this.jdbcUrl = jdbcUrl; - } - - public String getJdbcUser() { - return jdbcUser; - } - - public void setJdbcUser(String jdbcUser) { - this.jdbcUser = jdbcUser; - } - - public String getJdbcPassword() { - return jdbcPassword; - } - - public void setJdbcPassword(String jdbcPassword) { - this.jdbcPassword = jdbcPassword; - } - - public Date getLastUpdated() { - return lastUpdated; - } - - public void setLastUpdated(Date lastUpdated) { - this.lastUpdated = lastUpdated; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date created) { - this.createdDate = created; - } - - public static boolean isUnitTesting() { - return isUnitTesting; - } - - public static void setUnitTesting(boolean isUnitTesting) { - IntegrityAuditEntity.isUnitTesting = isUnitTesting; - } - private void writeObject(ObjectOutputStream out) throws IOException { if (isUnitTesting()) { /* |