diff options
21 files changed, 529 insertions, 480 deletions
diff --git a/feature-active-standby-management/pom.xml b/feature-active-standby-management/pom.xml index f8378f1a..2e776baf 100644 --- a/feature-active-standby-management/pom.xml +++ b/feature-active-standby-management/pom.xml @@ -158,6 +158,12 @@ <scope>test</scope> </dependency> <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>utils-test</artifactId> + <version>${policy.common.version}</version> + <scope>test</scope> + </dependency> + <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java index d7c153db..91d30d74 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java @@ -21,14 +21,12 @@ package org.onap.policy.drools.activestandby; import java.io.IOException; -import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; - import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; - +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.features.PolicyEngineFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; @@ -163,7 +161,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, synchronized (myPdpSync) { if (myPdp == null) { - myPdp = new DroolsPdpImpl(resourceName,false,4,new Date()); + myPdp = new DroolsPdpImpl(resourceName,false,4,MonitorTime.getInstance().getDate()); } String siteName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.SITE_NAME); if (siteName == null) { diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java index 38ab6e4b..4175068f 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java @@ -32,6 +32,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.Getter; import lombok.Setter; +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.drools.activestandby.DroolsPdpObject; @Entity @@ -72,7 +73,7 @@ public class DroolsPdpEntity extends DroolsPdpObject implements Serializable { * Constructor. */ public DroolsPdpEntity() { - updatedDate = new Date(); + updatedDate = MonitorTime.getInstance().getDate(); //When this is translated to a TimeStamp in MySQL, it assumes the date is relative //to the local timezone. So, a value of Date(0) is actually Dec 31 18:00:00 CST 1969 //which is an invalid value for the MySql TimeStamp diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java index 85cf88b3..5308cbe6 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java @@ -26,8 +26,9 @@ import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; - +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.utils.time.CurrentTime; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; import org.slf4j.Logger; @@ -73,6 +74,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { private StateManagementFeatureApi stateManagementFeature; + private final CurrentTime currentTime = MonitorTime.getInstance(); + private static boolean isUnitTesting = false; private static boolean isStalled = false; @@ -112,14 +115,14 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { logger.error("Could not get pdpUpdateInterval property. Using default {} ", pdpUpdateInterval, e); } - Date now = new Date(); + Date now = currentTime.getDate(); // Retrieve the ms since the epoch final long nowMs = now.getTime(); // Create the timer which will update the updateDate in DroolsPdpEntity table. // This is the heartbeat - updateWorker = new Timer(); + updateWorker = Factory.getInstance().makeTimer(); // Schedule the TimerUpdateClass to run at 100 ms and run at pdpCheckInterval ms thereafter // NOTE: The first run of the TimerUpdateClass results in myPdp being added to the @@ -127,7 +130,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { updateWorker.scheduleAtFixedRate(new TimerUpdateClass(), 100, pdpCheckInterval); // Create the timer which will run the election algorithm - waitTimer = new Timer(); + waitTimer = Factory.getInstance().makeTimer(); // Schedule it to start in startMs ms // (so it will run after the updateWorker and run at pdpUpdateInterval ms thereafter @@ -264,7 +267,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { logger.debug("DesignatedWaiter.run: myPdp: {}; Returning, isDesignated= {}", isDesignated, myPdp.getPdpId()); - Date tmpDate = new Date(); + Date tmpDate = currentTime.getDate(); logger.debug("DesignatedWaiter.run (end of run) waitTimerLastRunDate = {}", tmpDate); waitTimerLastRunDate = tmpDate; @@ -559,7 +562,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { pdpsConnector.setDesignated(myPdp,false); isDesignated = false; - waitTimerLastRunDate = new Date(); + waitTimerLastRunDate = currentTime.getDate(); logger.debug("DesignatedWaiter.run (designatedPdp == null) waitTimerLastRunDate = {}", waitTimerLastRunDate); myPdp.setUpdatedDate(waitTimerLastRunDate); @@ -573,7 +576,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { try { //Keep the order like this. StateManagement is last since it triggers controller init myPdp.setDesignated(true); - myPdp.setDesignatedDate(new Date()); + myPdp.setDesignatedDate(currentTime.getDate()); pdpsConnector.setDesignated(myPdp, true); isDesignated = true; String standbyStatus = stateManagementFeature.getStandbyStatus(); @@ -613,7 +616,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } } - waitTimerLastRunDate = new Date(); + waitTimerLastRunDate = currentTime.getDate(); logger.debug("DesignatedWaiter.run (designatedPdp.getPdpId().equals(myPdp.getPdpId())) " + "waitTimerLastRunDate = " + waitTimerLastRunDate); myPdp.setUpdatedDate(waitTimerLastRunDate); @@ -920,7 +923,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { synchronized (checkWaitTimerLock) { try { logger.debug("checkWaitTimer: entry"); - Date now = new Date(); + Date now = currentTime.getDate(); long nowMs = now.getTime(); long waitTimerMs = waitTimerLastRunDate.getTime(); @@ -951,7 +954,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } private long getDWaiterStartMs() { - Date now = new Date(); + Date now = currentTime.getDate(); // Retrieve the ms since the epoch long nowMs = now.getTime(); diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/Factory.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/Factory.java new file mode 100644 index 00000000..fae70074 --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/Factory.java @@ -0,0 +1,40 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.util.Timer; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; + +/** + * Factory for creating various objects. + */ +public class Factory { + + @Getter + @Setter(AccessLevel.PROTECTED) + private static Factory instance = new Factory(); + + public Timer makeTimer() { + return new Timer(); + } +} diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java index ed53f55c..1830d055 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java @@ -30,7 +30,8 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.FlushModeType; import javax.persistence.LockModeType; import javax.persistence.Query; - +import org.onap.policy.common.im.MonitorTime; +import org.onap.policy.common.utils.time.CurrentTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +44,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { private static final Logger logger = LoggerFactory.getLogger(JpaDroolsPdpsConnector.class); private EntityManagerFactory emf; + private final CurrentTime currentTime = MonitorTime.getInstance(); + //not sure if we want to use the same entity manager factory //for drools session and pass it in here, or create a new one @@ -114,7 +117,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { if (droolsPdpsList.size() == 1 && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)) { droolsPdpEntity = (DroolsPdpEntity)droolsPdpsList.get(0); em.refresh(droolsPdpEntity); //Make sure we have current values - Date currentDate = new Date(); + Date currentDate = currentTime.getDate(); long difference = currentDate.getTime() - droolsPdpEntity.getUpdatedDate().getTime(); //just set some kind of default here long pdpTimeout = 15000; @@ -156,7 +159,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { droolsPdpEntity.setDesignated(pdp.isDesignated()); //The isDesignated value is not the same and the new one == true if (pdp.isDesignated()) { - droolsPdpEntity.setDesignatedDate(new Date()); + droolsPdpEntity.setDesignatedDate(currentTime.getDate()); } } em.getTransaction().commit(); @@ -255,7 +258,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { if (designated) { em.refresh(droolsPdpEntity); //make sure we get the DB value if (!droolsPdpEntity.isDesignated()) { - droolsPdpEntity.setDesignatedDate(new Date()); + droolsPdpEntity.setDesignatedDate(currentTime.getDate()); } } @@ -369,7 +372,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { // time box that may be. // If the the PDP is not current, we should mark it as not primary in // the database - Date currentDate = new Date(); + Date currentDate = currentTime.getDate(); long difference = currentDate.getTime() - pdp.getUpdatedDate().getTime(); // just set some kind of default here diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java index 7669cc22..735e3a2a 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java @@ -20,31 +20,12 @@ package org.onap.policy.drools.activestandby; -/* - * Per MultiSite_v1-10.ppt: - * - * Extends the StateChangeNotifier class and overwrites the abstract handleStateChange() method to get state changes - * and do the following: - * - * When the Standby Status changes (from providingservice) to hotstandby or coldstandby, - * the Active/Standby selection algorithm must stand down if the PDP-D is currently the lead/active node - * and allow another PDP-D to take over. It must also call lock on all engines in the engine management. - * - * When the Standby Status changes from (hotstandby) to coldstandby, the Active/Standby algorithm must NOT assume - * the active/lead role. - * - * When the Standby Status changes (from coldstandby or providingservice) to hotstandby, - * the Active/Standby algorithm may assume the active/lead role if the active/lead fails. - * - * When the Standby Status changes to providingservice (from hotstandby or coldstandby) call unlock on all - * engines in the engine management layer. - */ -import java.util.Date; import java.util.Timer; import java.util.TimerTask; - +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.common.im.StateChangeNotifier; import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.utils.time.CurrentTime; import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.drools.system.PolicyEngineConstants; import org.slf4j.Logger; @@ -89,6 +70,8 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { private long waitInterval; private boolean isNowActivating; private String previousStandbyStatus; + private final CurrentTime currentTime = MonitorTime.getInstance(); + private final Factory timerFactory = Factory.getInstance(); public static final String NONE = "none"; public static final String UNSUPPORTED = "unsupported"; public static final String HOTSTANDBY_OR_COLDSTANDBY = "hotstandby_or_coldstandby"; @@ -101,7 +84,7 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { pdpUpdateInterval = Integer.parseInt(ActiveStandbyProperties.getProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL)); isWaitingForActivation = false; - startTimeWaitingForActivationMs = new Date().getTime(); + startTimeWaitingForActivationMs = currentTime.getMillis(); // delay the activate so the DesignatedWaiter can run twice - give it an extra 2 seconds waitInterval = 2 * pdpUpdateInterval + 2000L; isNowActivating = false; @@ -222,11 +205,11 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { // Just in case there is an old timer hanging around logger.debug("handleStateChange: PROVIDING_SERVICE cancelling delayActivationTimer."); cancelTimer(); - delayActivateTimer = makeTimer(); + delayActivateTimer = timerFactory.makeTimer(); // delay the activate so the DesignatedWaiter can run twice delayActivateTimer.schedule(new DelayActivateClass(), waitInterval); isWaitingForActivation = true; - startTimeWaitingForActivationMs = new Date().getTime(); + startTimeWaitingForActivationMs = currentTime.getMillis(); logger.debug("handleStateChange: PROVIDING_SERVICE scheduling delayActivationTimer in {} ms", waitInterval); } else { @@ -244,7 +227,7 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { if (isWaitingForActivation) { logger.debug("handleStateChange: PROVIDING_SERVICE isWaitingForActivation = {}", isWaitingForActivation); - long now = new Date().getTime(); + long now = currentTime.getMillis(); long waitTimeMs = now - startTimeWaitingForActivationMs; if (waitTimeMs > 3 * waitInterval) { logger.debug("handleStateChange: PROVIDING_SERVICE looks like the activation wait timer " @@ -327,8 +310,4 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { protected PolicyEngine getPolicyEngineManager() { return PolicyEngineConstants.getManager(); } - - protected Timer makeTimer() { - return new Timer(); - } } diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/AllSeemsWellTest.java index 5e9b360f..cb7e4c3f 100644 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/AllSeemsWellTest.java @@ -18,37 +18,38 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.drools.controller.test; +package org.onap.policy.drools.activestandby; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -import java.io.File; import java.io.FileInputStream; +import java.io.IOException; import java.util.Date; import java.util.Properties; -import java.util.function.Supplier; +import java.util.concurrent.Callable; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import org.apache.commons.lang3.time.DateUtils; -import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.IntegrityMonitorException; +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.common.im.StateManagement; -import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApi; -import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApiConstants; -import org.onap.policy.drools.activestandby.ActiveStandbyProperties; -import org.onap.policy.drools.activestandby.DroolsPdpEntity; -import org.onap.policy.drools.activestandby.DroolsPdpImpl; -import org.onap.policy.drools.activestandby.DroolsPdpsConnector; -import org.onap.policy.drools.activestandby.DroolsPdpsElectionHandler; -import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector; +import org.onap.policy.common.utils.time.CurrentTime; +import org.onap.policy.common.utils.time.PseudoTimer; +import org.onap.policy.common.utils.time.TestTimeMulti; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; +import org.powermock.reflect.Whitebox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,6 +60,10 @@ import org.slf4j.LoggerFactory; public class AllSeemsWellTest { private static final Logger logger = LoggerFactory.getLogger(AllSeemsWellTest.class); + + private static final String MONITOR_FIELD_NAME = "instance"; + private static final String HANDLER_INSTANCE_FIELD = "electionHandler"; + /* * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion @@ -66,7 +71,7 @@ public class AllSeemsWellTest { * checking the results. Add a few seconds for safety */ - private static int SLEEP_TIME_SEC = 10; + private static final int SLEEP_TIME_SEC = 10; /* * DroolsPdpsElectionHandler runs every 1 seconds, so it takes 10 seconds for the @@ -74,7 +79,7 @@ public class AllSeemsWellTest { * the forward progress counter to go stale which should add an additional 5 sec. */ - private static int STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC = 15; + private static final int STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC = 15; /* * As soon as the election hander successfully runs, it will resume the forward progress. @@ -82,7 +87,7 @@ public class AllSeemsWellTest { * then fpc is written every 1 sec and then the fpc is checked every 2 sec, that could * take a total of 5 sec to recognize the resumption of progress. So, add 1 for safety. */ - private static int RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC = 6; + private static final int RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC = 6; private static EntityManagerFactory emfx; private static EntityManagerFactory emfd; @@ -90,7 +95,12 @@ public class AllSeemsWellTest { private static EntityManager emd; private static EntityTransaction et; - private final String configDir = "src/test/resources/asw"; + private static final String CONFIG_DIR = "src/test/resources/asw"; + + private static CurrentTime saveTime; + private static Factory saveFactory; + + private TestTimeMulti testTime; /* * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing. @@ -108,23 +118,16 @@ public class AllSeemsWellTest { logger.debug("setUpClass: userDir={}", userDir); System.setProperty("com.sun.management.jmxremote.port", "9980"); System.setProperty("com.sun.management.jmxremote.authenticate","false"); - } - @AfterClass - public static void tearDownClass() throws Exception { - } + DroolsPdpsElectionHandler.setIsUnitTesting(true); - /** - * Setup. - * - * @throws Exception exception - */ - @Before - public void setUp() throws Exception { - //Create teh data access for xaml db - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); + saveTime = Whitebox.getInternalState(MonitorTime.class, MONITOR_FIELD_NAME); + saveFactory = Factory.getInstance(); + + resetInstanceObjects(); + + //Create the data access for xacml db + Properties stateManagementProperties = loadStateManagementProperties(); emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties); @@ -132,20 +135,59 @@ public class AllSeemsWellTest { emx = emfx.createEntityManager(); //Create the data access for drools db - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties); // Create an entity manager to use the DB emd = emfd.createEntityManager(); + } - DroolsPdpsElectionHandler.setIsUnitTesting(true); + /** + * Restores the system state. + * + * @throws IntegrityMonitorException if the integrity monitor cannot be shut down + */ + @AfterClass + public static void tearDownClass() throws IntegrityMonitorException { + resetInstanceObjects(); + + Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, saveTime); + Factory.setInstance(saveFactory); + + DroolsPdpsElectionHandler.setIsUnitTesting(false); + + emd.close(); + emfd.close(); + + emx.close(); + emfx.close(); } - @After - public void tearDown() throws Exception { + /** + * Setup. + * + * @throws Exception exception + */ + @Before + public void setUp() throws Exception { + resetInstanceObjects(); + + // set test time + testTime = new TestTimeMulti(); + Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, testTime); + + Factory factory = mock(Factory.class); + when(factory.makeTimer()).thenAnswer(ans -> new PseudoTimer(testTime)); + Factory.setInstance(factory); + } + + private static void resetInstanceObjects() throws IntegrityMonitorException { + IntegrityMonitor.setUnitTesting(true); + IntegrityMonitor.deleteInstance(); + IntegrityMonitor.setUnitTesting(false); + + Whitebox.setInternalState(ActiveStandbyFeature.class, HANDLER_INSTANCE_FIELD, (Object) null); } @@ -188,19 +230,13 @@ public class AllSeemsWellTest { cleanXacmlDb(); cleanDroolsDb(); - logger.debug("testAllSeemsWell: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); + Properties stateManagementProperties = loadStateManagementProperties(); logger.debug("testAllSeemsWell: Creating emfXacml"); final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( "junitXacmlPU", stateManagementProperties); - logger.debug("testAllSeemsWell: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); final String thisPdpId = activeStandbyProperties .getProperty(ActiveStandbyProperties.NODE_NAME); @@ -220,7 +256,7 @@ public class AllSeemsWellTest { */ logger.debug("testAllSeemsWell: Inserting PDP={} as not designated", thisPdpId); - Date yesterday = DateUtils.addDays(new Date(), -1); + Date yesterday = DateUtils.addDays(testTime.getDate(), -1); DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); conn.insertPdp(pdp); DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); @@ -238,40 +274,27 @@ public class AllSeemsWellTest { StateManagementFeatureApi stateManagementFeatureApi = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); stateManagementFeatureApi = feature; logger.debug("testAllSeemsWell stateManagementFeature.getResourceName(): {}", stateManagementFeatureApi.getResourceName()); break; } - if (stateManagementFeatureApi == null) { - logger.error("testAllSeemsWell failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testAllSeemsWell failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(stateManagementFeatureApi); + final StateManagementFeatureApi smf = stateManagementFeatureApi; // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); activeStandbyFeature = feature; logger.debug("testAllSeemsWell activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); break; } - if (activeStandbyFeature == null) { - logger.error("testAllSeemsWell failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testAllSeemsWell failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(activeStandbyFeature); logger.debug("testAllSeemsWell: Demoting PDP={}", thisPdpId); @@ -332,12 +355,24 @@ public class AllSeemsWellTest { } - private void waitForCondition(Supplier<Boolean> testCondition, int timeoutInSeconds) throws InterruptedException { - int maxIterations = timeoutInSeconds * 10; - int iterations = 0; - while (!testCondition.get() && iterations < maxIterations) { - iterations++; - Thread.sleep(100); + private static Properties loadStateManagementProperties() throws IOException { + try (FileInputStream input = new FileInputStream(CONFIG_DIR + "/feature-state-management.properties")) { + Properties props = new Properties(); + props.load(input); + return props; } } + + private static Properties loadActiveStandbyProperties() throws IOException { + try (FileInputStream input = + new FileInputStream(CONFIG_DIR + "/feature-active-standby-management.properties")) { + Properties props = new Properties(); + props.load(input); + return props; + } + } + + private void waitForCondition(Callable<Boolean> testCondition, int timeoutInSeconds) throws InterruptedException { + testTime.waitUntil(testCondition); + } } diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/FactoryTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/FactoryTest.java new file mode 100644 index 00000000..8a166954 --- /dev/null +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/FactoryTest.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FactoryTest { + private static Factory saveFactory; + + private Factory factory; + + @BeforeClass + public static void setUpBeforeClass() { + saveFactory = Factory.getInstance(); + assertNotNull(saveFactory); + } + + @AfterClass + public static void tearDownAfterClass() { + Factory.setInstance(saveFactory); + } + + @Before + public void setUp() { + factory = new Factory(); + } + + @Test + public void testMakeTimer() { + assertNotNull(factory.makeTimer()); + } + + @Test + public void testGetInstance_testSetInstance() { + Factory.setInstance(factory); + assertSame(factory, Factory.getInstance()); + + // repeat - should be the same + assertSame(factory, Factory.getInstance()); + } +} diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java index 28d3b439..4a89d257 100644 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java @@ -32,6 +32,7 @@ import static org.mockito.Mockito.when; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; +import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -47,6 +48,11 @@ public class PmStandbyStateChangeNotifierTest { private static final long UPDATE_INTERVAL = 100; private static final long WAIT_INTERVAL = 2 * UPDATE_INTERVAL + 2000; + private static Factory saveFactory; + + @Mock + private Factory factory; + @Mock private PolicyEngine engmgr; @@ -68,16 +74,25 @@ public class PmStandbyStateChangeNotifierTest { props.setProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL, String.valueOf(UPDATE_INTERVAL)); ActiveStandbyProperties.initProperties(props); + + saveFactory = Factory.getInstance(); + } + + @AfterClass + public static void tearDownAfterClass() { + Factory.setInstance(saveFactory); } /** * Initializes objects, including the notifier. */ - @Before public void setUp() { MockitoAnnotations.initMocks(this); + Factory.setInstance(factory); + when(factory.makeTimer()).thenReturn(timer); + notifier = new MyNotifier(); } @@ -167,12 +182,7 @@ public class PmStandbyStateChangeNotifierTest { @Test public void testHandleStateChange_ProvidingService_Ex() { - notifier = new MyNotifier() { - @Override - protected Timer makeTimer() { - throw new MyException(); - } - }; + when(factory.makeTimer()).thenThrow(new MyException()); when(mgmt.getStandbyStatus()).thenReturn(StateManagement.PROVIDING_SERVICE); notifier.update(mgmt, null); @@ -256,22 +266,11 @@ public class PmStandbyStateChangeNotifierTest { new PmStandbyStateChangeNotifier().getPolicyEngineManager(); } - @Test - public void testMakeTimer() { - // use real object with real method - new PmStandbyStateChangeNotifier().makeTimer().cancel(); - } - private class MyNotifier extends PmStandbyStateChangeNotifier { @Override protected PolicyEngine getPolicyEngineManager() { return engmgr; } - - @Override - protected Timer makeTimer() { - return timer; - } } private static class MyException extends RuntimeException { diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/StandbyStateManagementTest.java index 8bc8489a..143aaf31 100644 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/StandbyStateManagementTest.java @@ -1,4 +1,4 @@ -/* +/*- * ============LICENSE_START======================================================= * feature-active-standby-management * ================================================================================ @@ -18,12 +18,15 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.drools.controller.test; +package org.onap.policy.drools.activestandby; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -import java.io.File; import java.io.FileInputStream; +import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -32,30 +35,24 @@ import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; - import org.apache.commons.lang3.time.DateUtils; -import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.im.AdministrativeStateException; import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.IntegrityMonitorException; +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.common.im.StandbyStatusException; import org.onap.policy.common.im.StateManagement; -import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApi; -import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApiConstants; -import org.onap.policy.drools.activestandby.ActiveStandbyProperties; -import org.onap.policy.drools.activestandby.DroolsPdp; -import org.onap.policy.drools.activestandby.DroolsPdpEntity; -import org.onap.policy.drools.activestandby.DroolsPdpImpl; -import org.onap.policy.drools.activestandby.DroolsPdpsConnector; -import org.onap.policy.drools.activestandby.DroolsPdpsElectionHandler; -import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector; -import org.onap.policy.drools.activestandby.PmStandbyStateChangeNotifier; +import org.onap.policy.common.utils.time.CurrentTime; +import org.onap.policy.common.utils.time.PseudoTimer; +import org.onap.policy.common.utils.time.TestTimeMulti; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; +import org.powermock.reflect.Whitebox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -72,6 +69,10 @@ import org.slf4j.LoggerFactory; public class StandbyStateManagementTest { private static final Logger logger = LoggerFactory.getLogger(StandbyStateManagementTest.class); + + private static final String MONITOR_FIELD_NAME = "instance"; + private static final String HANDLER_INSTANCE_FIELD = "electionHandler"; + /* * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion @@ -79,20 +80,20 @@ public class StandbyStateManagementTest { * checking the results. Add a few seconds for safety */ - long sleepTime = 10000; + private static final long SLEEP_TIME = 10000; /* * DroolsPdpsElectionHandler runs every 1 seconds, so a 6 second sleep should be * plenty to ensure it has time to re-promote this PDP. */ - long electionWaitSleepTime = 6000; + private static final long ELECTION_WAIT_SLEEP_TIME = 6000; /* - * Sleep 1 seconds after each test to allow interrupt (shutdown) recovery. + * Sleep a few seconds after each test to allow interrupt (shutdown) recovery. */ - long interruptRecoveryTime = 5000; + private static final long INTERRUPT_RECOVERY_TIME = 5000; private static EntityManagerFactory emfx; private static EntityManagerFactory emfd; @@ -100,7 +101,12 @@ public class StandbyStateManagementTest { private static EntityManager emd; private static EntityTransaction et; - private final String configDir = "src/test/resources"; + private static final String CONFIG_DIR = "src/test/resources"; + + private static CurrentTime saveTime; + private static Factory saveFactory; + + private TestTimeMulti testTime; /* * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing. @@ -119,23 +125,13 @@ public class StandbyStateManagementTest { System.setProperty("com.sun.management.jmxremote.port", "9980"); System.setProperty("com.sun.management.jmxremote.authenticate","false"); - } + saveTime = Whitebox.getInternalState(MonitorTime.class, MONITOR_FIELD_NAME); + saveFactory = Factory.getInstance(); - @AfterClass - public static void tearDownClass() throws Exception { - } + resetInstanceObjects(); - /** - * Setup. - * - * @throws Exception exception - */ - @Before - public void setUp() throws Exception { - //Create teh data access for xaml db - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - "src/test/resources/feature-state-management.properties"))); + //Create the data access for xacml db + Properties stateManagementProperties = loadStateManagementProperties(); emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties); @@ -143,9 +139,7 @@ public class StandbyStateManagementTest { emx = emfx.createEntityManager(); //Create the data access for drools db - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - "src/test/resources/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties); @@ -153,8 +147,49 @@ public class StandbyStateManagementTest { emd = emfd.createEntityManager(); } - @After - public void tearDown() throws Exception { + /** + * Restores the system state. + * + * @throws IntegrityMonitorException if the integrity monitor cannot be shut down + */ + @AfterClass + public static void tearDownClass() throws IntegrityMonitorException { + resetInstanceObjects(); + + Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, saveTime); + Factory.setInstance(saveFactory); + + emd.close(); + emfd.close(); + + emx.close(); + emfx.close(); + } + + /** + * Setup. + * + * @throws Exception exception + */ + @Before + public void setUp() throws Exception { + resetInstanceObjects(); + + // set test time + testTime = new TestTimeMulti(); + Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, testTime); + + Factory factory = mock(Factory.class); + when(factory.makeTimer()).thenAnswer(ans -> new PseudoTimer(testTime)); + Factory.setInstance(factory); + } + + private static void resetInstanceObjects() throws IntegrityMonitorException { + IntegrityMonitor.setUnitTesting(true); + IntegrityMonitor.deleteInstance(); + IntegrityMonitor.setUnitTesting(false); + + Whitebox.setInternalState(ActiveStandbyFeature.class, HANDLER_INSTANCE_FIELD, (Object) null); } @@ -240,9 +275,7 @@ public class StandbyStateManagementTest { logger.debug("testPmStandbyStateChangeNotifier: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); String resourceName = "testPMS"; activeStandbyProperties.setProperty("resource.name", resourceName); @@ -324,12 +357,7 @@ public class StandbyStateManagementTest { // Get a DroolsPdpsConnector - logger.debug("testSanitizeDesignatedList: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); + Properties activeStandbyProperties = loadActiveStandbyProperties(); logger.debug("testSanitizeDesignatedList: Creating emfDrools"); EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( @@ -339,10 +367,10 @@ public class StandbyStateManagementTest { // Create 4 pdpd all not designated - DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); - DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); - DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); - DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, testTime.getDate()); + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, testTime.getDate()); + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, testTime.getDate()); + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, testTime.getDate()); List<DroolsPdp> listOfDesignated = new ArrayList<DroolsPdp>(); listOfDesignated.add(pdp1); @@ -355,20 +383,13 @@ public class StandbyStateManagementTest { StateManagementFeatureApi stateManagementFeature = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); stateManagementFeature = feature; logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", stateManagementFeature.getResourceName()); break; } - if (stateManagementFeature == null) { - logger.error("testColdStandby failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testColdStandby failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(stateManagementFeature); DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); @@ -421,12 +442,7 @@ public class StandbyStateManagementTest { logger.debug("\n\ntestComputeMostRecentPrimary: Entering\n\n"); - logger.debug("testComputeMostRecentPrimary: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); + Properties activeStandbyProperties = loadActiveStandbyProperties(); logger.debug("testComputeMostRecentPrimary: Creating emfDrools"); EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( @@ -438,18 +454,18 @@ public class StandbyStateManagementTest { // Create 4 pdpd all not designated - long designatedDateMs = new Date().getTime(); - DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); + long designatedDateMs = testTime.getMillis(); + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, testTime.getDate()); pdp1.setDesignatedDate(new Date(designatedDateMs - 2)); - DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, testTime.getDate()); //oldest pdp2.setDesignatedDate(new Date(designatedDateMs - 3)); - DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, testTime.getDate()); pdp3.setDesignatedDate(new Date(designatedDateMs - 1)); - DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, testTime.getDate()); //most recent pdp4.setDesignatedDate(new Date(designatedDateMs)); @@ -474,20 +490,13 @@ public class StandbyStateManagementTest { StateManagementFeatureApi stateManagementFeature = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); stateManagementFeature = feature; logger.debug("testComputeMostRecentPrimary stateManagementFeature.getResourceName(): {}", stateManagementFeature.getResourceName()); break; } - if (stateManagementFeature == null) { - logger.error("testComputeMostRecentPrimary failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testComputeMostRecentPrimary failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(stateManagementFeature); DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); @@ -601,12 +610,7 @@ public class StandbyStateManagementTest { logger.debug("\n\ntestComputeDesignatedPdp: Entering\n\n"); - logger.debug("testComputeDesignatedPdp: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); + Properties activeStandbyProperties = loadActiveStandbyProperties(); logger.debug("testComputeDesignatedPdp: Creating emfDrools"); @@ -619,21 +623,21 @@ public class StandbyStateManagementTest { // Create 4 pdpd all not designated. Two on site1. Two on site2 - long designatedDateMs = new Date().getTime(); - DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); + long designatedDateMs = testTime.getMillis(); + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, testTime.getDate()); pdp1.setDesignatedDate(new Date(designatedDateMs - 2)); pdp1.setSite("site1"); - DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, testTime.getDate()); pdp2.setDesignatedDate(new Date(designatedDateMs - 3)); pdp2.setSite("site1"); //oldest - DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, testTime.getDate()); pdp3.setDesignatedDate(new Date(designatedDateMs - 4)); pdp3.setSite("site2"); - DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, testTime.getDate()); //most recent pdp4.setDesignatedDate(new Date(designatedDateMs)); pdp4.setSite("site2"); @@ -656,20 +660,13 @@ public class StandbyStateManagementTest { StateManagementFeatureApi stateManagementFeature = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); stateManagementFeature = feature; logger.debug("testComputeDesignatedPdp stateManagementFeature.getResourceName(): {}", stateManagementFeature.getResourceName()); break; } - if (stateManagementFeature == null) { - logger.error("testComputeDesignatedPdp failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testComputeDesignatedPdp failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(stateManagementFeature); DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); @@ -739,19 +736,13 @@ public class StandbyStateManagementTest { cleanXacmlDb(); cleanDroolsDb(); - logger.debug("testColdStandby: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); + Properties stateManagementProperties = loadStateManagementProperties(); logger.debug("testColdStandby: Creating emfXacml"); final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( "junitXacmlPU", stateManagementProperties); - logger.debug("testColdStandby: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); final String thisPdpId = activeStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME); logger.debug("testColdStandby: Creating emfDrools"); @@ -764,7 +755,7 @@ public class StandbyStateManagementTest { conn.deleteAllPdps(); logger.debug("testColdStandby: Inserting PDP={} as designated", thisPdpId); - DroolsPdp pdp = new DroolsPdpImpl(thisPdpId, true, 4, new Date()); + DroolsPdp pdp = new DroolsPdpImpl(thisPdpId, true, 4, testTime.getDate()); conn.insertPdp(pdp); DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); logger.debug("testColdStandby: After insertion, DESIGNATED= {} " @@ -796,47 +787,33 @@ public class StandbyStateManagementTest { StateManagementFeatureApi smf = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); smf = feature; logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", smf.getResourceName()); break; } - if (smf == null) { - logger.error("testColdStandby failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testColdStandby failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(smf); // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); activeStandbyFeature = feature; logger.debug("testColdStandby activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); break; } - if (activeStandbyFeature == null) { - logger.error("testColdStandby failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID:{}", thisPdpId); - logger.debug("testColdStandby failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID:{}", thisPdpId); - } + assertNotNull(activeStandbyFeature); // Artificially putting a PDP into service is really a two step process, 1) // inserting it as designated and 2) promoting it so that its standbyStatus // is providing service. logger.debug("testColdStandby: Runner started; Sleeping " - + interruptRecoveryTime + "ms before promoting PDP= {}", + + INTERRUPT_RECOVERY_TIME + "ms before promoting PDP= {}", thisPdpId); - sleep(interruptRecoveryTime); + sleep(INTERRUPT_RECOVERY_TIME); logger.debug("testColdStandby: Promoting PDP={}", thisPdpId); smf.promote(); @@ -848,7 +825,7 @@ public class StandbyStateManagementTest { logger.debug("testColdStandby: Locking smf"); smf.lock(); - sleep(interruptRecoveryTime); + sleep(INTERRUPT_RECOVERY_TIME); // Verify that the PDP is no longer designated. @@ -858,7 +835,7 @@ public class StandbyStateManagementTest { assertTrue(droolsPdpEntity.isDesignated() == false); logger.debug("\n\ntestColdStandby: Exiting\n\n"); - sleep(interruptRecoveryTime); + sleep(INTERRUPT_RECOVERY_TIME); } @@ -877,19 +854,13 @@ public class StandbyStateManagementTest { cleanXacmlDb(); cleanDroolsDb(); - logger.debug("testHotStandby1: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); + Properties stateManagementProperties = loadStateManagementProperties(); logger.debug("testHotStandby1: Creating emfXacml"); final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( "junitXacmlPU", stateManagementProperties); - logger.debug("testHotStandby1: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); final String thisPdpId = activeStandbyProperties .getProperty(ActiveStandbyProperties.NODE_NAME); @@ -909,7 +880,7 @@ public class StandbyStateManagementTest { */ logger.debug("testHotStandby1: Inserting PDP={} as not designated", thisPdpId); - Date yesterday = DateUtils.addDays(new Date(), -1); + Date yesterday = DateUtils.addDays(testTime.getDate(), -1); DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); conn.insertPdp(pdp); DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); @@ -927,38 +898,24 @@ public class StandbyStateManagementTest { StateManagementFeatureApi smf = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); smf = feature; logger.debug("testHotStandby1 stateManagementFeature.getResourceName(): {}", smf.getResourceName()); break; } - if (smf == null) { - logger.error("testHotStandby1 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testHotStandby1 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(smf); // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); activeStandbyFeature = feature; logger.debug("testHotStandby1 activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); break; } - if (activeStandbyFeature == null) { - logger.error("testHotStandby1 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testHotStandby1 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(activeStandbyFeature); logger.debug("testHotStandby1: Demoting PDP={}", thisPdpId); @@ -967,8 +924,8 @@ public class StandbyStateManagementTest { logger.debug("testHotStandby1: Sleeping {} ms, to allow JpaDroolsPdpsConnector " - + "time to check droolspdpentity table", sleepTime); - sleep(sleepTime); + + "time to check droolspdpentity table", SLEEP_TIME); + sleep(SLEEP_TIME); // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service. @@ -985,7 +942,7 @@ public class StandbyStateManagementTest { logger.debug("testHotStandby1: Stopping policyManagementRunner"); logger.debug("\n\ntestHotStandby1: Exiting\n\n"); - sleep(interruptRecoveryTime); + sleep(INTERRUPT_RECOVERY_TIME); } @@ -1006,19 +963,13 @@ public class StandbyStateManagementTest { cleanXacmlDb(); cleanDroolsDb(); - logger.info("testHotStandby2: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); + Properties stateManagementProperties = loadStateManagementProperties(); logger.info("testHotStandby2: Creating emfXacml"); final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( "junitXacmlPU", stateManagementProperties); - logger.info("testHotStandby2: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); final String thisPdpId = activeStandbyProperties .getProperty(ActiveStandbyProperties.NODE_NAME); @@ -1036,7 +987,7 @@ public class StandbyStateManagementTest { String activePdpId = "pdp2"; logger.info("testHotStandby2: Inserting PDP={} as stale, designated PDP", activePdpId); - Date yesterday = DateUtils.addDays(new Date(), -1); + Date yesterday = DateUtils.addDays(testTime.getDate(), -1); DroolsPdp pdp = new DroolsPdpImpl(activePdpId, true, 4, yesterday); conn.insertPdp(pdp); DroolsPdpEntity droolsPdpEntity = conn.getPdp(activePdpId); @@ -1084,42 +1035,28 @@ public class StandbyStateManagementTest { StateManagementFeatureApi sm2 = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); sm2 = feature; logger.debug("testHotStandby2 stateManagementFeature.getResourceName(): {}", sm2.getResourceName()); break; } - if (sm2 == null) { - logger.error("testHotStandby2 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testHotStandby2 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(sm2); // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); activeStandbyFeature = feature; logger.debug("testHotStandby2 activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); break; } - if (activeStandbyFeature == null) { - logger.error("testHotStandby2 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testHotStandby2 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(activeStandbyFeature); logger.info("testHotStandby2: Runner started; Sleeping {} " - + "ms before promoting/demoting", interruptRecoveryTime); - sleep(interruptRecoveryTime); + + "ms before promoting/demoting", INTERRUPT_RECOVERY_TIME); + sleep(INTERRUPT_RECOVERY_TIME); logger.info("testHotStandby2: Runner started; promoting PDP={}", activePdpId); //At this point, the newly created pdp will have set the state to disabled/failed/cold standby @@ -1137,8 +1074,8 @@ public class StandbyStateManagementTest { logger.info("testHotStandby2: After demoting, PDP={} has standbyStatus= {}",thisPdpId , standbyStatus); logger.info("testHotStandby2: Sleeping {} ms, to allow JpaDroolsPdpsConnector " - + "time to check droolspdpentity table", sleepTime); - sleep(sleepTime); + + "time to check droolspdpentity table", SLEEP_TIME); + sleep(SLEEP_TIME); /* * Verify that this PDP, demoted to HOT_STANDBY, is now @@ -1160,7 +1097,7 @@ public class StandbyStateManagementTest { logger.info("testHotStandby2: Stopping policyManagementRunner"); logger.info("\n\ntestHotStandby2: Exiting\n\n"); - sleep(interruptRecoveryTime); + sleep(INTERRUPT_RECOVERY_TIME); } @@ -1194,19 +1131,13 @@ public class StandbyStateManagementTest { cleanXacmlDb(); cleanDroolsDb(); - logger.debug("testLocking1: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); + Properties stateManagementProperties = loadStateManagementProperties(); logger.debug("testLocking1: Creating emfXacml"); final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( "junitXacmlPU", stateManagementProperties); - logger.debug("testLocking1: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); final String thisPdpId = activeStandbyProperties .getProperty(ActiveStandbyProperties.NODE_NAME); @@ -1225,7 +1156,7 @@ public class StandbyStateManagementTest { */ logger.debug("testLocking1: Inserting PDP= {} as designated", thisPdpId); - DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 4, new Date()); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 4, testTime.getDate()); conn.insertPdp(pdp); DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); logger.debug("testLocking1: After insertion, PDP= {} has DESIGNATED= {}", @@ -1241,51 +1172,37 @@ public class StandbyStateManagementTest { StateManagementFeatureApi sm = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); sm = feature; logger.debug("testLocking1 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); break; } - if (sm == null) { - logger.error("testLocking1 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testLocking1 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(sm); // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); activeStandbyFeature = feature; logger.debug("testLocking1 activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); break; } - if (activeStandbyFeature == null) { - logger.error("testLocking1 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testLocking1 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(activeStandbyFeature); logger.debug("testLocking1: Runner started; Sleeping " - + interruptRecoveryTime + "ms before promoting PDP={}", + + INTERRUPT_RECOVERY_TIME + "ms before promoting PDP={}", thisPdpId); - sleep(interruptRecoveryTime); + sleep(INTERRUPT_RECOVERY_TIME); logger.debug("testLocking1: Promoting PDP={}", thisPdpId); sm.promote(); logger.debug("testLocking1: Sleeping {} ms, to allow time for " + "policy-management.Main class to come up, designated= {}", - sleepTime, conn.getPdp(thisPdpId).isDesignated()); - sleep(sleepTime); + SLEEP_TIME, conn.getPdp(thisPdpId).isDesignated()); + sleep(SLEEP_TIME); logger.debug("testLocking1: Waking up and invoking startTransaction on active PDP={}" + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated()); @@ -1312,9 +1229,9 @@ public class StandbyStateManagementTest { logger.debug("testLocking1: demoting PDP={}", thisPdpId); sm.demote(); - logger.debug("testLocking1: sleeping" + electionWaitSleepTime + logger.debug("testLocking1: sleeping" + ELECTION_WAIT_SLEEP_TIME + " to allow election handler to re-promote PDP={}", thisPdpId); - sleep(electionWaitSleepTime); + sleep(ELECTION_WAIT_SLEEP_TIME); logger.debug("testLocking1: Invoking startTransaction on re-promoted PDP={}" + ", designated={}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); @@ -1365,7 +1282,7 @@ public class StandbyStateManagementTest { // Just to avoid any race conditions, sleep a little after locking logger.debug("testLocking1: Sleeping a few millis after unlocking, to avoid race condition"); - sleep(electionWaitSleepTime); + sleep(ELECTION_WAIT_SLEEP_TIME); logger.debug("testLocking1: Invoking startTransaction on unlocked PDP=" + thisPdpId @@ -1413,7 +1330,7 @@ public class StandbyStateManagementTest { } logger.debug("\n\ntestLocking1: Exiting\n\n"); - sleep(interruptRecoveryTime); + sleep(INTERRUPT_RECOVERY_TIME); } @@ -1441,19 +1358,13 @@ public class StandbyStateManagementTest { cleanXacmlDb(); cleanDroolsDb(); - logger.debug("testLocking2: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); + Properties stateManagementProperties = loadStateManagementProperties(); logger.debug("testLocking2: Creating emfXacml"); final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( "junitXacmlPU", stateManagementProperties); - logger.debug("testLocking2: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); + Properties activeStandbyProperties = loadActiveStandbyProperties(); final String thisPdpId = activeStandbyProperties .getProperty(ActiveStandbyProperties.NODE_NAME); @@ -1473,7 +1384,7 @@ public class StandbyStateManagementTest { */ logger.debug("testLocking2: Inserting PDP= {} as designated", thisPdpId); - DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 3, new Date()); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 3, testTime.getDate()); conn.insertPdp(pdp); DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); logger.debug("testLocking2: After insertion, PDP= {} has DESIGNATED= {}", @@ -1489,38 +1400,24 @@ public class StandbyStateManagementTest { StateManagementFeatureApi sm = null; for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); sm = feature; logger.debug("testLocking2 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); break; } - if (sm == null) { - logger.error("testLocking2 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testLocking2 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(sm); // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); activeStandbyFeature = feature; logger.debug("testLocking2 activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); break; } - if (activeStandbyFeature == null) { - logger.error("testLocking2 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testLocking2 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } + assertNotNull(activeStandbyFeature); /* * Insert another PDP as not designated. Initial standby state will be @@ -1530,7 +1427,7 @@ public class StandbyStateManagementTest { String standbyPdpId = "pdp2"; logger.debug("testLocking2: Inserting PDP= {} as not designated", standbyPdpId); - Date yesterday = DateUtils.addDays(new Date(), -1); + Date yesterday = DateUtils.addDays(testTime.getDate(), -1); pdp = new DroolsPdpImpl(standbyPdpId, false, 4, yesterday); conn.insertPdp(pdp); droolsPdpEntity = conn.getPdp(standbyPdpId); @@ -1542,8 +1439,8 @@ public class StandbyStateManagementTest { final StateManagement sm2 = new StateManagement(emfXacml, standbyPdpId); logger.debug("testLocking2: Runner started; Sleeping {} ms " - + "before promoting/demoting", interruptRecoveryTime); - sleep(interruptRecoveryTime); + + "before promoting/demoting", INTERRUPT_RECOVERY_TIME); + sleep(INTERRUPT_RECOVERY_TIME); logger.debug("testLocking2: Promoting PDP= {}", thisPdpId); sm.promote(); @@ -1552,8 +1449,8 @@ public class StandbyStateManagementTest { logger.debug("testLocking2: Demoting PDP={}", standbyPdpId); sm2.demote(); - logger.debug("testLocking2: Sleeping {} ms, to allow time for to come up", sleepTime); - sleep(sleepTime); + logger.debug("testLocking2: Sleeping {} ms, to allow time for to come up", SLEEP_TIME); + sleep(SLEEP_TIME); logger.debug("testLocking2: Waking up and invoking startTransaction on active PDP={}" + ", designated= {}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); @@ -1580,8 +1477,8 @@ public class StandbyStateManagementTest { sm.demote(); logger.debug("testLocking2: sleeping {}" - + " to allow election handler to re-promote PDP={}", electionWaitSleepTime, thisPdpId); - sleep(electionWaitSleepTime); + + " to allow election handler to re-promote PDP={}", ELECTION_WAIT_SLEEP_TIME, thisPdpId); + sleep(ELECTION_WAIT_SLEEP_TIME); logger.debug("testLocking2: Waking up and invoking startTransaction " + "on re-promoted PDP= {}, designated= {}", @@ -1606,10 +1503,27 @@ public class StandbyStateManagementTest { assertTrue(standbyPdpDesignated == false); logger.debug("\n\ntestLocking2: Exiting\n\n"); - sleep(interruptRecoveryTime); + sleep(INTERRUPT_RECOVERY_TIME); + } + + private static Properties loadStateManagementProperties() throws IOException { + try (FileInputStream input = new FileInputStream(CONFIG_DIR + "/feature-state-management.properties")) { + Properties props = new Properties(); + props.load(input); + return props; + } + } + + private static Properties loadActiveStandbyProperties() throws IOException { + try (FileInputStream input = + new FileInputStream(CONFIG_DIR + "/feature-active-standby-management.properties")) { + Properties props = new Properties(); + props.load(input); + return props; + } } private void sleep(long sleepms) throws InterruptedException { - Thread.sleep(sleepms); + testTime.waitFor(sleepms); } } diff --git a/feature-active-standby-management/src/test/resources/META-INF/persistence.xml b/feature-active-standby-management/src/test/resources/META-INF/persistence.xml index 549f01de..ecbf22b7 100644 --- a/feature-active-standby-management/src/test/resources/META-INF/persistence.xml +++ b/feature-active-standby-management/src/test/resources/META-INF/persistence.xml @@ -31,15 +31,6 @@ <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" /> - <property - name="javax.persistence.schema-generation.scripts.action" - value="drop-and-create" /> - <property - name="javax.persistence.schema-generation.scripts.create-target" - value="./sql/generatedCreateDrools.ddl" /> - <property - name="javax.persistence.schema-generation.scripts.drop-target" - value="./sql/generatedDropDrools.ddl" /> </properties> </persistence-unit> <persistence-unit name="junitXacmlPU" @@ -52,15 +43,6 @@ <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" /> - <property - name="javax.persistence.schema-generation.scripts.action" - value="drop-and-create" /> - <property - name="javax.persistence.schema-generation.scripts.create-target" - value="./sql/generatedCreateXacml.ddl" /> - <property - name="javax.persistence.schema-generation.scripts.drop-target" - value="./sql/generatedDropXacml.ddl" /> </properties> </persistence-unit> </persistence> diff --git a/feature-active-standby-management/src/test/resources/asw/feature-active-standby-management.properties b/feature-active-standby-management/src/test/resources/asw/feature-active-standby-management.properties index f0711e6c..9b01736c 100644 --- a/feature-active-standby-management/src/test/resources/asw/feature-active-standby-management.properties +++ b/feature-active-standby-management/src/test/resources/asw/feature-active-standby-management.properties @@ -20,7 +20,7 @@ # DB properties javax.persistence.jdbc.driver = org.h2.Driver -javax.persistence.jdbc.url = jdbc:h2:file:./sql/activestandbymanagement +javax.persistence.jdbc.url = jdbc:h2:mem:asw_activestandbymanagement javax.persistence.jdbc.user = sa javax.persistence.jdbc.password = diff --git a/feature-active-standby-management/src/test/resources/asw/feature-state-management.properties b/feature-active-standby-management/src/test/resources/asw/feature-state-management.properties index 2629c63d..a5403c9f 100644 --- a/feature-active-standby-management/src/test/resources/asw/feature-state-management.properties +++ b/feature-active-standby-management/src/test/resources/asw/feature-state-management.properties @@ -20,7 +20,7 @@ # DB properties javax.persistence.jdbc.driver = org.h2.Driver -javax.persistence.jdbc.url = jdbc:h2:file:./sql/statemanagement +javax.persistence.jdbc.url = jdbc:h2:mem:asw_statemanagement javax.persistence.jdbc.user = sa javax.persistence.jdbc.password = @@ -28,7 +28,7 @@ javax.persistence.jdbc.password = http.server.services=TEST http.server.services.TEST.host=0.0.0.0 -http.server.services.TEST.port=9981 +http.server.services.TEST.port=9982 #These properties will default to the following if no other values are provided: # http.server.services.TEST.restClasses=org.onap.policy.drools.statemanagement.IntegrityMonitorRestManager # http.server.services.TEST.managed=false diff --git a/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties b/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties index 827d2e17..9e481b59 100644 --- a/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties +++ b/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties @@ -20,7 +20,7 @@ # DB properties javax.persistence.jdbc.driver = org.h2.Driver -javax.persistence.jdbc.url = jdbc:h2:file:./sql/activestandbymanagement +javax.persistence.jdbc.url = jdbc:h2:mem:activestandbymanagement javax.persistence.jdbc.user = sa javax.persistence.jdbc.password = diff --git a/feature-active-standby-management/src/test/resources/feature-state-management.properties b/feature-active-standby-management/src/test/resources/feature-state-management.properties index 3dd88473..ec840901 100644 --- a/feature-active-standby-management/src/test/resources/feature-state-management.properties +++ b/feature-active-standby-management/src/test/resources/feature-state-management.properties @@ -20,7 +20,7 @@ # DB properties javax.persistence.jdbc.driver = org.h2.Driver -javax.persistence.jdbc.url = jdbc:h2:file:./sql/statemanagement +javax.persistence.jdbc.url = jdbc:h2:mem:statemanagement javax.persistence.jdbc.user = sa javax.persistence.jdbc.password = diff --git a/feature-lifecycle/pom.xml b/feature-lifecycle/pom.xml index be5720dc..4884f48f 100644 --- a/feature-lifecycle/pom.xml +++ b/feature-lifecycle/pom.xml @@ -115,9 +115,15 @@ </dependency> <dependency> - <groupId>org.awaitility</groupId> - <artifactId>awaitility</artifactId> - <version>3.0.0</version> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>utils-test</artifactId> + <version>${policy.common.version}</version> <scope>test</scope> </dependency> diff --git a/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java b/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java index 36d2a545..5b4bd1ec 100644 --- a/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java +++ b/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -85,7 +86,7 @@ public class LifecycleFsm implements Startable { protected volatile LifecycleState state = new LifecycleStateTerminated(this); @GsonJsonIgnore - protected ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1); + protected ScheduledExecutorService scheduler = makeExecutor(); @GsonJsonIgnore protected ScheduledFuture<?> statusTask; @@ -118,10 +119,6 @@ public class LifecycleFsm implements Startable { */ public LifecycleFsm() { this.properties = SystemPersistenceConstants.getManager().getProperties(CONFIGURATION_PROPERTIES_NAME); - - scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - scheduler.setRemoveOnCancelPolicy(true); } @Override @@ -476,4 +473,15 @@ public class LifecycleFsm implements Startable { return fsm.isItMe(update.getName(), update.getPdpGroup(), update.getPdpSubgroup()); } } + + // these may be overridden by junit tests + + protected ScheduledExecutorService makeExecutor() { + ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1); + exec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); + exec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + exec.setRemoveOnCancelPolicy(true); + + return exec; + } } diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateActiveTest.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateActiveTest.java index 550379be..71245335 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateActiveTest.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateActiveTest.java @@ -21,7 +21,6 @@ package org.onap.policy.drools.lifecycle; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -59,7 +58,8 @@ public class LifecycleStateActiveTest extends LifecycleStateRunningTest { */ @Before public void startActive() throws CoderException { - fsm = new LifecycleFsm(); + fsm = makeFsmWithPseudoTime(); + fsm.setStatusTimerSeconds(15); assertTrue(fsm.start()); @@ -99,7 +99,7 @@ public class LifecycleStateActiveTest extends LifecycleStateRunningTest { assertEquals("A", fsm.getGroup()); assertEquals("a", fsm.getSubgroup()); assertTrue(fsm.isAlive()); - await().atMost(fsm.getStatusTimerSeconds() + 1, TimeUnit.SECONDS).until(isStatus(PdpState.ACTIVE)); + waitUntil(fsm.getStatusTimerSeconds() + 1, TimeUnit.SECONDS, isStatus(PdpState.ACTIVE)); } @Test @@ -114,7 +114,7 @@ public class LifecycleStateActiveTest extends LifecycleStateRunningTest { assertEquals(PdpState.TERMINATED, fsm.state()); assertFalse(fsm.isAlive()); assertFalse(fsm.state.isAlive()); - await().atMost(1, TimeUnit.SECONDS).until(isStatus(PdpState.TERMINATED)); + waitUntil(1, TimeUnit.SECONDS, isStatus(PdpState.TERMINATED)); } @Test @@ -143,7 +143,7 @@ public class LifecycleStateActiveTest extends LifecycleStateRunningTest { @Test public void status() { - await().atMost(fsm.getStatusTimerSeconds() + 1, TimeUnit.SECONDS).until(isStatus(PdpState.ACTIVE)); + waitUntil(fsm.getStatusTimerSeconds() + 1, TimeUnit.SECONDS, isStatus(PdpState.ACTIVE)); int preCount = fsm.client.getSink().getRecentEvents().length; assertTrue(fsm.status()); @@ -184,7 +184,7 @@ public class LifecycleStateActiveTest extends LifecycleStateRunningTest { change.setState(PdpState.PASSIVE); fsm.source.offer(new StandardCoder().encode(change)); assertEquals(PdpState.PASSIVE, fsm.state()); - await().atMost(fsm.getStatusTimerSeconds() + 1, TimeUnit.SECONDS).until(isStatus(PdpState.PASSIVE)); + waitUntil(fsm.getStatusTimerSeconds() + 1, TimeUnit.SECONDS, isStatus(PdpState.PASSIVE)); fsm.shutdown(); } diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStatePassiveTest.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStatePassiveTest.java index 711db028..9ecabbe8 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStatePassiveTest.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStatePassiveTest.java @@ -21,8 +21,6 @@ package org.onap.policy.drools.lifecycle; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -37,7 +35,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; -import org.awaitility.core.ConditionTimeoutException; import org.junit.Before; import org.junit.Test; import org.onap.policy.common.utils.coder.CoderException; @@ -63,7 +60,7 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { @Before public void startPassive() { /* start every test in passive mode */ - fsm = new LifecycleFsm(); + fsm = makeFsmWithPseudoTime(); fsm.setStatusTimerSeconds(15L); simpleStart(); } @@ -78,13 +75,12 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { public void controller() { fsm.start(controllerSupport.getController()); assertSame(controllerSupport.getController(), - fsm.getController(new ToscaPolicyTypeIdentifier(ControllerSupport.POLICY_TYPE, - ControllerSupport.POLICY_TYPE_VERSION))); + fsm.getController(new ToscaPolicyTypeIdentifier(ControllerSupport.POLICY_TYPE, + ControllerSupport.POLICY_TYPE_VERSION))); fsm.stop(controllerSupport.getController()); - assertNull(fsm.getController( - new ToscaPolicyTypeIdentifier(ControllerSupport.POLICY_TYPE, - ControllerSupport.POLICY_TYPE_VERSION))); + assertNull(fsm.getController(new ToscaPolicyTypeIdentifier(ControllerSupport.POLICY_TYPE, + ControllerSupport.POLICY_TYPE_VERSION))); fsm.shutdown(); } @@ -109,8 +105,7 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { } String[] events = fsm.client.getSink().getRecentEvents(); - PdpStatus status = - new StandardCoder().decode(events[events.length - 1], PdpStatus.class); + PdpStatus status = new StandardCoder().decode(events[events.length - 1], PdpStatus.class); return status.getMessageName() == PdpMessageType.PDP_STATUS && state == status.getState(); }; @@ -133,7 +128,7 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { } @Test - public void shutdown() throws CoderException { + public void shutdown() throws Exception { simpleStop(); fsm.shutdown(); @@ -147,22 +142,14 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { } private void status(PdpState state) { - await() - .atMost(5, TimeUnit.SECONDS) - .until(isStatus(state, 1)); + waitUntil(5, TimeUnit.SECONDS, isStatus(state, 1)); - await() - .atMost(fsm.statusTimerSeconds + 2, TimeUnit.SECONDS) - .until(isStatus(state, 2)); + waitUntil(fsm.statusTimerSeconds + 2, TimeUnit.SECONDS, isStatus(state, 2)); - await() - .atMost(fsm.statusTimerSeconds + 2, TimeUnit.SECONDS) - .until(isStatus(state, 3)); + waitUntil(fsm.statusTimerSeconds + 2, TimeUnit.SECONDS, isStatus(state, 3)); assertTrue(fsm.status()); - await() - .atMost(200, TimeUnit.MILLISECONDS) - .until(isStatus(state, 4)); + waitUntil(200, TimeUnit.MILLISECONDS, isStatus(state, 4)); } @Test @@ -182,8 +169,8 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { assertTrue(fsm.update(update)); int qlength = fsm.client.getSink().getRecentEvents().length; - PdpStatus lastStatus = new StandardCoder() - .decode(fsm.client.getSink().getRecentEvents()[qlength - 1], PdpStatus.class); + PdpStatus lastStatus = new StandardCoder().decode(fsm.client.getSink().getRecentEvents()[qlength - 1], + PdpStatus.class); assertEquals(update.getRequestId(), lastStatus.getRequestId()); assertEquals(update.getRequestId(), lastStatus.getResponse().getResponseTo()); @@ -193,8 +180,8 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { assertEquals("z", fsm.getSubgroup()); assertBasicPassive(); - String rawPolicy = - new String(Files.readAllBytes(Paths.get("src/test/resources/tosca-policy-operational-restart.json"))); + String rawPolicy = new String( + Files.readAllBytes(Paths.get("src/test/resources/tosca-policy-operational-restart.json"))); ToscaPolicy toscaPolicy = new StandardCoder().decode(rawPolicy, ToscaPolicy.class); update.setPolicies(Arrays.asList(toscaPolicy)); @@ -287,8 +274,8 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { update.setPdpGroup("A"); update.setPdpSubgroup("a"); - String rawPolicy = - new String(Files.readAllBytes(Paths.get("src/test/resources/tosca-policy-operational-restart.json"))); + String rawPolicy = new String( + Files.readAllBytes(Paths.get("src/test/resources/tosca-policy-operational-restart.json"))); ToscaPolicy toscaPolicy = new StandardCoder().decode(rawPolicy, ToscaPolicy.class); update.setPolicies(Arrays.asList(toscaPolicy)); @@ -315,9 +302,7 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { assertEquals("A", fsm.getGroup()); assertEquals("a", fsm.getSubgroup()); - await() - .atMost(5, TimeUnit.SECONDS) - .until(() -> controllerSupport.getController().getDrools().factCount("junits") == 1); + waitUntil(5, TimeUnit.SECONDS, () -> controllerSupport.getController().getDrools().factCount("junits") == 1); assertTrue(controllerSupport.getController().getDrools().delete(ToscaPolicy.class)); assertEquals(0, controllerSupport.getController().getDrools().factCount("junits")); @@ -331,24 +316,24 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest { assertFalse(fsm.state.isAlive()); } - private void assertExtendedTerminated() throws CoderException { + private void assertExtendedTerminated() throws Exception { assertBasicTerminated(); assertTrue(fsm.statusTask.isCancelled()); assertTrue(fsm.statusTask.isDone()); + // verify there are no outstanding tasks that might change the state + assertTrue(time.isEmpty()); + + assertFalse(fsm.client.getSink().isAlive()); + String[] events = fsm.client.getSink().getRecentEvents(); - PdpStatus status = - new StandardCoder().decode(events[events.length - 1], PdpStatus.class); + PdpStatus status = new StandardCoder().decode(events[events.length - 1], PdpStatus.class); assertEquals("drools", status.getPdpType()); assertEquals(PdpState.TERMINATED, status.getState()); assertEquals(PdpHealthStatus.HEALTHY, status.getHealthy()); assertEquals(NetworkUtil.getHostname(), status.getName()); assertEquals(fsm.getName(), status.getName()); assertEquals(PdpMessageType.PDP_STATUS, status.getMessageName()); - - assertThatThrownBy( () -> await() - .atMost(2 * fsm.statusTimerSeconds, TimeUnit.SECONDS) - .until(isStatus(PdpState.TERMINATED, events.length))).isInstanceOf(ConditionTimeoutException.class); } private void assertBasicPassive() { diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateRunningTest.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateRunningTest.java index 8ac47e55..b5b59767 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateRunningTest.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateRunningTest.java @@ -23,8 +23,13 @@ package org.onap.policy.drools.lifecycle; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.concurrent.Callable; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; +import org.onap.policy.common.utils.time.PseudoScheduledExecutorService; +import org.onap.policy.common.utils.time.TestTimeMulti; import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.utils.logging.LoggerUtil; @@ -32,6 +37,7 @@ public abstract class LifecycleStateRunningTest { private static final String CONTROLLER_NAME = "lifecycle"; protected static ControllerSupport controllerSupport = new ControllerSupport(CONTROLLER_NAME); + protected TestTimeMulti time; protected LifecycleFsm fsm; /** @@ -59,4 +65,23 @@ public abstract class LifecycleStateRunningTest { } SystemPersistenceConstants.getManager().setConfigurationDir(null); } + + /** + * Creates an FSM that uses pseudo time. + * @return a new FSM + */ + public LifecycleFsm makeFsmWithPseudoTime() { + time = new TestTimeMulti(); + + return new LifecycleFsm() { + @Override + protected ScheduledExecutorService makeExecutor() { + return new PseudoScheduledExecutorService(time); + } + }; + } + + public void waitUntil(long twait, TimeUnit units, Callable<Boolean> condition) { + time.waitUntil(twait, units, condition); + } } |