diff options
Diffstat (limited to 'integrity-monitor/src/main/java/org/onap/policy')
13 files changed, 383 insertions, 591 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 62103925..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-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,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; @@ -36,16 +45,9 @@ 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 javax.persistence.TypedQuery; +import lombok.Getter; +import lombok.Setter; import org.apache.commons.lang3.StringUtils; -import org.eclipse.persistence.config.PersistenceUnitProperties; import org.onap.policy.common.im.jmx.ComponentAdmin; import org.onap.policy.common.im.jmx.ComponentAdminMBean; import org.onap.policy.common.im.jmx.JmxAgentConnection; @@ -63,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; @@ -74,7 +79,7 @@ public class IntegrityMonitor { 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 = "; + "IntegrityMonitor.stateCheck(): " + "Failed to disableFail dependent resource = "; private static final String RESOURCE_STRING = "Resource "; private static final String LC_RESOURCE_STRING = "resource"; @@ -93,14 +98,15 @@ public class IntegrityMonitor { 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; /** @@ -152,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 @@ -195,24 +203,26 @@ 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); } @@ -231,17 +241,7 @@ public class IntegrityMonitor { // // Create the entity manager factory // - if (!properties.containsKey(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML)) { - properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceIM.xml"); - } 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 @@ -292,8 +292,8 @@ public class IntegrityMonitor { fquery.setParameter("rn", resourceName); List<ForwardProgressEntity> fpList = - fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); - ForwardProgressEntity fpx = null; + fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + ForwardProgressEntity fpx; if (!fpList.isEmpty()) { // ignores multiple results fpx = fpList.get(0); @@ -301,7 +301,7 @@ public class IntegrityMonitor { em.refresh(fpx); if (logger.isDebugEnabled()) { logger.debug("Resource {} exists and will be updated - old fpc= {}, lastUpdated= {}", resourceName, - fpx.getFpcCount(), fpx.getLastUpdated()); + fpx.getFpcCount(), fpx.getLastUpdated()); } fpx.setFpcCount(fpCounter); } else { @@ -320,13 +320,13 @@ public class IntegrityMonitor { 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); + 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 = null; + rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + ResourceRegistrationEntity rrx; if (!rrList.isEmpty()) { // ignores multiple results rrx = rrList.get(0); @@ -334,7 +334,7 @@ public class IntegrityMonitor { em.refresh(rrx); if (logger.isDebugEnabled()) { logger.debug("Resource {} exists and will be updated - old url= {}, createdDate={}", resourceName, - rrx.getResourceUrl(), rrx.getCreatedDate()); + rrx.getResourceUrl(), rrx.getCreatedDate()); } rrx.setLastUpdated(MonitorTime.getInstance().getDate()); } else { @@ -376,7 +376,7 @@ public class IntegrityMonitor { try { new ComponentAdmin(resourceName, this, stateManager); } catch (Exception e) { - logger.error("ComponentAdmin constructor exception: {}", e.toString(), e); + logger.error("ComponentAdmin constructor exception: {}", e, e); } } @@ -390,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); @@ -423,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; @@ -454,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; @@ -466,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) { @@ -475,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) { @@ -490,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); } @@ -534,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); @@ -560,12 +560,12 @@ public class IntegrityMonitor { String errorMsg = withinTransaction(dep + ": ForwardProgressEntity DB operation failed with exception: ", () -> { TypedQuery<ForwardProgressEntity> query = em.createQuery( - "Select p from ForwardProgressEntity p where p.resourceName=:resource", - ForwardProgressEntity.class); + "Select p from ForwardProgressEntity p where p.resourceName=:resource", + ForwardProgressEntity.class); query.setParameter(LC_RESOURCE_STRING, dep); List<ForwardProgressEntity> fpList = query.setLockMode(LockModeType.NONE) - .setFlushMode(FlushModeType.COMMIT).getResultList(); + .setFlushMode(FlushModeType.COMMIT).getResultList(); if (!fpList.isEmpty()) { // exists @@ -574,7 +574,7 @@ public class IntegrityMonitor { // returned em.refresh(forwardProgressEntity.get()); logger.debug("Found entry in ForwardProgressEntity table for dependent Resource={}", - dep); + dep); return null; } else { @@ -582,17 +582,17 @@ 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 TypedQuery<StateManagementEntity> query = - em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource", - StateManagementEntity.class); + em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource", + StateManagementEntity.class); query.setParameter(LC_RESOURCE_STRING, dep); List<StateManagementEntity> smList = - query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); if (!smList.isEmpty()) { // exist stateManagementEntity.set(smList.get(0)); @@ -608,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()); } @@ -625,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); @@ -677,13 +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); } } @@ -692,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); } @@ -723,7 +716,7 @@ public class IntegrityMonitor { fquery.setParameter("rn", dep); List<ForwardProgressEntity> fpList = - fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); ForwardProgressEntity fpx; if (!fpList.isEmpty()) { // ignores multiple results @@ -732,7 +725,7 @@ public class IntegrityMonitor { 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 @@ -762,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; }); @@ -773,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; @@ -801,13 +794,13 @@ public class IntegrityMonitor { private String getJmxUrlFromDb(String dep, AtomicReference<String> jmxUrl) { // query if ResourceRegistration entry exists for resourceName TypedQuery<ResourceRegistrationEntity> rquery = - em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn", - ResourceRegistrationEntity.class); + em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn", + ResourceRegistrationEntity.class); rquery.setParameter("rn", dep); List<ResourceRegistrationEntity> rrList = - rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); - ResourceRegistrationEntity rrx = null; + rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + ResourceRegistrationEntity rrx; if (!rrList.isEmpty()) { // ignores multiple results @@ -833,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(); @@ -861,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. @@ -920,7 +913,7 @@ public class IntegrityMonitor { try { if (logger.isDebugEnabled()) { logger.debug("{}: There has been a subsystemTest failure with error:{} Updating this resource's " - + "state to disableDependency", resourceName, e.getMessage()); + + "state to disableDependency", resourceName, e.getMessage()); } // Capture the subsystemTest failure info appendSeparator(errorMsg); @@ -948,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) { @@ -968,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 */ @@ -978,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()) { @@ -1029,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); + + "resource's state to disableDependency", group); 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.disableDependency(); @@ -1058,10 +1051,10 @@ 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"); + + " 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(); @@ -1080,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(); } @@ -1096,7 +1089,7 @@ public class IntegrityMonitor { } private void appendSeparator(StringBuilder errorMsg) { - if (errorMsg.length() != 0) { + if (!errorMsg.isEmpty()) { errorMsg.append(','); } } @@ -1122,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"); } @@ -1146,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); @@ -1167,25 +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 + * 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()); - } - logger.debug("endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY. " - + "Advancing forward progress counter. \n{}\n", msg); + var msg = new StringBuilder("allSeemsWellMap:"); + buildMapString(msg, allSeemsWellMap); + logger.debug( + """ + endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY. + Advancing forward progress counter. + {} + """, msg); } } // increment local FPC @@ -1193,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 { @@ -1209,7 +1213,7 @@ public class IntegrityMonitor { fquery.setParameter("rn", resourceName); List<ForwardProgressEntity> fpList = - fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); ForwardProgressEntity fpx; if (!fpList.isEmpty()) { // ignores multiple results @@ -1218,7 +1222,7 @@ public class IntegrityMonitor { 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); @@ -1246,11 +1250,6 @@ public class IntegrityMonitor { } } - // retrieve state manager reference - public final StateManagement getStateManager() { - return this.stateManager; - } - /** * Read and validate properties. * @@ -1265,7 +1264,7 @@ public class IntegrityMonitor { 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)); @@ -1274,13 +1273,13 @@ public class IntegrityMonitor { 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)); } @@ -1309,7 +1308,7 @@ public class IntegrityMonitor { value -> refreshStateAuditIntervalMs = value); logger.debug("IntegrityMonitor.validateProperties(): Property values \nmaxFpcUpdateIntervalMs = {}\n", - maxFpcUpdateIntervalMs); + maxFpcUpdateIntervalMs); } private static void setBoolean(Properties props, String propName, Consumer<Boolean> setter) { @@ -1331,8 +1330,8 @@ public class IntegrityMonitor { return propValue.trim(); } - private static void setInt(Properties props, String propName, IntConsumer 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; } @@ -1340,7 +1339,7 @@ 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); } } @@ -1425,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 @@ -1472,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"); @@ -1497,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; } @@ -1513,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); @@ -1544,7 +1543,7 @@ public class IntegrityMonitor { * 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) { @@ -1553,12 +1552,12 @@ public class IntegrityMonitor { try { // query if StateManagement entry exists for fpe resource TypedQuery<StateManagementEntity> query = - em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource", - StateManagementEntity.class); + em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource", + StateManagementEntity.class); query.setParameter(LC_RESOURCE_STRING, fpe.getResourceName()); List<StateManagementEntity> smList = - query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); if (!smList.isEmpty()) { // exists sme = smList.get(0); @@ -1567,11 +1566,11 @@ public class IntegrityMonitor { em.refresh(sme); if (logger.isDebugEnabled()) { logger.debug("IntegrityMonitor.executeStateAudit(): Found entry in StateManagementEntity table " - + "for Resource={}", sme.getResourceName()); + + "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) { @@ -1580,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(); @@ -1605,11 +1604,11 @@ public class IntegrityMonitor { 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) { @@ -1626,7 +1625,7 @@ public class IntegrityMonitor { 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()); @@ -1706,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 @@ -1718,7 +1717,7 @@ 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 + * 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 @@ -1742,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); @@ -1828,9 +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)) { @@ -1877,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 @@ -1886,18 +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 */ @@ -1922,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 feca72f9..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; @@ -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); @@ -197,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()); @@ -292,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()); @@ -357,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); @@ -369,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); @@ -377,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); } } @@ -458,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); @@ -474,8 +475,7 @@ public class StateManagement { return stateManagementEntity; } } catch (final Exception ex) { - final String message = "findStateManagementEntity exception"; - throw new EntityRetrievalException(message, ex); + throw new EntityRetrievalException("findStateManagementEntity exception", ex); } } @@ -489,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 @@ -531,7 +531,7 @@ public class StateManagement { @Override public void commit() { synchronized (FLUSHLOCK) { - if (getTransation().isActive()) { + if (getTransaction().isActive()) { super.commit(); } } @@ -540,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 cf7a968f..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,7 +2,7 @@ * ============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. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,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); 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 aa3524f0..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,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,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 1eaf3a6f..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,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,35 +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) @@ -65,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; } @@ -83,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 d73100f7..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,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,40 +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) @@ -67,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 30677814..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-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,37 +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) @@ -81,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(); @@ -103,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()); |