diff options
Diffstat (limited to 'integrity-monitor/src/main')
15 files changed, 556 insertions, 1019 deletions
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java index 717ae7a3..7031c50a 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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,14 @@ package org.onap.policy.common.im; +import com.google.re2j.Pattern; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import jakarta.persistence.FlushModeType; +import jakarta.persistence.LockModeType; +import jakarta.persistence.Persistence; +import jakarta.persistence.TypedQuery; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; @@ -31,16 +40,13 @@ import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; +import java.util.function.IntConsumer; +import java.util.function.LongConsumer; import java.util.function.Supplier; import javax.management.JMX; import javax.management.MBeanServerConnection; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.FlushModeType; -import javax.persistence.LockModeType; -import javax.persistence.Persistence; -import javax.persistence.Query; +import lombok.Getter; +import lombok.Setter; import org.apache.commons.lang3.StringUtils; import org.onap.policy.common.im.jmx.ComponentAdmin; import org.onap.policy.common.im.jmx.ComponentAdminMBean; @@ -59,6 +65,9 @@ public class IntegrityMonitor { private static final Logger logger = LoggerFactory.getLogger(IntegrityMonitor.class.getName()); + private static final Pattern COMMA_PAT = Pattern.compile(","); + private static final Pattern SEMICOLON_PAT = Pattern.compile(";"); + // only allow one instance of IntegrityMonitor private static IntegrityMonitor instance = null; @@ -69,8 +78,8 @@ public class IntegrityMonitor { private static final String IGNORE_INVALID_PROPERTY_STRING = "Ignored invalid property: {}"; private static final String PROPERTY_EXCEPTION_STRING = "IntegrityMonitor Property Exception: "; private static final String EXCEPTION_STRING = "IntegrityMonitor threw exception."; - private static final String STATE_CHECK_STRING = "IntegrityMonitor.stateCheck(): " - + "Failed to disableFail dependent resource = "; + private static final String STATE_CHECK_STRING = + "IntegrityMonitor.stateCheck(): " + "Failed to disableFail dependent resource = "; private static final String RESOURCE_STRING = "Resource "; private static final String LC_RESOURCE_STRING = "resource"; @@ -83,26 +92,27 @@ public class IntegrityMonitor { boolean alarmExists = false; /* - * Error message that is written by the dependencyCheck() method. It is made available - * externally through the evaluateSanity() method. + * Error message that is written by the dependencyCheck() method. It is made available externally through the + * evaluateSanity() method. */ private String dependencyCheckErrorMsg = ""; // The entity manager factory for JPA access - private EntityManagerFactory emf; - private EntityManager em; + private final EntityManagerFactory emf; + private final EntityManager em; // Persistence Unit for JPA public static final String PERSISTENCE_UNIT = "operationalPU"; public static final long CYCLE_INTERVAL_MILLIS = 1000L; + @Getter private StateManagement stateManager = null; /** * Set to {@code null} if to stop running. */ - private volatile Thread fpManager = null; + private AtomicReference<Thread> fpManager = new AtomicReference<>(); // The forward progress counter is incremented as the // process being monitored makes forward progress @@ -148,14 +158,16 @@ public class IntegrityMonitor { private static long writeFpcIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_WRITE_FPC_INTERVAL); // check the health of dependencies private static long checkDependencyIntervalMs = - toMillis(IntegrityMonitorProperties.DEFAULT_CHECK_DEPENDENCY_INTERVAL); + toMillis(IntegrityMonitorProperties.DEFAULT_CHECK_DEPENDENCY_INTERVAL); // A lead subsystem will have dependency groups with resource names in the // properties file. // For non-lead subsystems, the dependency_group property will be absent. private static String[] depGroups = null; - private static boolean isUnitTesting = false; + @Getter + @Setter + private static boolean unitTesting = false; // can turn on health checking of dependents via jmx test() call by setting // this property to true @@ -191,30 +203,31 @@ public class IntegrityMonitor { private final Object refreshStateAuditLock = new Object(); private final Object imFlushLock = new Object(); + @Getter private Map<String, String> allSeemsWellMap; + @Getter private Map<String, String> allNotWellMap; /** * IntegrityMonitor constructor. It is invoked from the getInstance() method in this class or from the constructor - * of a child or sub-class. A class can extend the IntegrityMonitor class if there is a need to override any of the + * of a child or subclass. A class can extend the IntegrityMonitor class if there is a need to override any of the * base methods (ex. subsystemTest()). Only one instance is allowed to be created per resource name. * * @param resourceName The resource name of the resource - * @param properties a set of properties passed in from the resource + * @param properties a set of properties passed in from the resource * @throws IntegrityMonitorException if any errors are encountered in the constructor */ protected IntegrityMonitor(String resourceName, Properties properties) throws IntegrityMonitorException { // singleton check since this constructor can be called from a child or - // sub-class + // subclass if (instance != null) { - String msg = "IM object exists and only one instance allowed"; + var msg = "IM object exists and only one instance allowed"; logger.error("{}", msg); throw new IntegrityMonitorException("IntegrityMonitor constructor exception: " + msg); } - instance = this; - IntegrityMonitor.resourceName = resourceName; + setInstance(this, resourceName); /* * Validate that the properties file contains all the needed properties. Throws an @@ -229,14 +242,6 @@ public class IntegrityMonitor { // Create the entity manager factory // emf = Persistence.createEntityManagerFactory(getPersistenceUnit(), properties); - // - // Did it get created? - // - if (emf == null) { - logger.error("Error creating IM entity manager factory with persistence unit: {}", - getPersistenceUnit()); - throw new IntegrityMonitorException("Unable to create IM Entity Manager Factory"); - } // add entry to forward progress and resource registration tables in DB @@ -249,71 +254,14 @@ public class IntegrityMonitor { try { // if ForwardProgress entry exists for resourceName, update it. If // not found, create a new entry - Query fquery = em.createQuery(QUERY_STRING); - fquery.setParameter("rn", resourceName); - - @SuppressWarnings("rawtypes") - List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); - ForwardProgressEntity fpx = null; - if (!fpList.isEmpty()) { - // ignores multiple results - fpx = (ForwardProgressEntity) fpList.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(fpx); - if (logger.isDebugEnabled()) { - logger.debug("Resource {} exists and will be updated - old fpc= {}, lastUpdated= {}", resourceName, - fpx.getFpcCount(), fpx.getLastUpdated()); - } - fpx.setFpcCount(fpCounter); - } else { - // Create a forward progress object - logger.debug("Adding resource {} to ForwardProgress table", resourceName); - fpx = new ForwardProgressEntity(); - } - // update/set columns in entry - fpx.setResourceName(resourceName); - em.persist(fpx); - // flush to the DB - synchronized (imFlushLock) { - em.flush(); - } + createOrUpdateForwardProgress(resourceName); // if ResourceRegistration entry exists for resourceName, update it. // If not found, create a new entry - Query rquery = em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn"); - rquery.setParameter("rn", resourceName); - - @SuppressWarnings("rawtypes") - List rrList = rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); - ResourceRegistrationEntity rrx = null; - if (!rrList.isEmpty()) { - // ignores multiple results - rrx = (ResourceRegistrationEntity) rrList.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(rrx); - if (logger.isDebugEnabled()) { - logger.debug("Resource {} exists and will be updated - old url= {}, createdDate={}", resourceName, - rrx.getResourceUrl(), rrx.getCreatedDate()); - } - rrx.setLastUpdated(MonitorTime.getInstance().getDate()); - } else { - // register resource by adding entry to table in DB - logger.debug("Adding resource {} to ResourceRegistration table", resourceName); - rrx = new ResourceRegistrationEntity(); - } - // update/set columns in entry - rrx.setResourceName(resourceName); - rrx.setResourceUrl(jmxUrl); - rrx.setNodeType(nodeType); - rrx.setSite(siteName); - em.persist(rrx); - // flush to the DB - synchronized (imFlushLock) { - et.commit(); - } + createOrUpdateResourceReg(resourceName, jmxUrl, et); } catch (Exception e) { - logger.error("IntegrityMonitor constructor DB table update failed with exception: ", e); + logger.error("IntegrityMonitor constructor DB table update threw an exception"); try { if (et.isActive()) { synchronized (imFlushLock) { @@ -326,36 +274,115 @@ public class IntegrityMonitor { throw e; } + makeStateManager(resourceName); + + // create management bean + makeManagementBean(resourceName); + + // set now as the last time the refreshStateAudit ran + IntegrityMonitor.this.refreshStateAuditLastRunDate = MonitorTime.getInstance().getDate(); + + fpManager.set(new Thread(this::runFpManager)); + fpManager.get().start(); + + } + + protected void createOrUpdateForwardProgress(String resourceName) { + TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class); + fquery.setParameter("rn", resourceName); + + List<ForwardProgressEntity> fpList = + fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + ForwardProgressEntity fpx; + if (!fpList.isEmpty()) { + // ignores multiple results + fpx = fpList.get(0); + // refresh the object from DB in case cached data was returned + em.refresh(fpx); + if (logger.isDebugEnabled()) { + logger.debug("Resource {} exists and will be updated - old fpc= {}, lastUpdated= {}", resourceName, + fpx.getFpcCount(), fpx.getLastUpdated()); + } + fpx.setFpcCount(fpCounter); + } else { + // Create a forward progress object + logger.debug("Adding resource {} to ForwardProgress table", resourceName); + fpx = new ForwardProgressEntity(); + } + // update/set columns in entry + fpx.setResourceName(resourceName); + em.persist(fpx); + // flush to the DB + synchronized (imFlushLock) { + em.flush(); + } + } + + protected void createOrUpdateResourceReg(String resourceName, String jmxUrl, EntityTransaction et) { + TypedQuery<ResourceRegistrationEntity> rquery = + em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn", + ResourceRegistrationEntity.class); + rquery.setParameter("rn", resourceName); + + List<ResourceRegistrationEntity> rrList = + rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + ResourceRegistrationEntity rrx; + if (!rrList.isEmpty()) { + // ignores multiple results + rrx = rrList.get(0); + // refresh the object from DB in case cached data was returned + em.refresh(rrx); + if (logger.isDebugEnabled()) { + logger.debug("Resource {} exists and will be updated - old url= {}, createdDate={}", resourceName, + rrx.getResourceUrl(), rrx.getCreatedDate()); + } + rrx.setLastUpdated(MonitorTime.getInstance().getDate()); + } else { + // register resource by adding entry to table in DB + logger.debug("Adding resource {} to ResourceRegistration table", resourceName); + rrx = new ResourceRegistrationEntity(); + } + // update/set columns in entry + rrx.setResourceName(resourceName); + rrx.setResourceUrl(jmxUrl); + rrx.setNodeType(nodeType); + rrx.setSite(siteName); + em.persist(rrx); + // flush to the DB + synchronized (imFlushLock) { + et.commit(); + } + } + + protected void makeStateManager(String resourceName) throws IntegrityMonitorException { try { // create instance of StateManagement class and pass emf to it stateManager = new StateManagement(emf, resourceName); - /** - * Initialize the state and status attributes. This will maintain any Administrative - * state value but will set the operational state = enabled, availability status = null, - * standby status = null. The integrity monitor will set the operational state via the - * FPManager and the owning application must set the standby status by calling - * promote/demote on the StateManager. + /* + * Initialize the state and status attributes. This will maintain any Administrative state value but will + * set the operational state = enabled, availability status = null, standby status = null. The integrity + * monitor will set the operational state via the FPManager and the owning application must set the standby + * status by calling promote/demote on the StateManager. */ stateManager.initializeState(); } catch (StateManagementException e) { throw new IntegrityMonitorException(e); } + } - // create management bean + protected void makeManagementBean(String resourceName) { try { new ComponentAdmin(resourceName, this, stateManager); } catch (Exception e) { - logger.error("ComponentAdmin constructor exception: {}", e.toString(), e); + logger.error("ComponentAdmin constructor exception: {}", e, e); } + } - // set now as the last time the refreshStateAudit ran - IntegrityMonitor.this.refreshStateAuditLastRunDate = MonitorTime.getInstance().getDate(); - - fpManager = new Thread(this::runFpManager); - fpManager.start(); - + private static void setInstance(IntegrityMonitor newInstance, String newResourceName) { + instance = newInstance; + resourceName = newResourceName; } /** @@ -363,12 +390,12 @@ public class IntegrityMonitor { * instance is allowed to be created per resource name. * * @param resourceName The resource name of the resource - * @param properties a set of properties passed in from the resource + * @param properties a set of properties passed in from the resource * @return The new instance of IntegrityMonitor * @throws IntegrityMonitorException if unable to create jmx url or the constructor returns an exception */ public static IntegrityMonitor getInstance(String resourceName, Properties properties) - throws IntegrityMonitorException { + throws IntegrityMonitorException { synchronized (getInstanceLock) { logger.debug("getInstance() called - resourceName= {}", resourceName); @@ -379,7 +406,8 @@ public class IntegrityMonitor { if (instance == null) { logger.debug("Creating new instance of IntegrityMonitor"); - instance = new IntegrityMonitor(resourceName, properties); + // note: new() will populate "instance" + new IntegrityMonitor(resourceName, properties); } return instance; } @@ -395,7 +423,7 @@ public class IntegrityMonitor { logger.debug("getInstance() called"); if (instance == null) { String msg = "No IntegrityMonitor instance exists." - + " Please use the method IntegrityMonitor.getInstance(String resourceName, Properties properties)"; + + " Please use the method IntegrityMonitor.getInstance(String resourceName, Properties properties)"; throw new IntegrityMonitorPropertiesException(msg); } else { return instance; @@ -411,7 +439,7 @@ public class IntegrityMonitor { synchronized (getInstanceLock) { if (isUnitTesting() && instance != null && instance.fpManager != null) { // Stop the FPManager thread - Thread fpm = instance.fpManager; + Thread fpm = instance.fpManager.get(); instance.fpManager = null; fpm.interrupt(); @@ -426,7 +454,7 @@ public class IntegrityMonitor { if (fpm.isAlive()) { logger.error("IntegrityMonitor.deleteInstance() Failed to kill FPManager thread"); throw new IntegrityMonitorException( - "IntegrityMonitor.deleteInstance() Failed to kill FPManager thread"); + "IntegrityMonitor.deleteInstance() Failed to kill FPManager thread"); } instance = null; @@ -438,7 +466,7 @@ public class IntegrityMonitor { private static String getJmxUrlFromProps() throws IntegrityMonitorException { // get the jmx remote port and construct the JMX URL - Properties systemProps = System.getProperties(); + var systemProps = System.getProperties(); String jmxPort = systemProps.getProperty("com.sun.management.jmxremote.port"); String jmxErrMsg; if (jmxPort == null) { @@ -447,7 +475,7 @@ public class IntegrityMonitor { throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg); } - int port = 0; + var port = 0; try { port = Integer.parseInt(jmxPort); } catch (NumberFormatException e) { @@ -462,12 +490,12 @@ public class IntegrityMonitor { jmxFqdn = InetAddress.getLocalHost().getCanonicalHostName(); } } catch (Exception e) { - String msg = "getJmxUrl could not get hostname"; + var msg = "getJmxUrl could not get hostname"; logger.error("{}", msg, e); throw new IntegrityMonitorException("getJmxUrl Exception: " + msg); } if (jmxFqdn == null) { - String msg = "getJmxUrl encountered null hostname"; + var msg = "getJmxUrl encountered null hostname"; logger.error("{}", msg); throw new IntegrityMonitorException("getJmxUrl error: " + msg); } @@ -506,7 +534,7 @@ public class IntegrityMonitor { } // check standby state and throw exception if cold standby if ((stateManager.getStandbyStatus() != null) - && stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) { + && stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) { String msg = RESOURCE_STRING + resourceName + " is cold standby"; logger.debug("{}", msg); throw new StandbyStatusException("IntegrityMonitor Standby Status Exception: " + msg); @@ -531,21 +559,22 @@ public class IntegrityMonitor { String errorMsg = withinTransaction(dep + ": ForwardProgressEntity DB operation failed with exception: ", () -> { - Query query = em.createQuery( - "Select p from ForwardProgressEntity p where p.resourceName=:resource"); + TypedQuery<ForwardProgressEntity> query = em.createQuery( + "Select p from ForwardProgressEntity p where p.resourceName=:resource", + ForwardProgressEntity.class); query.setParameter(LC_RESOURCE_STRING, dep); - @SuppressWarnings("rawtypes") - List fpList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT) - .getResultList(); + List<ForwardProgressEntity> fpList = query.setLockMode(LockModeType.NONE) + .setFlushMode(FlushModeType.COMMIT).getResultList(); if (!fpList.isEmpty()) { // exists - forwardProgressEntity.set((ForwardProgressEntity) fpList.get(0)); + forwardProgressEntity.set(fpList.get(0)); // refresh the object from DB in case cached data was // returned em.refresh(forwardProgressEntity.get()); - logger.debug("Found entry in ForwardProgressEntity table for dependent Resource={}", dep); + logger.debug("Found entry in ForwardProgressEntity table for dependent Resource={}", + dep); return null; } else { @@ -553,18 +582,20 @@ public class IntegrityMonitor { } }); - if (errorMsg == null) { + if (StringUtils.isEmpty(errorMsg)) { errorMsg = withinTransaction(dep + ": StateManagementEntity DB read failed with exception: ", () -> { // query if StateManagement entry exists for dependent resource - Query query = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource"); + TypedQuery<StateManagementEntity> query = + em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource", + StateManagementEntity.class); query.setParameter(LC_RESOURCE_STRING, dep); - @SuppressWarnings("rawtypes") - List smList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + List<StateManagementEntity> smList = + query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); if (!smList.isEmpty()) { // exist - stateManagementEntity.set((StateManagementEntity) smList.get(0)); + stateManagementEntity.set(smList.get(0)); // refresh the object from DB in case cached data was // returned em.refresh(stateManagementEntity.get()); @@ -577,12 +608,12 @@ public class IntegrityMonitor { } // verify that the ForwardProgress is current (check last_updated) - if (errorMsg == null) { + if (StringUtils.isEmpty(errorMsg)) { checkForwardProgress(dep, forwardProgressEntity.get(), stateManagementEntity.get()); } // check operation, admin and standby states of dependent resource - if (errorMsg == null) { + if (StringUtils.isEmpty(errorMsg)) { errorMsg = checkDependentStates(dep, stateManagementEntity.get()); } @@ -594,45 +625,38 @@ public class IntegrityMonitor { /** * Runs an action within a transaction. * - * @param exMsg message to log and return if an exception occurs + * @param exMsg message to log and return if an exception occurs * @param action action to apply; returns non-null if an error occurs * @return {@code null} if success, or an error message otherwise */ private String withinTransaction(String exMsg, Supplier<String> action) { - String errorMsg = null; - // Start a transaction EntityTransaction et = em.getTransaction(); et.begin(); try { - errorMsg = action.get(); - if (errorMsg != null) { - logger.error("{}", errorMsg); - } - + var errorMsg = action.get(); + logger.error("{}", errorMsg); synchronized (imFlushLock) { et.commit(); } - + return errorMsg; } catch (RuntimeException ex) { // log an error - errorMsg = exMsg; - logger.error("{}", errorMsg, ex); + logger.error("{}", exMsg, ex); synchronized (imFlushLock) { if (et.isActive()) { et.rollback(); } } + return exMsg; } - - return errorMsg; } private void checkForwardProgress(String dep, ForwardProgressEntity forwardProgressEntity, - StateManagementEntity stateManagementEntity) { + StateManagementEntity stateManagementEntity) { if (forwardProgressEntity != null && stateManagementEntity != null) { - Date date = MonitorTime.getInstance().getDate(); + var date = MonitorTime.getInstance().getDate(); long diffMs = date.getTime() - forwardProgressEntity.getLastUpdated().getTime(); logger.debug("IntegrityMonitor.stateCheck(): diffMs = {}", diffMs); @@ -646,15 +670,13 @@ public class IntegrityMonitor { } } else { + String msg; if (forwardProgressEntity == null) { - String msg = STATE_CHECK_STRING + dep - + "; " + " forwardProgressEntity == null."; - logger.error("{}", msg); + msg = STATE_CHECK_STRING + dep + "; " + " forwardProgressEntity == null."; } else { - String msg = STATE_CHECK_STRING + dep - + "; " + " stateManagementEntity == null."; - logger.error("{}", msg); + msg = STATE_CHECK_STRING + dep + "; " + " stateManagementEntity == null."; } + logger.error("{}", msg); } } @@ -663,15 +685,15 @@ public class IntegrityMonitor { if (stateManagementEntity != null) { if ((stateManager.getAdminState() != null) - && stateManagementEntity.getAdminState().equals(StateManagement.LOCKED)) { + && stateManagementEntity.getAdminState().equals(StateManagement.LOCKED)) { errorMsg = dep + ": resource is administratively locked"; logger.error("{}", errorMsg); } else if ((stateManager.getOpState() != null) - && stateManagementEntity.getOpState().equals(StateManagement.DISABLED)) { + && stateManagementEntity.getOpState().equals(StateManagement.DISABLED)) { errorMsg = dep + ": resource is operationally disabled"; logger.error("{}", errorMsg); } else if ((stateManager.getStandbyStatus() != null) - && stateManagementEntity.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) { + && stateManagementEntity.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) { errorMsg = dep + ": resource is cold standby"; logger.error("{}", errorMsg); } @@ -690,20 +712,20 @@ public class IntegrityMonitor { } private String fpCheck2(String dep) { - Query fquery = em.createQuery(QUERY_STRING); + TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class); fquery.setParameter("rn", dep); - @SuppressWarnings("rawtypes") - List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + List<ForwardProgressEntity> fpList = + fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); ForwardProgressEntity fpx; if (!fpList.isEmpty()) { // ignores multiple results - fpx = (ForwardProgressEntity) fpList.get(0); + fpx = fpList.get(0); // refresh the object from DB in case cached data was returned em.refresh(fpx); if (logger.isDebugEnabled()) { logger.debug("Dependent resource {} - fpc= {}, lastUpdated={}", dep, fpx.getFpcCount(), - fpx.getLastUpdated()); + fpx.getLastUpdated()); } long currTime = MonitorTime.getInstance().getMillis(); // if dependent resource FPC has not been updated, consider it @@ -733,9 +755,9 @@ public class IntegrityMonitor { ArrayList<ForwardProgressEntity> fpList = new ArrayList<>(); withinTransaction("getAllForwardProgessEntity DB read failed with exception: ", () -> { - Query fquery = em.createQuery("Select e from ForwardProgressEntity e"); + var fquery = em.createQuery("Select e from ForwardProgressEntity e"); fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList() - .forEach(obj -> fpList.add((ForwardProgressEntity) obj)); + .forEach(obj -> fpList.add((ForwardProgressEntity) obj)); return null; }); @@ -744,10 +766,10 @@ public class IntegrityMonitor { } logger.debug("getAllForwardProgressEntity: fpList.size(): {}", fpList.size()); - int index = 0; + var index = 0; for (ForwardProgressEntity fpe : fpList) { logger.debug("getAllForwardProgressEntity: fpList.get({}).getResourceName(): {}", index++, - fpe.getResourceName()); + fpe.getResourceName()); } return fpList; @@ -759,9 +781,8 @@ public class IntegrityMonitor { // get the JMX URL from the database AtomicReference<String> jmxUrl = new AtomicReference<>(); - String errorMsg = - withinTransaction(dep + ": ResourceRegistrationEntity DB read failed with exception: ", - () -> getJmxUrlFromDb(dep, jmxUrl)); + String errorMsg = withinTransaction(dep + ": ResourceRegistrationEntity DB read failed with exception: ", + () -> getJmxUrlFromDb(dep, jmxUrl)); if (jmxUrl.get() != null) { errorMsg = jmxCheck2(dep, jmxUrl.get(), errorMsg); @@ -772,25 +793,24 @@ public class IntegrityMonitor { private String getJmxUrlFromDb(String dep, AtomicReference<String> jmxUrl) { // query if ResourceRegistration entry exists for resourceName - Query rquery = em.createQuery( - "Select r from ResourceRegistrationEntity r where r.resourceName=:rn"); + TypedQuery<ResourceRegistrationEntity> rquery = + em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn", + ResourceRegistrationEntity.class); rquery.setParameter("rn", dep); - @SuppressWarnings("rawtypes") - List rrList = rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT) - .getResultList(); - ResourceRegistrationEntity rrx = null; + List<ResourceRegistrationEntity> rrList = + rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + ResourceRegistrationEntity rrx; if (!rrList.isEmpty()) { // ignores multiple results - rrx = (ResourceRegistrationEntity) rrList.get(0); + rrx = rrList.get(0); // refresh the object from DB in case cached data was // returned em.refresh(rrx); jmxUrl.set(rrx.getResourceUrl()); if (logger.isDebugEnabled()) { - logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl.get(), - rrx.getCreatedDate()); + logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl.get(), rrx.getCreatedDate()); } return null; @@ -806,7 +826,7 @@ public class IntegrityMonitor { jmxAgentConnection = new JmxAgentConnection(jmxUrl); MBeanServerConnection mbeanServer = jmxAgentConnection.getMBeanConnection(); ComponentAdminMBean admin = - JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class); + JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class); // invoke the test method via the jmx proxy admin.test(); @@ -834,7 +854,7 @@ public class IntegrityMonitor { synchronized (dependencyCheckLock) { // Start with the error message empty - StringBuilder errorMsg = new StringBuilder(); + var errorMsg = new StringBuilder(); /* * Before we check dependency groups we need to check subsystemTest. @@ -846,18 +866,17 @@ public class IntegrityMonitor { dependencyOk = checkDependencies(errorMsg) && dependencyOk; /* - * We have checked all the dependency groups. If all are ok and subsystemTest - * passed, dependencyFailure == false + * We have checked all the dependency groups. If all are ok and subsystemTest passed, dependencyFailure + * == false */ if (dependencyOk) { dependenciesGood(errorMsg); } } else if (dependencyOk) { /* - * This is put here to clean up when no dependency group should exist, but one was - * erroneously added which caused the state to be disabled/dependency/coldstandby - * and later removed. We saw this happen in the lab, but is not very likely in a - * production environment...but you never know. + * This is put here to clean up when no dependency group should exist, but one was erroneously added + * which caused the state to be disabled/dependency/coldstandby and later removed. We saw this happen in + * the lab, but is not very likely in a production environment...but you never know. */ noDependencyGroups(errorMsg); } @@ -893,10 +912,8 @@ public class IntegrityMonitor { // This indicates a subsystemTest failure try { if (logger.isDebugEnabled()) { - logger.debug( - "{}: There has been a subsystemTest failure with error:{} Updating this resource's " - + "state to disableDependency", - resourceName, e.getMessage()); + logger.debug("{}: There has been a subsystemTest failure with error:{} Updating this resource's " + + "state to disableDependency", resourceName, e.getMessage()); } // Capture the subsystemTest failure info appendSeparator(errorMsg); @@ -924,7 +941,7 @@ public class IntegrityMonitor { * @return {@code true} if the dependencies are OK, {@code false} otherwise */ private boolean checkDependencies(StringBuilder errorMsg) { - boolean dependencyOk = true; + var dependencyOk = true; // check state of resources in dependency groups for (String group : depGroups) { @@ -936,7 +953,7 @@ public class IntegrityMonitor { } // check the next group - } // end for (String group : depGroups) + } return dependencyOk; } @@ -944,7 +961,7 @@ public class IntegrityMonitor { /** * Checks if a dependency group has an error. * - * @param group group to be checked + * @param group group to be checked * @param errorMsg error messages are appended here * @return {@code true} if the group has an error, {@code false} otherwise */ @@ -954,12 +971,12 @@ public class IntegrityMonitor { // ignore empty group return false; } - String[] dependencies = group.split(","); + String[] dependencies = COMMA_PAT.split(group); if (logger.isDebugEnabled()) { logger.debug("group dependencies = {}", Arrays.toString(dependencies)); } - int realDepCount = 0; - int failDepCount = 0; + var realDepCount = 0; + var failDepCount = 0; for (String dep : dependencies) { dep = dep.trim(); if (dep.isEmpty()) { @@ -974,7 +991,7 @@ public class IntegrityMonitor { appendSeparator(errorMsg); errorMsg.append(failMsg); } - } // end for (String dep : dependencies) + } // if all dependencies in a group are failed, set this // resource's state to disable dependency @@ -1005,16 +1022,16 @@ public class IntegrityMonitor { * Disables the dependency group. * * @param errorMsg error messages are appended to this - * @param group group of interest + * @param group group of interest * @return {@code true} if it was successfully disabled, {@code false} otherwise */ private boolean disableDependency(StringBuilder errorMsg, String group) { try { logger.debug("All dependents in group {} have failed their health check. Updating this " - + "resource's state to disableDependency", group); - if (stateManager.getAvailStatus() == null || !((stateManager.getAvailStatus()) - .equals(StateManagement.DEPENDENCY) - || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) { + + "resource's state to disableDependency", group); + if (stateManager.getAvailStatus() == null + || !((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY) + || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) { // Note: redundant calls are made by // refreshStateAudit this.stateManager.disableDependency(); @@ -1033,12 +1050,11 @@ public class IntegrityMonitor { private void dependenciesGood(StringBuilder errorMsg) { try { - logger.debug( - "All dependency groups have at least one viable member. Updating this resource's state" - + " to enableNoDependency"); + logger.debug("All dependency groups have at least one viable member. Updating this resource's state" + + " to enableNoDependency"); if (stateManager.getAvailStatus() != null - && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY) - || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) { + && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY) + || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) { // Note: redundant calls are made by // refreshStateAudit this.stateManager.enableNoDependency(); @@ -1057,8 +1073,8 @@ public class IntegrityMonitor { try { logger.debug("There are no dependents. Updating this resource's state to enableNoDependency"); if (stateManager.getAvailStatus() != null - && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY) - || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) { + && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY) + || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) { // Note: redundant calls are made by refreshStateAudit this.stateManager.enableNoDependency(); } @@ -1073,7 +1089,7 @@ public class IntegrityMonitor { } private void appendSeparator(StringBuilder errorMsg) { - if (errorMsg.length() != 0) { + if (!errorMsg.isEmpty()) { errorMsg.append(','); } } @@ -1099,9 +1115,8 @@ public class IntegrityMonitor { * Additional testing for subsystems that do not have a /test interface (for ex. 3rd party processes like elk). This * method would be overridden by the subsystem. * - * @throws IntegrityMonitorException if an error occurs */ - public void subsystemTest() throws IntegrityMonitorException { + public void subsystemTest() { // Testing provided by subsystem logger.debug("IntegrityMonitor subsystemTest() OK"); } @@ -1123,8 +1138,8 @@ public class IntegrityMonitor { // check standby state and throw exception if locked if ((stateManager.getStandbyStatus() != null) - && (stateManager.getStandbyStatus().equals(StateManagement.HOT_STANDBY) - || stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY))) { + && (stateManager.getStandbyStatus().equals(StateManagement.HOT_STANDBY) + || stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY))) { String msg = RESOURCE_STRING + resourceName + " is standby"; throw new StandbyStatusException("IntegrityMonitor Standby Status Exception: " + msg); @@ -1144,26 +1159,28 @@ public class IntegrityMonitor { if (getAllNotWellMap() != null) { if (!(getAllNotWellMap().isEmpty())) { /* - * An entity has reported that it is not well. We must not allow the the forward - * progress counter to advance. + * An entity has reported that it is not well. We must not allow the forward progress counter to + * advance. */ - String msg = "allNotWellMap:"; - for (Entry<String, String> entry : allNotWellMap.entrySet()) { - msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue()); - } - logger.error("endTransaction: allNotWellMap is NOT EMPTY. Not advancing forward" - + "progress counter. \n{}\n", msg); + var msg = new StringBuilder("allNotWellMap:"); + buildMapString(msg, allNotWellMap); + logger.error( + """ + endTransaction: allNotWellMap is NOT EMPTY. Not advancing forward progress counter. + {} + """, msg); return; } if (logger.isDebugEnabled() && getAllSeemsWellMap() != null && !(getAllSeemsWellMap().isEmpty())) { - String msg = "allSeemsWellMap:"; - for (Entry<String, String> entry : allSeemsWellMap.entrySet()) { - msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue()); - } + var msg = new StringBuilder("allSeemsWellMap:"); + buildMapString(msg, allSeemsWellMap); logger.debug( - "endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY. " - + "Advancing forward progress counter. \n{}\n", msg); + """ + endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY. + Advancing forward progress counter. + {} + """, msg); } } // increment local FPC @@ -1171,6 +1188,15 @@ public class IntegrityMonitor { } } + private void buildMapString(StringBuilder msg, Map<String, String> map) { + for (Entry<String, String> entry : map.entrySet()) { + msg.append("\nkey = "); + msg.append(entry.getKey()); + msg.append(" msg = "); + msg.append(entry.getValue()); + } + } + // update FP count in DB with local FP count private void writeFpc() throws IntegrityMonitorException { @@ -1183,20 +1209,20 @@ public class IntegrityMonitor { try { // query if ForwardProgress entry exists for resourceName - Query fquery = em.createQuery(QUERY_STRING); + TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class); fquery.setParameter("rn", resourceName); - @SuppressWarnings("rawtypes") - List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + List<ForwardProgressEntity> fpList = + fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); ForwardProgressEntity fpx; if (!fpList.isEmpty()) { // ignores multiple results - fpx = (ForwardProgressEntity) fpList.get(0); + fpx = fpList.get(0); // refresh the object from DB in case cached data was returned em.refresh(fpx); if (logger.isDebugEnabled()) { logger.debug("Updating FP entry: Resource={}, fpcCount={}, lastUpdated={}, new fpcCount={}", - resourceName, fpx.getFpcCount(), fpx.getLastUpdated(), fpCounter); + resourceName, fpx.getFpcCount(), fpx.getLastUpdated(), fpCounter); } fpx.setFpcCount(fpCounter); em.persist(fpx); @@ -1219,16 +1245,11 @@ public class IntegrityMonitor { } catch (Exception e1) { logger.error(EXCEPTION_STRING, e1); } - logger.error("writeFpc DB table commit failed with exception: {}", e); + logger.error("writeFpc DB table commit failed with exception"); throw e; } } - // retrieve state manager reference - public final StateManagement getStateManager() { - return this.stateManager; - } - /** * Read and validate properties. * @@ -1241,28 +1262,24 @@ public class IntegrityMonitor { checkNonNull(prop, IntegrityMonitorProperties.DB_USER); checkNonNull(prop, IntegrityMonitorProperties.DB_PWD); - setLong(prop, IntegrityMonitorProperties.FP_MONITOR_INTERVAL, - value -> monitorIntervalMs = toMillis(value)); + setLong(prop, IntegrityMonitorProperties.FP_MONITOR_INTERVAL, value -> monitorIntervalMs = toMillis(value)); - setInt(prop, IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, - value -> failedCounterThreshold = value); + setInt(prop, value -> failedCounterThreshold = value); - setLong(prop, IntegrityMonitorProperties.TEST_TRANS_INTERVAL, - value -> testTransIntervalMs = toMillis(value)); + setLong(prop, IntegrityMonitorProperties.TEST_TRANS_INTERVAL, value -> testTransIntervalMs = toMillis(value)); - setLong(prop, IntegrityMonitorProperties.WRITE_FPC_INTERVAL, - value -> writeFpcIntervalMs = toMillis(value)); + setLong(prop, IntegrityMonitorProperties.WRITE_FPC_INTERVAL, value -> writeFpcIntervalMs = toMillis(value)); setLong(prop, IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL, value -> checkDependencyIntervalMs = toMillis(value)); - // dependency_groups are a semi-colon separated list of groups + // dependency_groups are a semicolon separated list of groups // each group is a comma separated list of resource names // For ex. dependency_groups = site_1.pap_1,site_1.pap_2 ; site_1.pdp_1, // site_1.pdp_2 String depGroupsValue = prop.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS); if (!StringUtils.isBlank(depGroupsValue)) { - depGroups = depGroupsValue.split(";"); + depGroups = SEMICOLON_PAT.split(depGroupsValue); if (logger.isDebugEnabled()) { logger.debug("dependency groups property = {}", Arrays.toString(depGroups)); } @@ -1285,14 +1302,13 @@ public class IntegrityMonitor { setLong(prop, IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL, value -> maxFpcUpdateIntervalMs = toMillis(value)); - setLong(prop, IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, - value -> stateAuditIntervalMs = value); + setLong(prop, IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, value -> stateAuditIntervalMs = value); setLong(prop, IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, value -> refreshStateAuditIntervalMs = value); logger.debug("IntegrityMonitor.validateProperties(): Property values \nmaxFpcUpdateIntervalMs = {}\n", - maxFpcUpdateIntervalMs); + maxFpcUpdateIntervalMs); } private static void setBoolean(Properties props, String propName, Consumer<Boolean> setter) { @@ -1302,8 +1318,7 @@ public class IntegrityMonitor { } } - private static String checkNonNull(Properties props, String propName) - throws IntegrityMonitorPropertiesException { + private static String checkNonNull(Properties props, String propName) throws IntegrityMonitorPropertiesException { String propValue = props.getProperty(propName); if (propValue == null) { @@ -1315,8 +1330,8 @@ public class IntegrityMonitor { return propValue.trim(); } - private static void setInt(Properties props, String propName, Consumer<Integer> setter) { - String propValue = props.getProperty(propName); + private static void setInt(Properties props, IntConsumer setter) { + String propValue = props.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD); if (StringUtils.isBlank(propValue)) { return; } @@ -1324,11 +1339,11 @@ public class IntegrityMonitor { try { setter.accept(Integer.parseInt(propValue.trim())); } catch (NumberFormatException e) { - logger.warn(IGNORE_INVALID_PROPERTY_STRING, propName, e); + logger.warn(IGNORE_INVALID_PROPERTY_STRING, IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, e); } } - private static void setLong(Properties props, String propName, Consumer<Long> setter) { + private static void setLong(Properties props, String propName, LongConsumer setter) { String propValue = props.getProperty(propName); if (StringUtils.isBlank(propValue)) { return; @@ -1409,7 +1424,7 @@ public class IntegrityMonitor { missedCycles += 1; if (missedCycles >= failedCounterThreshold && !alarmExists) { logger.debug("Forward progress not detected for resource {}. Setting state to disable failed.", - resourceName); + resourceName); if (!(stateManager.getOpState()).equals(StateManagement.DISABLED)) { // Note: The refreshStateAudit will make redundant // calls @@ -1425,8 +1440,7 @@ public class IntegrityMonitor { lastFpCounter = fpCounter; missedCycles = 0; // set op state to enabled - logger.debug("Forward progress detected for resource {}. Setting state to enable not failed.", - resourceName); + logger.debug("Forward progress detected for resource {}. Setting state to enable not failed.", resourceName); if (!(stateManager.getOpState()).equals(StateManagement.ENABLED)) { // Note: The refreshStateAudit will make redundant calls stateManager.enableNotFailed(); @@ -1457,13 +1471,13 @@ public class IntegrityMonitor { return; } if (!stateManager.getStandbyStatus().equals(StateManagement.NULL_VALUE) - && stateManager.getStandbyStatus() != null - && !stateManager.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)) { + && stateManager.getStandbyStatus() != null + && !stateManager.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)) { logger.debug("IntegrityMonitor.stateAudit(): NOT PROVIDING_SERVICE. returning"); return; } - Date date = MonitorTime.getInstance().getDate(); + var date = MonitorTime.getInstance().getDate(); long timeSinceLastStateAudit = date.getTime() - lastStateAuditTime.getTime(); if (timeSinceLastStateAudit < stateAuditIntervalMs) { logger.debug("IntegrityMonitor.stateAudit(): Not time to run. returning"); @@ -1482,14 +1496,14 @@ public class IntegrityMonitor { */ public void executeStateAudit() { logger.debug("IntegrityMonitor.executeStateAudit(): entry"); - Date date = MonitorTime.getInstance().getDate(); + var date = MonitorTime.getInstance().getDate(); // Get all entries in the forwardprogressentity table List<ForwardProgressEntity> fpList = getAllForwardProgressEntity(); // Check if each forwardprogressentity entry is current for (ForwardProgressEntity fpe : fpList) { - // If the this is my ForwardProgressEntity, continue + // If this is my ForwardProgressEntity, continue if (fpe.getResourceName().equals(IntegrityMonitor.resourceName)) { continue; } @@ -1498,21 +1512,21 @@ public class IntegrityMonitor { long diffMs = date.getTime() - fpe.getLastUpdated().getTime(); if (logger.isDebugEnabled()) { logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, diffMs = {}", fpe.getResourceName(), - diffMs); + diffMs); } // Threshold for a stale entry long staleMs = maxFpcUpdateIntervalMs; if (logger.isDebugEnabled()) { logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, staleMs = {}", fpe.getResourceName(), - staleMs); + staleMs); } if (diffMs > staleMs) { // ForwardProgress is stale. Disable it // Start a transaction logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, FPC is stale. Disabling it", - fpe.getResourceName()); + fpe.getResourceName()); EntityTransaction et = em.getTransaction(); et.begin(); StateManagementEntity sme = disableEntity(et, fpe); @@ -1520,15 +1534,16 @@ public class IntegrityMonitor { if (sme != null && !sme.getOpState().equals(StateManagement.DISABLED)) { disableFailed(sme); } - } // end if(diffMs > staleMs) - } // end for(ForwardProgressEntity fpe : fpList) + } + } logger.debug("IntegrityMonitor.executeStateAudit(): exit"); } /** * Disables the entity. + * * @param entrans entity transaction - * @param fpe entity of interest + * @param fpe entity of interest * @return the corresponding state management entity */ private StateManagementEntity disableEntity(EntityTransaction entrans, ForwardProgressEntity fpe) { @@ -1536,28 +1551,26 @@ public class IntegrityMonitor { try { // query if StateManagement entry exists for fpe resource - Query query = - em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource"); + TypedQuery<StateManagementEntity> query = + em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource", + StateManagementEntity.class); query.setParameter(LC_RESOURCE_STRING, fpe.getResourceName()); - @SuppressWarnings("rawtypes") - List smList = - query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + List<StateManagementEntity> smList = + query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); if (!smList.isEmpty()) { // exists - sme = (StateManagementEntity) smList.get(0); + sme = smList.get(0); // refresh the object from DB in case cached data was // returned em.refresh(sme); if (logger.isDebugEnabled()) { - logger.debug( - "IntegrityMonitor.executeStateAudit(): Found entry in StateManagementEntity table " - + "for Resource={}", - sme.getResourceName()); + logger.debug("IntegrityMonitor.executeStateAudit(): Found entry in StateManagementEntity table " + + "for Resource={}", sme.getResourceName()); } } else { String msg = "IntegrityMonitor.executeStateAudit(): " + fpe.getResourceName() - + ": resource not found in state management entity database table"; + + ": resource not found in state management entity database table"; logger.error("{}", msg); } synchronized (imFlushLock) { @@ -1566,7 +1579,7 @@ public class IntegrityMonitor { } catch (Exception e) { // log an error logger.error("IntegrityMonitor.executeStateAudit(): {}: StateManagementEntity DB read failed with " - + "exception: ", fpe.getResourceName(), e); + + "exception: ", fpe.getResourceName(), e); synchronized (imFlushLock) { if (entrans.isActive()) { entrans.rollback(); @@ -1584,19 +1597,18 @@ public class IntegrityMonitor { stateManager.disableFailed(dep); } } catch (Exception e) { - String msg = STATE_CHECK_STRING + dep - + "; " + e.getMessage(); + String msg = STATE_CHECK_STRING + dep + "; " + e.getMessage(); logger.error("{}", msg, e); } } private void disableEntity(String dep) { try { - // create instance of StateMangement class for dependent - StateManagement depStateManager = new StateManagement(emf, dep); + // create instance of StateManagement class for dependent + var depStateManager = new StateManagement(emf, dep); if (!depStateManager.getOpState().equals(StateManagement.DISABLED)) { logger.debug("Forward progress not detected for dependent resource {}. Setting dependent's " - + "state to disable failed.", dep); + + "state to disable failed.", dep); depStateManager.disableFailed(); } } catch (Exception e) { @@ -1607,12 +1619,13 @@ public class IntegrityMonitor { /** * Indicates a failure to disable an entity. + * * @param sme entity of interest */ private void disableFailed(StateManagementEntity sme) { if (logger.isDebugEnabled()) { logger.debug("IntegrityMonitor.executeStateAudit(): Changing OpStat = disabled for {}", - sme.getResourceName()); + sme.getResourceName()); } try { stateManager.disableFailed(sme.getResourceName()); @@ -1692,7 +1705,7 @@ public class IntegrityMonitor { long currTime = MonitorTime.getInstance().getMillis(); logger.debug("checkDependentHealth currTime - lastDependencyCheckTime = {}", - currTime - lastDependencyCheckTime); + currTime - lastDependencyCheckTime); if ((currTime - lastDependencyCheckTime) > checkDependencyIntervalMs) { // execute dependency check and update this resource's state @@ -1702,13 +1715,13 @@ public class IntegrityMonitor { } /* - * This is a simple refresh audit which is periodically run to assure that the states and status - * attributes are aligned and notifications are sent to any listeners. It is possible for - * state/status to get out of sync and notified systems to be out of synch due to database - * corruption (manual or otherwise) or because a node became isolated. + * This is a simple refresh audit which is periodically run to assure that the states and status attributes are + * aligned and notifications are sent to any listeners. It is possible for state/status to get out of sync and + * notified systems to be out of sync due to database corruption (manual or otherwise) or because a node became + * isolated. * - * When the operation (lock/unlock) is called, it will cause a re-evaluation of the state and - * send a notification to all registered observers. + * When the operation (lock/unlock) is called, it will cause a re-evaluation of the state and send a notification to + * all registered observers. */ private void refreshStateAudit() { logger.debug("refreshStateAudit(): entry"); @@ -1728,7 +1741,7 @@ public class IntegrityMonitor { logger.debug("executeRefreshStateAudit(): entry"); synchronized (refreshStateAuditLock) { logger.debug("refreshStateAudit: entry"); - Date now = MonitorTime.getInstance().getDate(); + var now = MonitorTime.getInstance().getDate(); long nowMs = now.getTime(); long lastTimeMs = refreshStateAuditLastRunDate.getTime(); logger.debug("refreshStateAudit: ms since last run = {}", nowMs - lastTimeMs); @@ -1814,10 +1827,8 @@ public class IntegrityMonitor { * @param key the key * @param asw <code>true</code> if all seems well for the key, <code>false</code> if all seems not well for the key * @param msg message to add for the key - * @throws AllSeemsWellException if an error occurs */ - public void allSeemsWell(String key, Boolean asw, String msg) - throws AllSeemsWellException { + public void allSeemsWell(String key, Boolean asw, String msg) { logger.debug("allSeemsWell entry: key = {}, asw = {}, msg = {}", key, asw, msg); if (StringUtils.isEmpty(key)) { @@ -1841,7 +1852,7 @@ public class IntegrityMonitor { allNotWellMap = new HashMap<>(); } - if (asw) { + if (Boolean.TRUE.equals(asw)) { logger.info("allSeemsWell: ALL SEEMS WELL: key = {}, msg = {}", key, msg); allSeemsWellMap.put(key, msg); allNotWellMap.remove(key); @@ -1864,7 +1875,7 @@ public class IntegrityMonitor { } /** - * Converts the given value to milliseconds using the current {@link #propertyUnits}. + * Converts the given value to milliseconds using the current propertyUnits. * * @param value value to be converted, or -1 * @return the value, in milliseconds, or -1 @@ -1873,19 +1884,10 @@ public class IntegrityMonitor { return (value < 0 ? -1 : value * 1000L); } - public Map<String, String> getAllSeemsWellMap() { - return allSeemsWellMap; - } - - public Map<String, String> getAllNotWellMap() { - return allNotWellMap; - } - // these methods may be overridden by junit tests /** - * Indicates that the {@link FpManager#run()} method has started. This method - * simply returns. + * Indicates that the {FpManager#run()} method has started. This method simply returns. * * @throws InterruptedException can be interrupted */ @@ -1910,16 +1912,4 @@ public class IntegrityMonitor { protected String getPersistenceUnit() { return PERSISTENCE_UNIT; } - - /* - * The remaining methods are used by JUnit tests. - */ - - public static boolean isUnitTesting() { - return isUnitTesting; - } - - public static void setUnitTesting(boolean isUnitTesting) { - IntegrityMonitor.isUnitTesting = isUnitTesting; - } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java index 252fd27b..6af7a557 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * Copyright (C) 2017-2018, 2020 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. @@ -20,12 +21,16 @@ package org.onap.policy.common.im; -public class IntegrityMonitorProperties { +import lombok.AccessLevel; +import lombok.NoArgsConstructor; - 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 +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class IntegrityMonitorProperties { + + 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 // intervals specified are in seconds public static final int DEFAULT_MONITOR_INTERVAL = 30; @@ -54,8 +59,4 @@ public class IntegrityMonitorProperties { // AllSeemsWell types public static final Boolean ALLNOTWELL = Boolean.FALSE; public static final Boolean ALLSEEMSWELL = Boolean.TRUE; - - private IntegrityMonitorProperties() { - // Private constructor to prevent subclassing - } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java index e489a8c1..61afb682 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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. @@ -20,31 +20,20 @@ package org.onap.policy.common.im; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; import org.onap.policy.common.utils.time.CurrentTime; /** * "Current" time used by IntegrityMonitor classes. */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class MonitorTime { /** * Instance to be used. This is overridden by junit tests. */ + @Getter private static CurrentTime instance = new CurrentTime(); - - /** - * Constructor. - */ - private MonitorTime() { - super(); - } - - /** - * Get instance. - * - * @return the CurrentTime singleton - */ - public static CurrentTime getInstance() { - return instance; - } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java index eee3a9ef..5fc111e0 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * Copyright (C) 2017, 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2020-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. @@ -20,6 +20,7 @@ package org.onap.policy.common.im; +import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* @@ -43,6 +44,7 @@ import org.slf4j.LoggerFactory; * StateManagement class. * */ +@Getter public class StateChangeNotifier { private static final Logger logger = LoggerFactory.getLogger(StateChangeNotifier.class); // The observable class @@ -71,12 +73,4 @@ public class StateChangeNotifier { logger.debug("handleStateChange, message: {}", this.message); } } - - public StateManagement getStateManagement() { - return stateManagement; - } - - public String getMessage() { - return message; - } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java index 73724b30..d1bc9cc1 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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,12 +21,14 @@ package org.onap.policy.common.im; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Getter @Setter +@NoArgsConstructor public class StateElement { private static final Logger logger = LoggerFactory.getLogger(StateElement.class); @@ -41,10 +43,6 @@ public class StateElement { String endingStandbyStatus = null; String exception = null; - public StateElement() { - // Empty constructor - } - /** * Display the state element. */ diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java index 7a018ef9..eace6037 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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,16 +21,16 @@ package org.onap.policy.common.im; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.FlushModeType; +import jakarta.persistence.LockModeType; +import jakarta.persistence.TypedQuery; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.FlushModeType; -import javax.persistence.LockModeType; -import javax.persistence.TypedQuery; import org.onap.policy.common.im.exceptions.EntityRetrievalException; import org.onap.policy.common.im.jpa.StateManagementEntity; import org.onap.policy.common.utils.jpa.EntityMgrCloser; @@ -147,7 +148,7 @@ public class StateManagement { * was updated, {@code null} if no change was made * @throws StateManagementException if an error occurs */ - private void setState(String methodName, String resourceName, ExFunction<StateManagementEntity,String> updateState) + private void setState(String methodName, String resourceName, ExFunction<StateManagementEntity, String> updateState) throws StateManagementException { synchronized (SYNCLOCK) { @@ -155,13 +156,13 @@ public class StateManagement { resourceName); logger.debug("StateManagement: {}() operation started, resourceName = {}", methodName, resourceName); - final EntityManager em = emf.createEntityManager(); + final var em = emf.createEntityManager(); - try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) { + try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) { logger.debug(FIND_MESSAGE, resourceName); - final StateManagementEntity sm = findStateManagementEntity(em, resourceName); + final var sm = findStateManagementEntity(em, resourceName); String changed = updateState.update(sm); em.persist(sm); @@ -174,7 +175,6 @@ public class StateManagement { logger.debug("StateManagement: {}() operation completed, resourceName = {}", methodName, resourceName); } catch (final Exception ex) { - logger.error("StateManagement.{}() caught unexpected exception: ", methodName, ex); throw new StateManagementException("StateManagement." + methodName + "() Exception: " + ex); } } @@ -198,7 +198,7 @@ public class StateManagement { throws StateManagementException { setState(actionName, resourceName, sm -> { - final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(), + final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus(), actionName); sm.setAdminState(stateElement.getEndingAdminState()); @@ -293,7 +293,7 @@ public class StateManagement { AtomicReference<String> newStatus = new AtomicReference<>(); setState(PROMOTE_ACTION, resourceName, sm -> { - final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(), + final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus(), PROMOTE_ACTION); sm.setAdminState(stateElement.getEndingAdminState()); @@ -358,8 +358,8 @@ public class StateManagement { logger.debug("StateManagement(6/1/16): {} for resourceName {}", methodName, resourceName); - final EntityManager em = emf.createEntityManager(); - try (final EntityMgrCloser emc = new EntityMgrCloser(em)) { + final var em = emf.createEntityManager(); + try (final var emc = new EntityMgrCloser(em)) { final TypedQuery<StateManagementEntity> query = em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class); @@ -370,7 +370,7 @@ public class StateManagement { query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); if (!resourceList.isEmpty()) { // exist - final StateManagementEntity stateManagementEntity = resourceList.get(0); + final var stateManagementEntity = resourceList.get(0); // refresh the object from DB in case cached data was returned em.refresh(stateManagementEntity); function.accept(stateManagementEntity); @@ -378,7 +378,7 @@ public class StateManagement { notFound.run(); } } catch (final Exception ex) { - logger.error("StateManagement: {} exception: {}", methodName, ex.toString(), ex); + logger.error("StateManagement: {} exception: {}", methodName, ex.getMessage(), ex); } } @@ -459,14 +459,14 @@ public class StateManagement { query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); if (!resourceList.isEmpty()) { // exist - final StateManagementEntity stateManagementEntity = resourceList.get(0); + final var stateManagementEntity = resourceList.get(0); // refresh the object from DB in case cached data was returned em.refresh(stateManagementEntity); stateManagementEntity.setModifiedDate(MonitorTime.getInstance().getDate()); return stateManagementEntity; } else { // not exist - create one - final StateManagementEntity stateManagementEntity = new StateManagementEntity(); + final var stateManagementEntity = new StateManagementEntity(); stateManagementEntity.setResourceName(otherResourceName); stateManagementEntity.setAdminState(UNLOCKED); stateManagementEntity.setOpState(ENABLED); @@ -475,9 +475,7 @@ public class StateManagement { return stateManagementEntity; } } catch (final Exception ex) { - final String message = "findStateManagementEntity exception"; - logger.error("{}: {}", message, ex.toString(), ex); - throw new EntityRetrievalException(message, ex); + throw new EntityRetrievalException("findStateManagementEntity exception", ex); } } @@ -491,9 +489,9 @@ public class StateManagement { /* * Start transaction */ - final EntityManager em = emf.createEntityManager(); + final var em = emf.createEntityManager(); - try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) { + try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) { final TypedQuery<StateManagementEntity> stateManagementEntityListQuery = em.createQuery("SELECT p FROM StateManagementEntity p", StateManagementEntity.class); final List<StateManagementEntity> stateManagementEntityList = stateManagementEntityListQuery @@ -515,7 +513,7 @@ public class StateManagement { } @FunctionalInterface - private static interface ExFunction<T,R> { + private static interface ExFunction<T, R> { public R update(T object) throws IntegrityMonitorException; } @@ -533,7 +531,7 @@ public class StateManagement { @Override public void commit() { synchronized (FLUSHLOCK) { - if (getTransation().isActive()) { + if (getTransaction().isActive()) { super.commit(); } } @@ -542,7 +540,7 @@ public class StateManagement { @Override public void rollback() { synchronized (FLUSHLOCK) { - if (getTransation().isActive()) { + if (getTransaction().isActive()) { super.rollback(); } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java index 3542aa2c..2ebef874 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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. @@ -20,6 +20,7 @@ package org.onap.policy.common.im; +import com.google.re2j.Pattern; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -37,6 +38,8 @@ import org.slf4j.LoggerFactory; * The StateTransition class coordinates all state transitions. */ public class StateTransition { + private static final Pattern COMMA_PAT = Pattern.compile(","); + private static final String DEPENDENCY_FAILED = "dependency.failed"; private static final String ANY_DISABLED_ANY_COLDSTANDBY = "${1},disabled,${3},coldstandby,"; @@ -165,7 +168,7 @@ public class StateTransition { } - StateElement stateElement = new StateElement(); + var stateElement = new StateElement(); // dependency,failed is stored as dependency.failed in StateTable String availStatus2 = availStatus; @@ -177,7 +180,7 @@ public class StateTransition { String value = STATE_TABLE.get(key); if (value != null) { - String[] parts = value.split(",", 5); + String[] parts = COMMA_PAT.split(value, 5); stateElement.setEndingAdminState(parts[0].trim()); stateElement.setEndingOpState(parts[1].trim()); stateElement.setEndingAvailStatus(parts[2].trim().replace(".", ",")); diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java index bd7ed7b5..8cbdaa7d 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018, 2020-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. @@ -22,7 +22,6 @@ package org.onap.policy.common.im.jmx; import java.util.ArrayList; import java.util.Iterator; - import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistrationException; @@ -31,7 +30,6 @@ import javax.management.MBeanServerFactory; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; - import org.onap.policy.common.im.IntegrityMonitor; import org.onap.policy.common.im.IntegrityMonitorException; import org.onap.policy.common.im.StateManagement; @@ -54,7 +52,7 @@ public class ComponentAdmin implements ComponentAdminMBean { /** * Constructor. - * + * * @param name the MBean name * @param integrityMonitor the integrity monitor * @param stateManager the state manager @@ -81,7 +79,7 @@ public class ComponentAdmin implements ComponentAdminMBean { /** * Registers with the MBean server. - * + * * @throws ComponentAdminException a JMX exception */ public synchronized void register() throws ComponentAdminException { @@ -89,13 +87,13 @@ public class ComponentAdmin implements ComponentAdminMBean { try { logger.debug("Registering {} MBean", name); - MBeanServer mbeanServer = findMBeanServer(); + var mbeanServer = findMBeanServer(); if (mbeanServer == null) { return; } - ObjectName objectName = new ObjectName(name); + var objectName = new ObjectName(name); if (mbeanServer.isRegistered(objectName)) { logger.debug("Unregistering a previously registered {} MBean", name); @@ -114,7 +112,7 @@ public class ComponentAdmin implements ComponentAdminMBean { /** * Checks if this MBean is registered with the MBeanServer. - * + * * @return true if this MBean is registered with the MBeanServer. */ public boolean isRegistered() { @@ -123,7 +121,7 @@ public class ComponentAdmin implements ComponentAdminMBean { /** * Unregisters with the MBean server. - * + * * @throws ComponentAdminException a JMX exception */ public synchronized void unregister() throws ComponentAdminException { @@ -151,7 +149,7 @@ public class ComponentAdmin implements ComponentAdminMBean { /** * Finds the MBeanServer. - * + * * @return the MBeanServer, or null if it is not found */ public static MBeanServer findMBeanServer() { @@ -172,7 +170,7 @@ public class ComponentAdmin implements ComponentAdminMBean { /** * Creates the MBeanServer (intended for unit testing only). - * + * * @return the MBeanServer */ public static MBeanServer createMBeanServer() { @@ -181,7 +179,7 @@ public class ComponentAdmin implements ComponentAdminMBean { /** * Get the MBean object name for the specified feature name. - * + * * @param componentName component name * @return the object name * @throws MalformedObjectNameException a JMX exception diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java new file mode 100644 index 00000000..5213baef --- /dev/null +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * Integrity Monitor + * ================================================================================ + * Copyright (C) 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.im.jpa; + +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.PrePersist; +import jakarta.persistence.PreUpdate; +import jakarta.persistence.Temporal; +import jakarta.persistence.TemporalType; +import java.io.Serial; +import java.io.Serializable; +import java.util.Date; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.onap.policy.common.im.MonitorTime; + +/* + * Superclass of Entities having create and update timestamps. + */ +@MappedSuperclass +@Getter +@Setter +@NoArgsConstructor +public class DateEntity implements Serializable { + @Serial + private static final long serialVersionUID = 1L; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "created_date", updatable = false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "last_updated") + private Date lastUpdated; + + /** + * PrePersist callback method. + */ + @PrePersist + public void prePersist() { + var date = MonitorTime.getInstance().getDate(); + this.createdDate = date; + this.lastUpdated = date; + } + + @PreUpdate + public void preUpdate() { + this.lastUpdated = MonitorTime.getInstance().getDate(); + } +} diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java index f0ea2c00..7c9698b3 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java @@ -2,14 +2,15 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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,39 +21,35 @@ package org.onap.policy.common.im.jpa; -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 persist a policy object ForwardProgress - */ -import org.onap.policy.common.im.MonitorTime; +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.Table; +import java.io.Serial; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; @Entity @Table(name = "ForwardProgressEntity") -@NamedQueries({@NamedQuery(name = " ForwardProgressEntity.findAll", query = "SELECT e FROM ForwardProgressEntity e "), - @NamedQuery(name = "ForwardProgressEntity.deleteAll", query = "DELETE FROM ForwardProgressEntity WHERE 1=1")}) -// @SequenceGenerator(name="seqForwardProgress", initialValue=1, allocationSize=1) - -public class ForwardProgressEntity implements Serializable { +@NamedQuery(name = " ForwardProgressEntity.findAll", query = "SELECT e FROM ForwardProgressEntity e ") +@NamedQuery(name = "ForwardProgressEntity.deleteAll", query = "DELETE FROM ForwardProgressEntity WHERE 1=1") +@Getter +@Setter +@NoArgsConstructor +public class ForwardProgressEntity extends DateEntity { + @Serial private static final long serialVersionUID = 1L; @Id - // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqForwardProgress") @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "forwardProgressId") + @Setter(AccessLevel.NONE) private long forwardProgressId; @Column(name = "resourceName", nullable = false, length = 100, unique = true) @@ -61,84 +58,13 @@ public class ForwardProgressEntity implements Serializable { @Column(name = "fpc_count", nullable = false) private long fpcCount; - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "created_date", updatable = false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "last_updated") - private Date lastUpdated; - - public ForwardProgressEntity() { - // default constructor - } - /** * PrePersist callback method. */ @PrePersist + @Override public void prePersist() { - Date date = MonitorTime.getInstance().getDate(); - this.createdDate = date; - this.lastUpdated = date; this.fpcCount = 0; - } - - @PreUpdate - public void preUpdate() { - this.lastUpdated = MonitorTime.getInstance().getDate(); - } - - /** - * Get the forward progress Id. - * - * @return the Id - */ - public long getForwardProgressId() { - return forwardProgressId; - } - - public String getResourceName() { - return this.resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - /** - * Get the fpcCount. - * - * @return the fpcCount - */ - public long getFpcCount() { - return fpcCount; - } - - /** - * Set the fpcCount. - * - * @param fpcCount the fpcCount to set - */ - public void setFpcCount(long fpcCount) { - this.fpcCount = fpcCount; - } - - /** - * Get the lastUpdated. - * - * @return the lastUpdated - */ - public Date getLastUpdated() { - return lastUpdated; - } - - /** - * Set the lastUpdated. - * - * @param lastUpdated the lastUpdated to set - */ - public void setLastUpdated(Date lastUpdated) { - this.lastUpdated = lastUpdated; + super.prePersist(); } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java index 1822578b..e70a000b 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java @@ -2,14 +2,15 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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,36 +21,41 @@ package org.onap.policy.common.im.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.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; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.onap.policy.common.im.MonitorTime; @Entity @Table(name = "ImTestEntity") -@NamedQueries({@NamedQuery(name = " ImTestEntity.findAll", query = "SELECT e FROM ImTestEntity e "), - @NamedQuery(name = "ImTestEntity.deleteAll", query = "DELETE FROM ImTestEntity WHERE 1=1")}) -// @SequenceGenerator(name="seqImTest", initialValue=1, allocationSize=1) - +@NamedQuery(name = " ImTestEntity.findAll", query = "SELECT e FROM ImTestEntity e ") +@NamedQuery(name = "ImTestEntity.deleteAll", query = "DELETE FROM ImTestEntity WHERE 1=1") +@Getter +@Setter +@NoArgsConstructor public class ImTestEntity implements Serializable { + @Serial private static final long serialVersionUID = 1L; @Id - // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqImTest") @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ImTestId") + @Setter(AccessLevel.NONE) private long imTestId; @Column(name = "created_by", nullable = false, length = 255) @@ -66,16 +72,12 @@ public class ImTestEntity implements Serializable { @Column(name = "modified_date", nullable = false) private Date modifiedDate; - public ImTestEntity() { - // default constructor - } - /** * PrePersist callback method. */ @PrePersist public void prePersist() { - Date date = MonitorTime.getInstance().getDate(); + var date = MonitorTime.getInstance().getDate(); this.createdDate = date; this.modifiedDate = date; } @@ -84,76 +86,4 @@ public class ImTestEntity implements Serializable { public void preUpdate() { this.modifiedDate = MonitorTime.getInstance().getDate(); } - - /** - * Get the Im test Id. - * - * @return the Id - */ - public long getImTestId() { - return imTestId; - } - - /** - * Get the createdBy. - * - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * Set the createdBy. - * - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * Get the modifiedBy. - * - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * Set the ModifiedBy. - * - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * Get the modifiedDate. - * - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - /** - * Set the modifiedDate. - * - * @param modifiedDate the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - /** - * Get the createdDate. - * - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java index 42e141aa..a771ba09 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java @@ -2,14 +2,15 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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,42 +21,38 @@ package org.onap.policy.common.im.jpa; -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; -import org.onap.policy.common.im.MonitorTime; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.NamedQueries; +import jakarta.persistence.NamedQuery; +import jakarta.persistence.Table; +import java.io.Serial; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; /* * The Entity class to persist a policy object ResourceRegistration */ @Entity @Table(name = "ResourceRegistrationEntity") -@NamedQueries({ - @NamedQuery(name = " ResourceRegistrationEntity.findAll", - query = "SELECT e FROM ResourceRegistrationEntity e "), - @NamedQuery(name = "ResourceRegistrationEntity.deleteAll", - query = "DELETE FROM ResourceRegistrationEntity WHERE 1=1")}) -// @SequenceGenerator(name="seqResourceRegistration", initialValue=1, allocationSize=1) - -public class ResourceRegistrationEntity implements Serializable { +@NamedQuery(name = " ResourceRegistrationEntity.findAll", query = "SELECT e FROM ResourceRegistrationEntity e ") +@NamedQuery(name = "ResourceRegistrationEntity.deleteAll", query = "DELETE FROM ResourceRegistrationEntity WHERE 1=1") +@Getter +@Setter +@NoArgsConstructor +public class ResourceRegistrationEntity extends DateEntity { + @Serial private static final long serialVersionUID = 1L; @Id - // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqResourceRegistration") @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ResourceRegistrationId") + @Setter(AccessLevel.NONE) private long resourceRegistrationId; @Column(name = "resourceName", nullable = false, length = 100, unique = true) @@ -69,99 +66,4 @@ public class ResourceRegistrationEntity implements Serializable { @Column(name = "nodeType", nullable = true, length = 50) private String nodeType; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "created_date", updatable = false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "last_updated") - private Date lastUpdated; - - public ResourceRegistrationEntity() { - // default constructor - } - - /** - * PrePersist callback method. - */ - @PrePersist - public void prePersist() { - Date date = MonitorTime.getInstance().getDate(); - this.createdDate = date; - this.lastUpdated = date; - } - - @PreUpdate - public void preUpdate() { - this.lastUpdated = MonitorTime.getInstance().getDate(); - } - - /** - * Get the resource registration Id. - * - * @return the Id - */ - public long getResourceRegistrationId() { - return resourceRegistrationId; - } - - public String getResourceName() { - return this.resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceUrl() { - return this.resourceUrl; - } - - public void setResourceUrl(String resourceUrl) { - this.resourceUrl = resourceUrl; - } - - public String getSite() { - return this.site; - } - - public void setSite(String site) { - this.site = site; - } - - public String getNodeType() { - return this.nodeType; - } - - public void setNodeType(String nodeType) { - this.nodeType = nodeType; - } - - /** - * Get the createdDate. - * - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * Get the lastUpdated. - * - * @return the lastUpdated - */ - public Date getLastUpdated() { - return lastUpdated; - } - - /** - * Set the lastUpdated. - * - * @param lastUpdated the lastUpdated to set - */ - public void setLastUpdated(Date lastUpdated) { - this.lastUpdated = lastUpdated; - } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java index 494931d2..b03ec71b 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * 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,38 +21,37 @@ package org.onap.policy.common.im.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.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.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; import lombok.AccessLevel; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import org.onap.policy.common.im.MonitorTime; @Entity @Table(name = "StateManagementEntity") @NamedQuery(name = "StateManagementEntity.findAll", query = "SELECT e FROM StateManagementEntity e") -// @SequenceGenerator(name="seqSM", initialValue=1, allocationSize=1) - @Getter @Setter - +@NoArgsConstructor public class StateManagementEntity implements Serializable { + @Serial private static final long serialVersionUID = 1L; @Id - // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqSM") @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") @Getter(AccessLevel.NONE) @@ -82,10 +82,6 @@ public class StateManagementEntity implements Serializable { @Column(name = "modifiedDate", nullable = false) private Date modifiedDate; - public StateManagementEntity() { - // default constructor - } - @PrePersist public void prePersist() { this.createdDate = MonitorTime.getInstance().getDate(); @@ -104,7 +100,7 @@ public class StateManagementEntity implements Serializable { * @return a new StateManagementEntity */ public static StateManagementEntity clone(StateManagementEntity sm) { - StateManagementEntity newStateManagementEntity = new StateManagementEntity(); + var newStateManagementEntity = new StateManagementEntity(); newStateManagementEntity.setResourceName(sm.getResourceName()); newStateManagementEntity.setAdminState(sm.getResourceName()); newStateManagementEntity.setOpState(sm.getOpState()); diff --git a/integrity-monitor/src/main/resources/META-INF/persistence.xml b/integrity-monitor/src/main/resources/META-INF/persistence.xml index 7aff9219..ecba25cc 100644 --- a/integrity-monitor/src/main/resources/META-INF/persistence.xml +++ b/integrity-monitor/src/main/resources/META-INF/persistence.xml @@ -4,6 +4,7 @@ Integrity Monitor ================================================================================ Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. + Modifications Copyright (C) 2023-2024 Nordix Foundation. ================================================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,24 +20,25 @@ ============LICENSE_END========================================================= --> -<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" +<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="schemaPU" transaction-type="RESOURCE_LOCAL"> - <!-- Limited use for generating the DB and schema files for imtest DB - uses eclipselink --> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <!-- Limited use for generating the DB and schema files for imtest DB - uses hibernate --> + <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <class>org.onap.policy.common.im.jpa.ImTestEntity</class> <class>org.onap.policy.common.im.jpa.StateManagementEntity</class> <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class> <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class> <shared-cache-mode>NONE</shared-cache-mode> <properties> - <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" /> + <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create" /> </properties> </persistence-unit> <persistence-unit name="operationalPU" transaction-type="RESOURCE_LOCAL"> <!-- For operational use --> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <class>org.onap.policy.common.im.jpa.ImTestEntity</class> <class>org.onap.policy.common.im.jpa.StateManagementEntity</class> <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class> diff --git a/integrity-monitor/src/main/resources/logback.xml b/integrity-monitor/src/main/resources/logback.xml deleted file mode 100644 index 1d498631..00000000 --- a/integrity-monitor/src/main/resources/logback.xml +++ /dev/null @@ -1,261 +0,0 @@ -<!-- - ============LICENSE_START======================================================= - Integrity Monitor - ================================================================================ - Copyright (C) 2017-2019 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. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= - --> - -<configuration - scan="true" - scanPeriod="3 seconds" - debug="true"> - <!--<jmxConfigurator /> --> - <!-- directory path for all other type logs --> - <property - name="logDir" - value="${POLICY_LOGS}" /> - - <!-- directory path for debugging type logs --> - <property - name="debugDir" - value="${POLICY_LOGS}" /> - - <!-- specify the component name - <ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> - <property - name="componentName" - value="common-modules"></property> - <property - name="subComponentName" - value="integrity-monitor"></property> - - <!-- log file names --> - <property - name="errorLogName" - value="error" /> - <property - name="metricsLogName" - value="metrics" /> - <property - name="auditLogName" - value="audit" /> - <property - name="debugLogName" - value="debug" /> - - <property - name="defaultPatternTimestamp" - value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}" /> - - <property - name="defaultPatternTarget" - value="%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}" /> - - - <property - name="defaultPatternDetails" - value="%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}" /> - - <property - name="defaultPattern" - value="${defaultPatternTimestamp}|${defaultPatternTarget}|%p|${defaultPatternDetails}|%c||%msg%n" /> - - <property - name="logDirectory" - value="${logDir}/${componentName}/${subComponentName}" /> - <property - name="debugLogDirectory" - value="${debugDir}/${componentName}/${subComponentName}" /> - <!-- - <property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" /> - <property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" /> - --> - <!-- example from old log4j.properties: ${catalina.base}/logs/pdp-rest.log --> - <!-- Example evaluator filter applied against console appender --> - <appender - name="STDOUT" - class="ch.qos.logback.core.ConsoleAppender"> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - <!-- ============================================================================ --> - <!-- EELF Appenders --> - <!-- ============================================================================ --> - - <!-- The EELFAppender is used to record events to the general application - log --> - - - - - <!-- EELF Audit Appender. This appender is used to record audit engine - related logging events. The audit logger and appender are specializations - of the EELF application root logger and appender. This can be used to segregate - Policy engine events from other components, or it can be eliminated to record - these events as part of the application root log. --> - - <appender - name="EELFAudit" - class="ch.qos.logback.core.rolling.RollingFileAppender"> - <file>${logDirectory}/${auditLogName}.log</file> - <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> - <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip - </fileNamePattern> - <minIndex>1</minIndex> - <maxIndex>9</maxIndex> - </rollingPolicy> - <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - <appender - name="asyncEELFAudit" - class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>256</queueSize> - <appender-ref ref="EELFAudit" /> - </appender> - - <appender - name="EELFMetrics" - class="ch.qos.logback.core.rolling.RollingFileAppender"> - <file>${logDirectory}/${metricsLogName}.log</file> - <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> - <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip - </fileNamePattern> - <minIndex>1</minIndex> - <maxIndex>9</maxIndex> - </rollingPolicy> - <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy> - <encoder> - <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - - %msg%n"</pattern> --> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - - <appender - name="asyncEELFMetrics" - class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>256</queueSize> - <appender-ref ref="EELFMetrics" /> - </appender> - - <appender - name="EELFError" - class="ch.qos.logback.core.rolling.RollingFileAppender"> - <file>${logDirectory}/${errorLogName}.log</file> - <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> - <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip - </fileNamePattern> - <minIndex>1</minIndex> - <maxIndex>9</maxIndex> - </rollingPolicy> - <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> - <level>ERROR</level> - </filter> - <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - <appender - name="asyncEELFError" - class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>256</queueSize> - <appender-ref ref="EELFError" /> - </appender> - - <appender - name="EELFDebug" - class="ch.qos.logback.core.rolling.RollingFileAppender"> - <file>${debugLogDirectory}/${debugLogName}.log</file> - <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> - <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip - </fileNamePattern> - <minIndex>1</minIndex> - <maxIndex>9</maxIndex> - </rollingPolicy> - <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> - <level>INFO</level> - </filter> - <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - <appender - name="asyncEELFDebug" - class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>256</queueSize> - <appender-ref ref="EELFDebug" /> - <includeCallerData>true</includeCallerData> - </appender> - - - <!-- ============================================================================ --> - <!-- EELF loggers --> - <!-- ============================================================================ --> - - <logger - name="com.att.eelf.audit" - level="info" - additivity="false"> - <appender-ref ref="asyncEELFAudit" /> - </logger> - - <logger - name="com.att.eelf.metrics" - level="info" - additivity="false"> - <appender-ref ref="asyncEELFMetrics" /> - </logger> - - <logger - name="com.att.eelf.error" - level="error" - additivity="false"> - <appender-ref ref="asyncEELFError" /> - </logger> - - <logger - name="com.att.eelf.debug" - level="info" - additivity="false"> - <appender-ref ref="asyncEELFDebug" /> - </logger> - - - <!-- <root level="INFO"> --> - <root level="INFO"> - <appender-ref ref="asyncEELFDebug" /> - <appender-ref ref="asyncEELFError" /> - </root> - -</configuration> |