aboutsummaryrefslogtreecommitdiffstats
path: root/integrity-monitor/src/main/java/org
diff options
context:
space:
mode:
Diffstat (limited to 'integrity-monitor/src/main/java/org')
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java371
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java90
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java712
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java54
4 files changed, 329 insertions, 898 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 68334e83..9a553dc8 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
@@ -29,7 +29,9 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
+import java.util.function.Supplier;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.persistence.EntityManager;
@@ -221,7 +223,7 @@ public class IntegrityMonitor {
validateProperties(properties);
// construct jmx url
- String jmxUrl = getJmxUrl();
+ String jmxUrl = getJmxUrlFromProps();
//
// Create the entity manager factory
@@ -433,7 +435,7 @@ public class IntegrityMonitor {
logger.debug("deleteInstance() exit");
}
- private static String getJmxUrl() throws IntegrityMonitorException {
+ private static String getJmxUrlFromProps() throws IntegrityMonitorException {
// get the jmx remote port and construct the JMX URL
Properties systemProps = System.getProperties();
@@ -520,53 +522,40 @@ public class IntegrityMonitor {
* message is set then the evaluateSanity will return an error.
*
* @param dep the dependency
+ * @return {@code null} if success, an error message otherwise
*/
public String stateCheck(String dep) {
logger.debug("checking state of dependent resource: {}", dep);
- String errorMsg = null;
- ForwardProgressEntity forwardProgressEntity = null;
- StateManagementEntity stateManagementEntity = null;
+ AtomicReference<ForwardProgressEntity> forwardProgressEntity = new AtomicReference<>();
+ AtomicReference<StateManagementEntity> stateManagementEntity = new AtomicReference<>();
- // Start a transaction
- EntityTransaction et = em.getTransaction();
- et.begin();
+ String errorMsg =
+ withinTransaction(dep + ": ForwardProgressEntity DB operation failed with exception: ", () -> {
+ Query query = em.createQuery(
+ "Select p from ForwardProgressEntity p where p.resourceName=:resource");
+ query.setParameter(LC_RESOURCE_STRING, dep);
- try {
- Query query = em.createQuery("Select p from ForwardProgressEntity p where p.resourceName=:resource");
- query.setParameter(LC_RESOURCE_STRING, dep);
+ @SuppressWarnings("rawtypes")
+ List fpList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT)
+ .getResultList();
- @SuppressWarnings("rawtypes")
- List fpList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ if (!fpList.isEmpty()) {
+ // exists
+ forwardProgressEntity.set((ForwardProgressEntity) 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);
+ return null;
- if (!fpList.isEmpty()) {
- // exists
- forwardProgressEntity = (ForwardProgressEntity) fpList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(forwardProgressEntity);
- logger.debug("Found entry in ForwardProgressEntity table for dependent Resource={}", dep);
- } else {
- errorMsg = dep + ": resource not found in ForwardProgressEntity database table";
- logger.error("{}", errorMsg);
- }
- synchronized (imFlushLock) {
- et.commit();
- }
- } catch (Exception ex) {
- // log an error
- errorMsg = dep + ": ForwardProgressEntity DB operation failed with exception: ";
- logger.error("{}", errorMsg, ex);
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
+ } else {
+ return dep + ": resource not found in ForwardProgressEntity database table";
}
- }
- }
+ });
if (errorMsg == null) {
- // Start a transaction
- et = em.getTransaction();
- et.begin();
- try {
+ 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");
query.setParameter(LC_RESOURCE_STRING, dep);
@@ -575,39 +564,26 @@ public class IntegrityMonitor {
List smList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!smList.isEmpty()) {
// exist
- stateManagementEntity = (StateManagementEntity) smList.get(0);
+ stateManagementEntity.set((StateManagementEntity) smList.get(0));
// refresh the object from DB in case cached data was
// returned
- em.refresh(stateManagementEntity);
+ em.refresh(stateManagementEntity.get());
logger.debug("Found entry in StateManagementEntity table for dependent Resource={}", dep);
+ return null;
} else {
- errorMsg = dep + ": resource not found in state management entity database table";
- logger.error("{}", errorMsg);
- }
-
- synchronized (imFlushLock) {
- et.commit();
+ return dep + ": resource not found in state management entity database table";
}
- } catch (Exception e) {
- // log an error
- errorMsg = dep + ": StateManagementEntity DB read failed with exception: ";
- logger.error("{}", errorMsg, e);
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
- }
- }
- }
+ });
}
// verify that the ForwardProgress is current (check last_updated)
if (errorMsg == null) {
- checkForwardProgress(dep, forwardProgressEntity, stateManagementEntity);
+ checkForwardProgress(dep, forwardProgressEntity.get(), stateManagementEntity.get());
}
// check operation, admin and standby states of dependent resource
if (errorMsg == null) {
- errorMsg = checkDependentStates(dep, stateManagementEntity);
+ errorMsg = checkDependentStates(dep, stateManagementEntity.get());
}
String returnMsg = "IntegrityMonitor.stateCheck(): returned error_msg: " + errorMsg;
@@ -615,6 +591,44 @@ public class IntegrityMonitor {
return errorMsg;
}
+ /**
+ * Runs an action within a transaction.
+ *
+ * @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);
+ }
+
+ synchronized (imFlushLock) {
+ et.commit();
+ }
+
+ } catch (RuntimeException ex) {
+ // log an error
+ errorMsg = exMsg;
+ logger.error("{}", errorMsg, ex);
+ synchronized (imFlushLock) {
+ if (et.isActive()) {
+ et.rollback();
+ }
+ }
+ }
+
+ return errorMsg;
+ }
+
private void checkForwardProgress(String dep, ForwardProgressEntity forwardProgressEntity,
StateManagementEntity stateManagementEntity) {
if (forwardProgressEntity != null && stateManagementEntity != null) {
@@ -672,58 +686,39 @@ public class IntegrityMonitor {
private String fpCheck(String dep) {
logger.debug("checking forward progress count of dependent resource: {}", dep);
- String errorMsg = null;
-
- // check FPC count - a changing FPC count indicates the resource JVM is
- // running
-
- // Start a transaction
- EntityTransaction et = em.getTransaction();
- et.begin();
- try {
- Query fquery = em.createQuery(QUERY_STRING);
- fquery.setParameter("rn", dep);
+ return withinTransaction(dep + ": ForwardProgressEntity DB read failed with exception: ", () -> fpCheck2(dep));
+ }
- @SuppressWarnings("rawtypes")
- List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ForwardProgressEntity fpx;
- 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("Dependent resource {} - fpc= {}, lastUpdated={}", dep, fpx.getFpcCount(),
- fpx.getLastUpdated());
- }
- long currTime = MonitorTime.getInstance().getMillis();
- // if dependent resource FPC has not been updated, consider it
- // an error
- if ((currTime - fpx.getLastUpdated().getTime()) > maxFpcUpdateIntervalMs) {
- errorMsg = dep + ": FP count has not been updated in the last " + maxFpcUpdateIntervalMs + "ms";
- logger.error("{}", errorMsg);
- disableEntity(dep);
- }
- } else {
- // resource entry not found in FPC table
- errorMsg = dep + ": resource not found in ForwardProgressEntity table in the DB";
- logger.error("{}", errorMsg);
- }
- synchronized (imFlushLock) {
- et.commit();
+ private String fpCheck2(String dep) {
+ Query fquery = em.createQuery(QUERY_STRING);
+ fquery.setParameter("rn", dep);
+
+ @SuppressWarnings("rawtypes")
+ List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ ForwardProgressEntity fpx;
+ 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("Dependent resource {} - fpc= {}, lastUpdated={}", dep, fpx.getFpcCount(),
+ fpx.getLastUpdated());
}
- } catch (Exception e) {
- // log an error and continue
- errorMsg = dep + ": ForwardProgressEntity DB read failed with exception: ";
- logger.error("{}", errorMsg, e);
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
- }
+ long currTime = MonitorTime.getInstance().getMillis();
+ // if dependent resource FPC has not been updated, consider it
+ // an error
+ if ((currTime - fpx.getLastUpdated().getTime()) > maxFpcUpdateIntervalMs) {
+ disableEntity(dep);
+ return dep + ": FP count has not been updated in the last " + maxFpcUpdateIntervalMs + "ms";
}
- }
- return errorMsg;
+ return null;
+
+ } else {
+ // resource entry not found in FPC table
+ return dep + ": resource not found in ForwardProgressEntity table in the DB";
+ }
}
/**
@@ -731,113 +726,101 @@ public class IntegrityMonitor {
*
* @return list of all forward progress entities
*/
+ @SuppressWarnings("unchecked")
public List<ForwardProgressEntity> getAllForwardProgressEntity() {
logger.debug("getAllForwardProgressEntity: entry");
+
ArrayList<ForwardProgressEntity> fpList = new ArrayList<>();
- // Start a transaction
- EntityTransaction et = em.getTransaction();
- et.begin();
- try {
+
+ withinTransaction("getAllForwardProgessEntity DB read failed with exception: ", () -> {
Query fquery = em.createQuery("Select e from ForwardProgressEntity e");
- @SuppressWarnings("rawtypes")
- List myList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- synchronized (imFlushLock) {
- et.commit();
- }
- logger.debug("getAllForwardProgressEntity: myList.size(): {}", myList.size());
- for (int i = 0; i < myList.size(); i++) {
- if (logger.isDebugEnabled()) {
- logger.debug("getAllForwardProgressEntity: myList.get({}).getResourceName(): {}", i,
- ((ForwardProgressEntity) myList.get(i)).getResourceName());
- }
- fpList.add((ForwardProgressEntity) myList.get(i));
- }
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.commit();
- }
- }
- } catch (Exception e) {
- // log an error and continue
- String msg = "getAllForwardProgessEntity DB read failed with exception: ";
- logger.error("{}", msg, e);
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
- }
- }
+ fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList()
+ .forEach(obj -> fpList.add((ForwardProgressEntity) obj));
+ return null;
+ });
+
+ if (!logger.isDebugEnabled()) {
+ return fpList;
+ }
+
+ logger.debug("getAllForwardProgressEntity: fpList.size(): {}", fpList.size());
+ int index = 0;
+ for (ForwardProgressEntity fpe : fpList) {
+ logger.debug("getAllForwardProgressEntity: fpList.get({}).getResourceName(): {}", index++,
+ fpe.getResourceName());
}
+
return fpList;
}
private String jmxCheck(String dep) {
logger.debug("checking health of dependent by calling test() via JMX on resource: {}", dep);
- String errorMsg = null;
-
// get the JMX URL from the database
- String jmxUrl = null;
- // Start a transaction
- EntityTransaction et = em.getTransaction();
- et.begin();
- try {
- // query if ResourceRegistration entry exists for resourceName
- Query rquery = em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn");
- rquery.setParameter("rn", dep);
+ AtomicReference<String> jmxUrl = new AtomicReference<>();
- @SuppressWarnings("rawtypes")
- List rrList = rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ResourceRegistrationEntity rrx = null;
+ String errorMsg =
+ withinTransaction(dep + ": ResourceRegistrationEntity DB read failed with exception: ",
+ () -> getJmxUrlFromDb(dep, jmxUrl));
- 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);
- jmxUrl = rrx.getResourceUrl();
- if (logger.isDebugEnabled()) {
- logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl, rrx.getCreatedDate());
- }
- } else {
- errorMsg = dep + ": resource not found in ResourceRegistrationEntity table in the DB";
- logger.error("{}", errorMsg);
- }
+ if (jmxUrl.get() != null) {
+ errorMsg = jmxCheck2(dep, jmxUrl.get(), errorMsg);
+ }
- synchronized (imFlushLock) {
- et.commit();
- }
- } catch (Exception e) {
- errorMsg = dep + ": ResourceRegistrationEntity DB read failed with exception: ";
- logger.error("{}", errorMsg, e);
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
- }
+ return errorMsg;
+ }
+
+ 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");
+ rquery.setParameter("rn", dep);
+
+ @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);
+ jmxUrl.set(rrx.getResourceUrl());
+ if (logger.isDebugEnabled()) {
+ logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl.get(),
+ rrx.getCreatedDate());
}
+
+ return null;
+
+ } else {
+ return dep + ": resource not found in ResourceRegistrationEntity table in the DB";
}
+ }
- if (jmxUrl != null) {
- JmxAgentConnection jmxAgentConnection = null;
- try {
- jmxAgentConnection = new JmxAgentConnection(jmxUrl);
- MBeanServerConnection mbeanServer = jmxAgentConnection.getMBeanConnection();
- ComponentAdminMBean admin =
- JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class);
-
- // invoke the test method via the jmx proxy
- admin.test();
- logger.debug("Dependent resource {} sanity test passed", dep);
- } catch (Exception e) {
- errorMsg = dep + ": resource sanity test failed with exception: ";
- logger.error("{}", errorMsg, e);
- } finally {
- // close the JMX connector
- if (jmxAgentConnection != null) {
- jmxAgentConnection.disconnect();
- }
+ private String jmxCheck2(String dep, String jmxUrl, String errorMsg) {
+ JmxAgentConnection jmxAgentConnection = null;
+ try {
+ jmxAgentConnection = new JmxAgentConnection(jmxUrl);
+ MBeanServerConnection mbeanServer = jmxAgentConnection.getMBeanConnection();
+ ComponentAdminMBean admin =
+ JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class);
+
+ // invoke the test method via the jmx proxy
+ admin.test();
+ logger.debug("Dependent resource {} sanity test passed", dep);
+ } catch (Exception e) {
+ String errorMsg2 = dep + ": resource sanity test failed with exception: ";
+ logger.error("{}", errorMsg2, e);
+ return errorMsg2;
+ } finally {
+ // close the JMX connector
+ if (jmxAgentConnection != null) {
+ jmxAgentConnection.disconnect();
}
}
-
return errorMsg;
}
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 030a0371..73724b30 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,14 +2,14 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,9 +20,13 @@
package org.onap.policy.common.im;
+import lombok.Getter;
+import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@Getter
+@Setter
public class StateElement {
private static final Logger logger = LoggerFactory.getLogger(StateElement.class);
@@ -41,86 +45,6 @@ public class StateElement {
// Empty constructor
}
- public String getAdminState() {
- return this.adminState;
- }
-
- public void setAdminState(String adminState) {
- this.adminState = adminState;
- }
-
- public String getOpState() {
- return this.opState;
- }
-
- public void setOpState(String opState) {
- this.opState = opState;
- }
-
- public String getAvailStatus() {
- return this.availStatus;
- }
-
- public void setAvailStatus(String availStatus) {
- this.availStatus = availStatus;
- }
-
- public String getStandbyStatus() {
- return this.standbyStatus;
- }
-
- public void setStandbyStatus(String standbyStatus) {
- this.standbyStatus = standbyStatus;
- }
-
- public String getActionName() {
- return this.actionName;
- }
-
- public void setActionName(String actionName) {
- this.actionName = actionName;
- }
-
- public String getEndingAdminState() {
- return this.endingAdminState;
- }
-
- public void setEndingAdminState(String endingAdminState) {
- this.endingAdminState = endingAdminState;
- }
-
- public String getEndingOpState() {
- return this.endingOpState;
- }
-
- public void setEndingOpState(String endingOpState) {
- this.endingOpState = endingOpState;
- }
-
- public String getEndingAvailStatus() {
- return this.endingAvailStatus;
- }
-
- public void setEndingAvailStatus(String endingAvailStatus) {
- this.endingAvailStatus = endingAvailStatus;
- }
-
- public String getEndingStandbyStatus() {
- return this.endingStandbyStatus;
- }
-
- public void setEndingStandbyStatus(String endingStandbyStatus) {
- this.endingStandbyStatus = endingStandbyStatus;
- }
-
- public String getException() {
- return this.exception;
- }
-
- public void setException(String exception) {
- this.exception = exception;
- }
-
/**
* 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 c5f9d7bc..575f8d01 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
@@ -22,6 +22,8 @@ package org.onap.policy.common.im;
import java.util.List;
import java.util.Observable;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
@@ -103,44 +105,14 @@ public class StateManagement extends Observable {
public StateManagement(final EntityManagerFactory entityManagerFactory, final String resourceName)
throws StateManagementException {
emf = entityManagerFactory;
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: constructor, resourceName: {}", resourceName);
- }
-
- final EntityManager em = emf.createEntityManager();
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- this.resourceName = resourceName;
- if (logger.isDebugEnabled()) {
- logger.debug("resourceName = {}", this.resourceName);
- }
-
-
- try {
- // Create a StateManagementEntity object
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
+ logger.debug("StateManagement: constructor, resourceName: {}", resourceName);
- // persist the administrative state
- if (logger.isDebugEnabled()) {
- logger.debug("Persist adminstrative state, resourceName = {}", this.resourceName);
- }
- em.persist(sm);
- et.commit();
+ this.resourceName = resourceName;
- // Load the StateTransition hash table
- st = new StateTransition();
+ setState("StateManagement", this.resourceName, sm -> null);
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: constructor end, resourceName: {}", this.resourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement: constructor caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement: Exception: " + ex.toString(), ex);
- }
- }
+ // Load the StateTransition hash table
+ st = new StateTransition();
}
/**
@@ -150,84 +122,81 @@ public class StateManagement extends Observable {
* and the owning application will set the StandbyStatus.
*/
public void initializeState() throws StateManagementException {
+ setState("initializeState", this.resourceName, sm -> {
+ sm.setAdminState(sm.getAdminState()); // preserve the Admin state
+ sm.setOpState(StateManagement.ENABLED);
+ sm.setAvailStatus(StateManagement.NULL_VALUE);
+ sm.setStandbyStatus(StateManagement.NULL_VALUE);
+ return ADMIN_STATE;
+ });
+ }
+
+ /**
+ * Sets the management entity state.
+ *
+ * @param methodName name of the method that invoked this
+ * @param resourceName resource name of the desired entity
+ * @param updateState function to update the state; returns a string indicating which item
+ * 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)
+ throws StateManagementException {
+
synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK initializeState() operation for resourceName = {}\n",
- this.resourceName);
- logger.debug("StateManagement: initializeState() operation started, resourceName = {}",
- this.resourceName);
- }
+ logger.debug("\nStateManagement: SYNCLOCK {}() operation for resourceName = {}\n", methodName,
+ resourceName);
+ logger.debug("StateManagement: {}() operation started, resourceName = {}", methodName, resourceName);
+
final EntityManager em = emf.createEntityManager();
try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
- // set state
- sm.setAdminState(sm.getAdminState()); // preserve the Admin state
- sm.setOpState(StateManagement.ENABLED);
- sm.setAvailStatus(StateManagement.NULL_VALUE);
- sm.setStandbyStatus(StateManagement.NULL_VALUE);
+ logger.debug(FIND_MESSAGE, resourceName);
+
+ final StateManagementEntity sm = findStateManagementEntity(em, resourceName);
+ String changed = updateState.update(sm);
em.persist(sm);
et.commit();
- setChanged();
- notifyObservers(ADMIN_STATE);
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: initializeState() operation completed, resourceName = {}",
- this.resourceName);
+ if (changed != null) {
+ setChanged();
+ notifyObservers(changed);
}
+
+ logger.debug("StateManagement: {}() operation completed, resourceName = {}",
+ methodName, resourceName);
} catch (final Exception ex) {
- logger.error("StateManagement.initializeState() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.initializeState() Exception: " + ex);
+ logger.error("StateManagement.{}() caught unexpected exception: ", methodName, ex);
+ throw new StateManagementException("StateManagement." + methodName + "() Exception: " + ex);
}
}
}
+ private void setStateUsingTable(String actionName, String resourceName, String changeName)
+ throws StateManagementException {
+
+ setState(actionName, resourceName, sm -> {
+ final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
+ sm.getAvailStatus(), sm.getStandbyStatus(), actionName);
+
+ sm.setAdminState(stateElement.getEndingAdminState());
+ sm.setOpState(stateElement.getEndingOpState());
+ sm.setAvailStatus(stateElement.getEndingAvailStatus());
+ sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
+
+ return changeName;
+ });
+ }
+
/**
* lock() changes the administrative state to locked.
*
* @throws StateManagementException if an error occurs
*/
public void lock() throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK lock() operation for resourceName = {}\n", this.resourceName);
- logger.debug("StateManagement: lock() operation started, resourceName = {}", this.resourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
-
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), LOCK);
-
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
- setChanged();
- notifyObservers(ADMIN_STATE);
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: lock() operation completed, resourceName = {}", this.resourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.lock() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.lock() Exception: " + ex.toString());
- }
- }
+ setStateUsingTable(LOCK, this.resourceName, ADMIN_STATE);
}
/**
@@ -236,41 +205,7 @@ public class StateManagement extends Observable {
* @throws StateManagementException if an error occurs
*/
public void unlock() throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK unlock() operation for resourceName = {}\n",
- this.resourceName);
- logger.debug("StateManagement: unlock() operation started, resourceName = {}", this.resourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), UNLOCK);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
- setChanged();
- notifyObservers(ADMIN_STATE);
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: unlock() operation completed, resourceName = {}", this.resourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.unlock() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.unlock() Exception: " + ex);
- }
- }
+ setStateUsingTable(UNLOCK, this.resourceName, ADMIN_STATE);
}
/**
@@ -280,44 +215,7 @@ public class StateManagement extends Observable {
* @throws StateManagementException if an error occurs
*/
public void enableNotFailed() throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK enabledNotFailed() operation for resourceName = {}\n",
- this.resourceName);
- logger.debug("StateManagement: enableNotFailed() operation started, resourceName = {}",
- this.resourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), ENABLE_NOT_FAILED);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
-
- setChanged();
- notifyObservers(OPERATION_STATE);
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement enableNotFailed() operation completed, resourceName = {}",
- this.resourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.enableNotFailed() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.enableNotFailed() Exception: " + ex);
- }
- }
+ setStateUsingTable(ENABLE_NOT_FAILED, this.resourceName, OPERATION_STATE);
}
/**
@@ -327,43 +225,7 @@ public class StateManagement extends Observable {
* @throws StateManagementException if an error occurs
*/
public void disableFailed() throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK disabledFailed() operation for resourceName = {}\n",
- this.resourceName);
- logger.debug("StateManagement: disableFailed() operation started, resourceName = {}",
- this.resourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), DISABLE_FAILED);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
- setChanged();
- notifyObservers(OPERATION_STATE);
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: disableFailed() operation completed, resourceName = {}",
- this.resourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.disableFailed() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.disableFailed() Exception: " + ex);
- }
- }
+ setStateUsingTable(DISABLE_FAILED, this.resourceName, OPERATION_STATE);
}
/**
@@ -373,49 +235,13 @@ public class StateManagement extends Observable {
* @throws StateManagementException if an error occurs
*/
public void disableFailed(final String otherResourceName) throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (otherResourceName == null) {
- logger.error("\nStateManagement: SYNCLOCK disableFailed(otherResourceName) operation: resourceName is "
- + "NULL.\n");
- return;
- }
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK disabledFailed(otherResourceName) operation for resourceName "
- + "= {}\n", otherResourceName);
- logger.debug("StateManagement: disableFailed(otherResourceName) operation started, resourceName = {}",
- otherResourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, otherResourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, otherResourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), DISABLE_FAILED);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
- setChanged();
- notifyObservers(OPERATION_STATE);
-
- if (logger.isDebugEnabled()) {
- logger.debug(
- "StateManagement: disableFailed(otherResourceName) operation completed, resourceName = {}",
- otherResourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.disableFailed(otherResourceName) caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.disableFailed(otherResourceName) Exception: " + ex);
- }
+ if (otherResourceName == null) {
+ logger.error(
+ "\nStateManagement: SYNCLOCK disableFailed(otherResourceName) operation: resourceName is NULL.\n");
+ return;
}
+
+ setStateUsingTable(DISABLE_FAILED, otherResourceName, OPERATION_STATE);
}
/**
@@ -425,43 +251,7 @@ public class StateManagement extends Observable {
* @throws StateManagementException if an error occurs
*/
public void disableDependency() throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK disableDependency() operation for resourceName = {}\n",
- this.resourceName);
- logger.debug("StateManagement: disableDependency() operation started, resourceName = {}",
- this.resourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), DISABLE_DEPENDENCY);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
- setChanged();
- notifyObservers(OPERATION_STATE);
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: disableDependency() operation completed, resourceName = {}",
- this.resourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.disableDependency() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.disableDependency() Exception: " + ex);
- }
- }
+ setStateUsingTable(DISABLE_DEPENDENCY, this.resourceName, OPERATION_STATE);
}
/**
@@ -471,43 +261,7 @@ public class StateManagement extends Observable {
* @throws StateManagementException if an error occurs
*/
public void enableNoDependency() throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK enableNoDependency() operation for resourceName = {}\n",
- this.resourceName);
- logger.debug("StateManagement: enableNoDependency() operation started, resourceName = {}",
- this.resourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), ENABLE_NO_DEPENDENCY);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
- setChanged();
- notifyObservers(OPERATION_STATE);
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: enableNoDependency() operation completed, resourceName = {}",
- this.resourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.enableNoDependency() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.enableNoDependency() Exception: " + ex);
- }
- }
+ setStateUsingTable(ENABLE_NO_DEPENDENCY, this.resourceName, OPERATION_STATE);
}
/**
@@ -516,48 +270,26 @@ public class StateManagement extends Observable {
* @throws IntegrityMonitorException if the status fails to change
*/
public void promote() throws IntegrityMonitorException {
- synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK promote() operation for resourceName = {}\n",
- this.resourceName);
- logger.debug("StateManagement: promote() operation started, resourceName = {}", this.resourceName);
- }
+ AtomicReference<String> newStatus = new AtomicReference<>();
- StateManagementEntity sm;
+ setState(PROMOTE, resourceName, sm -> {
+ final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
+ sm.getAvailStatus(), sm.getStandbyStatus(), PROMOTE);
- final EntityManager em = emf.createEntityManager();
+ sm.setAdminState(stateElement.getEndingAdminState());
+ sm.setOpState(stateElement.getEndingOpState());
+ sm.setAvailStatus(stateElement.getEndingAvailStatus());
+ sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- sm = findStateManagementEntity(em, this.resourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), PROMOTE);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
+ newStatus.set(sm.getStandbyStatus());
- em.persist(sm);
- et.commit();
- setChanged();
- notifyObservers(STANDBY_STATUS);
- } catch (final Exception ex) {
- logger.error("StateManagement.promote() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.promote() Exception: " + ex);
- }
+ return STANDBY_STATUS;
+ });
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: promote() operation completed, resourceName = {}", this.resourceName);
- }
- if (sm.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
- final String msg =
- "Failure to promote " + this.resourceName + " StandbyStatus = " + StateManagement.COLD_STANDBY;
- throw new StandbyStatusException(msg);
- }
+ if (StateManagement.COLD_STANDBY.equals(newStatus.get())) {
+ final String msg =
+ "Failure to promote " + this.resourceName + " StandbyStatus = " + StateManagement.COLD_STANDBY;
+ throw new StandbyStatusException(msg);
}
}
@@ -567,42 +299,7 @@ public class StateManagement extends Observable {
* @throws StateManagementException if an error occurs
*/
public void demote() throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK demote() operation for resourceName = {}\n",
- this.resourceName);
- logger.debug("StateManagement: demote() operation started, resourceName = {}",
- this.resourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug(FIND_MESSAGE, this.resourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, this.resourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), DEMOTE);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
- setChanged();
- notifyObservers(STANDBY_STATUS);
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: demote() operation completed, resourceName = {}", this.resourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.demote() caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.demote() Exception: " + ex);
- }
- }
+ setStateUsingTable(DEMOTE, this.resourceName, STANDBY_STATUS);
}
/**
@@ -615,46 +312,13 @@ public class StateManagement extends Observable {
* @throws StateManagementException if an error occurs
*/
public void demote(final String otherResourceName) throws StateManagementException {
- synchronized (SYNCLOCK) {
- if (otherResourceName == null) {
- logger.error(
- "\nStateManagement: SYNCLOCK demote(otherResourceName) operation: resourceName is NULL.\n");
- return;
- }
- if (logger.isDebugEnabled()) {
- logger.debug("\nStateManagement: SYNCLOCK demote(otherResourceName) operation for resourceName = {}\n",
- otherResourceName);
- }
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: SYNCLOCK demote(otherResourceName) findStateManagementEntity for {}",
- otherResourceName);
- }
- final StateManagementEntity sm = findStateManagementEntity(em, otherResourceName);
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), DEMOTE);
- // set transition state
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- em.persist(sm);
- et.commit();
- // We don't notify observers because this is assumed to be a remote resource
-
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: demote(otherResourceName) operation completed, resourceName = {}",
- otherResourceName);
- }
- } catch (final Exception ex) {
- logger.error("StateManagement.demote(otherResourceName) caught unexpected exception: ", ex);
- throw new StateManagementException("StateManagement.demote(otherResourceName) Exception: " + ex);
- }
+ if (otherResourceName == null) {
+ logger.error(
+ "\nStateManagement: SYNCLOCK demote(otherResourceName) operation: resourceName is NULL.\n");
+ return;
}
+
+ setStateUsingTable(DEMOTE, otherResourceName, null);
}
/**
@@ -663,9 +327,16 @@ public class StateManagement extends Observable {
* @return the administration state
*/
public String getAdminState() {
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement(6/1/16): getAdminState for resourceName {}", this.resourceName);
- }
+ getEntityState("getAdminState", this.resourceName,
+ sm -> this.adminState = sm.getAdminState(),
+ () -> this.adminState = null);
+ return this.adminState;
+ }
+
+ private void getEntityState(String methodName, String resourceName, Consumer<StateManagementEntity> function,
+ Runnable notFound) {
+
+ logger.debug("StateManagement(6/1/16): {} for resourceName {}", methodName, resourceName);
final EntityManager em = emf.createEntityManager();
try (final EntityMgrCloser emc = new EntityMgrCloser(em)) {
@@ -682,15 +353,14 @@ public class StateManagement extends Observable {
final StateManagementEntity stateManagementEntity = resourceList.get(0);
// refresh the object from DB in case cached data was returned
em.refresh(stateManagementEntity);
- this.adminState = stateManagementEntity.getAdminState();
+ function.accept(stateManagementEntity);
} else {
- this.adminState = null;
+ notFound.run();
}
} catch (final Exception ex) {
- logger.error("StateManagement: getAdminState exception: {}", ex.toString(), ex);
+ logger.error("StateManagement: {} exception: {}", methodName, ex.toString(), ex);
}
- return this.adminState;
}
/**
@@ -699,33 +369,9 @@ public class StateManagement extends Observable {
* @return the operational state
*/
public String getOpState() {
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement(6/1/16): getOpState for resourceName {}", this.resourceName);
- }
-
- final EntityManager em = emf.createEntityManager();
- try (EntityMgrCloser emc = new EntityMgrCloser(em)) {
- final TypedQuery<StateManagementEntity> query =
- em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
-
- query.setParameter(RESOURCE_NAME, this.resourceName);
-
- // Just test that we are retrieving the right object
- final List<StateManagementEntity> resourceList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!resourceList.isEmpty()) {
- // exist
- final StateManagementEntity stateManagementEntity = resourceList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(stateManagementEntity);
- this.opState = stateManagementEntity.getOpState();
- } else {
- this.opState = null;
- }
- } catch (final Exception ex) {
- logger.error("StateManagement: getOpState exception: {}", ex.toString(), ex);
- }
-
+ getEntityState("getOpState", this.resourceName,
+ sm -> this.opState = sm.getOpState(),
+ () -> this.opState = null);
return this.opState;
}
@@ -735,33 +381,9 @@ public class StateManagement extends Observable {
* @return the availability status
*/
public String getAvailStatus() {
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement(6/1/16): getAvailStatus for resourceName {}", this.resourceName);
- }
-
- final EntityManager em = emf.createEntityManager();
- try (EntityMgrCloser emc = new EntityMgrCloser(em)) {
- final TypedQuery<StateManagementEntity> query =
- em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
-
- query.setParameter(RESOURCE_NAME, this.resourceName);
-
- // Just test that we are retrieving the right object
- final List<StateManagementEntity> resourceList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!resourceList.isEmpty()) {
- // exist
- final StateManagementEntity stateManagementEntity = resourceList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(stateManagementEntity);
- this.availStatus = stateManagementEntity.getAvailStatus();
- } else {
- this.availStatus = null;
- }
- } catch (final Exception ex) {
- logger.error("StateManagement: getAvailStatus exception: {}", ex.toString(), ex);
- }
-
+ getEntityState("getAvailStatus", this.resourceName,
+ sm -> this.availStatus = sm.getAvailStatus(),
+ () -> this.availStatus = null);
return this.availStatus;
}
@@ -771,33 +393,9 @@ public class StateManagement extends Observable {
* @return the standby status
*/
public String getStandbyStatus() {
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement(6/1/16): getStandbyStatus for resourceName {}", this.resourceName);
- }
-
- final EntityManager em = emf.createEntityManager();
- try (EntityMgrCloser emc = new EntityMgrCloser(em)) {
- final TypedQuery<StateManagementEntity> query =
- em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
-
- query.setParameter(RESOURCE_NAME, this.resourceName);
-
- // Just test that we are retrieving the right object
- final List<StateManagementEntity> resourceList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!resourceList.isEmpty()) {
- // exist
- final StateManagementEntity stateManagementEntity = resourceList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(stateManagementEntity);
- this.standbyStatus = stateManagementEntity.getStandbyStatus();
- } else {
- this.standbyStatus = null;
- }
- } catch (final Exception ex) {
- logger.error("StateManagement: getStandbyStatus exception: {}", ex.toString(), ex);
- }
-
+ getEntityState("getStandbyStatus", this.resourceName,
+ sm -> this.standbyStatus = sm.getStandbyStatus(),
+ () -> this.standbyStatus = null);
return this.standbyStatus;
}
@@ -808,48 +406,16 @@ public class StateManagement extends Observable {
* @return the standby status
*/
public String getStandbyStatus(final String otherResourceName) {
+ AtomicReference<String> tempStandbyStatus = new AtomicReference<>();
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: getStandbyStatus: Entering, resourceName='{}'", otherResourceName);
- }
+ getEntityState("getStandbyStatus", otherResourceName,
+ sm -> tempStandbyStatus.set(sm.getStandbyStatus()),
+ () -> logger.error("getStandbyStatus: resourceName ={} not found in statemanagemententity table",
+ otherResourceName));
- String tempStandbyStatus = null;
+ logger.debug("getStandbyStatus: Returning standbyStatus={}", tempStandbyStatus.get());
- // The transaction is required for the LockModeType
- final EntityManager em = emf.createEntityManager();
-
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- final TypedQuery<StateManagementEntity> stateManagementListQuery =
- em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
- stateManagementListQuery.setParameter(RESOURCE_NAME, otherResourceName);
- final List<StateManagementEntity> stateManagementList = stateManagementListQuery
- .setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!stateManagementList.isEmpty()) {
- final StateManagementEntity stateManagementEntity = stateManagementList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(stateManagementEntity);
- tempStandbyStatus = stateManagementEntity.getStandbyStatus();
- if (logger.isDebugEnabled()) {
- logger.debug("getStandbyStatus: resourceName ={} has standbyStatus={}", otherResourceName,
- tempStandbyStatus);
- }
- } else {
- logger.error("getStandbyStatus: resourceName ={} not found in statemanagemententity table",
- otherResourceName);
- }
-
- et.commit();
- } catch (final Exception e) {
- logger.error(
- "getStandbyStatus: Caught Exception attempting to get statemanagemententity record, message='{}'",
- e.getMessage(), e);
- }
- if (logger.isDebugEnabled()) {
- logger.debug("getStandbyStatus: Returning standbyStatus={}", tempStandbyStatus);
- }
-
- return tempStandbyStatus;
+ return tempStandbyStatus.get();
}
/**
@@ -861,9 +427,7 @@ public class StateManagement extends Observable {
*/
private static StateManagementEntity findStateManagementEntity(final EntityManager em,
final String otherResourceName) {
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagementEntity: findStateManagementEntity: Entry");
- }
+ logger.debug("StateManagementEntity: findStateManagementEntity: Entry");
try {
final TypedQuery<StateManagementEntity> query =
em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
@@ -902,9 +466,7 @@ public class StateManagement extends Observable {
*/
public void deleteAllStateManagementEntities() {
- if (logger.isDebugEnabled()) {
- logger.debug("StateManagement: deleteAllStateManagementEntities: Entering");
- }
+ logger.debug("StateManagement: deleteAllStateManagementEntities: Entering");
/*
* Start transaction
@@ -916,17 +478,12 @@ public class StateManagement extends Observable {
em.createQuery("SELECT p FROM StateManagementEntity p", StateManagementEntity.class);
final List<StateManagementEntity> stateManagementEntityList = stateManagementEntityListQuery
.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (logger.isDebugEnabled()) {
- logger.debug("deleteAllStateManagementEntities: Deleting {} StateManagementEntity records",
- stateManagementEntityList.size());
- }
+ logger.debug("deleteAllStateManagementEntities: Deleting {} StateManagementEntity records",
+ stateManagementEntityList.size());
for (final StateManagementEntity stateManagementEntity : stateManagementEntityList) {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "deleteAllStateManagementEntities: Deleting statemanagemententity with resourceName={} and"
- + " standbyStatus={}",
- stateManagementEntity.getResourceName(), stateManagementEntity.getStandbyStatus());
- }
+ logger.debug("deleteAllStateManagementEntities: Deleting statemanagemententity with resourceName={} and"
+ + " standbyStatus={}", stateManagementEntity.getResourceName(),
+ stateManagementEntity.getStandbyStatus());
em.remove(stateManagementEntity);
}
@@ -934,9 +491,12 @@ public class StateManagement extends Observable {
} catch (final Exception ex) {
logger.error("StateManagement.deleteAllStateManagementEntities() caught Exception: ", ex);
}
- if (logger.isDebugEnabled()) {
- logger.debug("deleteAllStateManagementEntities: Exiting");
- }
+ logger.debug("deleteAllStateManagementEntities: Exiting");
+ }
+
+ @FunctionalInterface
+ private static interface ExFunction<T,R> {
+ public R update(T object) throws IntegrityMonitorException;
}
private static class MyTransaction extends EntityTransCloser {
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 79f843e4..494931d2 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
@@ -34,6 +34,9 @@ import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.Setter;
import org.onap.policy.common.im.MonitorTime;
@Entity
@@ -41,6 +44,9 @@ import org.onap.policy.common.im.MonitorTime;
@NamedQuery(name = "StateManagementEntity.findAll", query = "SELECT e FROM StateManagementEntity e")
// @SequenceGenerator(name="seqSM", initialValue=1, allocationSize=1)
+@Getter
+@Setter
+
public class StateManagementEntity implements Serializable {
private static final long serialVersionUID = 1L;
@@ -48,6 +54,8 @@ public class StateManagementEntity implements Serializable {
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqSM")
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
+ @Getter(AccessLevel.NONE)
+ @Setter(AccessLevel.NONE)
private long id;
@Column(name = "resourceName", nullable = false, length = 100, unique = true)
@@ -67,6 +75,7 @@ public class StateManagementEntity implements Serializable {
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_Date", updatable = false)
+ @Setter(AccessLevel.NONE)
private Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
@@ -88,51 +97,6 @@ public class StateManagementEntity implements Serializable {
this.modifiedDate = MonitorTime.getInstance().getDate();
}
- public String getResourceName() {
- return this.resourceName;
- }
-
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
-
- public String getAdminState() {
- return this.adminState;
- }
-
- public void setAdminState(String adminState) {
- this.adminState = adminState;
- }
-
- public String getOpState() {
- return this.opState;
- }
-
- public void setOpState(String opState) {
- this.opState = opState;
-
- }
-
- public String getAvailStatus() {
- return this.availStatus;
- }
-
- public void setAvailStatus(String availStatus) {
- this.availStatus = availStatus;
- }
-
- public String getStandbyStatus() {
- return this.standbyStatus;
- }
-
- public void setStandbyStatus(String standbyStatus) {
- this.standbyStatus = standbyStatus;
- }
-
- public void setModifiedDate(Date modifiedDate) {
- this.modifiedDate = modifiedDate;
- }
-
/**
* Clone a StateManagementEntity.
*